# Question
Title: Thoughts on customizing the user profile page?
I'm looking to really transform the user profile page for my drupal 7 site and community into something enganging and interative. Perhaps a friends block, list of social media links like fb, linked in, etc as well as to be able to see new posts and comments that that user has contributed to the site.

Certainly we can do better than the default drupal page these days!

What modules do you recommend to start putting together a recipe for a quality and informative user profile experience?

Also, does you have any links for tutorials that would be good resources? Perhaps even a cool profile page you have done as an example.

# Answer
> 1 votes
I think the two key modules for this would be Views and Panels. That should get you most of the way but, depending on what you want to display, you may need some other modules.

---
Tags: 7, users
---


title: FAPI #required and hook_form_validate ?

text:
# Question
Title: FAPI #required and hook_form_validate ?
I made a custom form using FAPI (Drupal 7), with '#required' attribute in some form elements. Besides this, I use hook\_form\_validate() to check some business rules.

The point is at first submission, required fields appears red-bordered, but still no error message.

On second submit, the error messages appear with both required and business rules .

Is there a way, to have the second behaviour on first attempt ?

Thank you.

# Answer
For those interested, the solution proposed by Clive did not work any better. Thanks to him anyway !

I found out a workaround, by adding this in my \*.module :

```
    /**
     * Implements hook_node_view
     */
    function MY_MODULE_node_view($node, $view_mode, $langcode) {
      if($node->type =='SOME_TYPE'){
          $node->content['order_form'] = drupal_get_form('order_form');
      }
    }

```

This way, the form is output correctly to the page, without further ado, and the validation messages appears right on time.
> 1 votes

# Answer
This behaviour is usually caused by the form being rendered too late in the page build process (for example by calling `echo render(drupal_get_form('form_id'));` directly in a template file).

By the time the form submits, the session messages have already been prepared for rendering, and so when more messages are added by your form's validation, they don't display until the next page load.

Without knowing exactly where you're rendering/preparing the form is hard to offer advice on how to fix it. I think it would suffice to say that if you're rendering the form directly in a template file, you should move it to a preprocess function at least.

The better way would be to prepare and render the form at the module level, rather than the theme level, as that will be processed early enough in the page load for this problem to disappear.

To address your comment:

I think the problem is definitely where you're calling the form building function from. You should be able to just take that code and put in a preprocess function, preferably in a module file as that pretty much guarantees the call won't come too late:

```
function MYMODULE_preprocess_page(&$vars) {
  if ($_GET['q'] == 'some/path') {
    $vars['the_form'] = module_invoke('my_module', 'block_view', 0);
  }
}

```

Then just print it if it's available in page.tpl.php:

```
<?php if ($the_form): echo $the_form; endif; ?>

```
> 2 votes

---
Tags: forms
---


# Question
Title: Assigning a page title to forms created with the form API FAPI
I have a moule called newsl witch display a page containing a form. I would like the way to specify the page title. Is it with drupal\_set\_title() ? How to call it ?

# Answer
if your page url http://site.com/my\_page

you can use

```
function hook_page_alter(&$page)
{

    if(arg(0)=="my_page")
    {
                 drupal_set_title("Ahmed");
    }
}

```
> 0 votes

---
Tags: 7
---


title: building a complex frontpage

text:
# Question
Title: building a complex frontpage
I've built all my site apart from the frontpage which right now shows:

```
No front page content has been created yet.

```

The frontpage will be the most complex page of all, containing a lot of boxes (blocks) which will be presenting lists of items.

I've got 2 solutions for this problem and I'd like to know which one is best.

**solution 1 - blocks**

* create the ~10 blocks that the frontpage needs
* make them translatable
* use description prefix "front -" for easier identification in `admin/structure/block`
* configure "Only the listed pages": `<front>`
* somehow remove the "No front page content has been created yet" message

This solution seems very tunable. The CM will be able to do whatever he wants with the individual view blocks of the frontpage. On the other hand there will be too many blocks in the administration page (but only 1 for all languages).

**solution 2 - node**

* create a node
* the node should be of a type which has fields for configuring the fetching and displaying of items. e.g fields:
    + int: number of news to fetch
    + int: number of events to fetch
    + bool: should display teaser
    + html: teaser content
    + etc
* in `admin/config/system/site-information` set that node as Default frontpage

The drawback of this is that I should implement the fetching and display, and if the CM wants to change something that the content type does not support I'll need to implement it. On the other hand I'll have full flexibility in HTML if I provide a separate template just for this content type.

So, is there a definite winner between those 2? Also note that, for various reasons, I don't want to use `panels`.

# Answer
> 5 votes
I know you said you didn't want to use it, but this is a PERFECT use case for Panels. I'm not a huge Panels user and will generally steer clear of it if I can, but sometimes you have to step outside of your comfort zone and just use the best tool for the job.

There's a video here that focuses on using Views and Panels for a home page layout.

> In this Drupal video tutorial we take a brief look at panels. I show you how to recreate a home page that relies on views content panes. As a result, we create a two column home page panel which pulls in recent content from across all content types and shows which users are online.

But if you are REALLY set in your ways, then go with the blocks. You can always put the blocks into Panels at a later date.

# Answer
> 2 votes
I have done this with blocks before, you can create a template file called page--front.tpl.php and do whatever you want there. Then make use of functions like views\_embed\_view to embed a view:

```
<?php print views_embed_view('case_studies','block_1'); ?>

```

Or use a block:

```
<?php print module_invoke('search', 'block_view', 'search'); ?>

```

My current project has a dynamic page calling all sorts of content elements and I am doing it with panels this time, consider using it.

---
Tags: 7, nodes
---


title: Exposing inline images to Views

text:
# Question
Title: Exposing inline images to Views
I'm using Media module to insert inline images in the nodes body through the wysiwyg.

I'm trying to make an Views slideshow to list all these images and I've been banging my head at Views interface for the past hours, trying to find the related field which should be included but I can't find anything.

Is this simply not possible? If that's the case is there any Views plugin/add-on that can do the job?

Regards

# Answer
If an image is inserted into a textarea like your wysiwyg editor, the node does not retain an entity relationship with that image, you would need to parse the full content of that field for images, figure out if they are internal, get their ID...

Your node should ideally have a field of type image, that way your saved node has an association with one or more images you have uploaded. You can then insert the images inline wherever you wish.
> 3 votes

---
Tags: views, wysiwyg, media
---


# Question
Title: file upload broken on node form on custom page
> **Possible Duplicate:**
> D7 Image field upload errors with custom node\_add() form

I have a custom page with a node form on it. The problem is that when I try to upload an image I get lots of errors.

The code is like this:

```
module_load_include('inc', 'node', 'node.pages');
$output = drupal_render(node_add('node_type'));
return $output;

```

Some of the errors I get are:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of E:\work\my_site\includes\form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1193 of E:\work\my_site\modules\comment\comment.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of E:\work\my_site\modules\menu\menu.module).

```

The funny thing is that if I return the form array everything works well.

```
module_load_include('inc', 'node', 'node.pages');
$output = node_add('node_type');
return $output;

```

Unfortunately this doesn't help me at all.

This is the same problem as in here but the solution there is not an option for me.

Any ideas? Thanks

# Answer
> 7 votes
Yeah, apparently you should add these line to the menu item array:

```
'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

```

it is not enough to just add `module_load_include('inc', 'node', 'node.pages');` before printing the form.

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


title: PDF Reader module not displaying pdf

text:
# Question
Title: PDF Reader module not displaying pdf
I'm using the PDF Reader module to try to display a pdf file. Ideally I'll use the Goolge Viewer, but as of right now none of the displayers display my pdf.

My pdf file is set to full chmod 777 as well as the directory containing it (site/default/files/), for testing purposes only right now just to make sure the error wasn't due to permissions.

Here is screenshot of what I'm seeing -

I can click the 'try downloading the file here' link and view/save the file.

Any ideas?

EDIT: The screenshot is from a dev server connected to the internet.

# Answer
> 3 votes
You should test this module on the live site, but not on the localhost. If you are testing on localhost, Google Docs Viewer will not be able to access in the PDF document and can't show it, but you can download it from local server.

---
Tags: files
---


# Question
Title: How to make a link in calendar module to current date?
Here is another calendar related question: I want to create a link-item that links to a view that filters events to the current date. Easy, you say?

Right now i have a mini-calendar block that show the current month and a view (type page) for events that has a contextual filter: **Date: Date (node)**. It provides the default value **Current Date** if the filter value is not in the URL.

This works fine. The view shows the events for the current date when the /events page with the view is visited for the first time (no filter value in URL).

So, if the mini-block with the month view is used, it shows the events of that day accordingly. But if someone cycles through the months and wants to go back to show events of today he has to click back to the current month and date to show them.

Now i want a link-item that links to the current date view as a kind of shortcut, visible on all event-views, but i have no idea how to do that.

Right now i have my view duplicated, with an own path (/eventstoday) and a block with the link to that view, shown on event-view pages.

But there must be a way to achieve this with only one view...

Any help would be appreciated... and thanks for reading!

**EDIT:**

Additional Information about settings used: I use Ajax in the views and also the calendar configuration option: "Track current date in session" for all users.

> Store session information about the user's current date as they move back and forth through the calendar. Without this setting users will revert to the current day each time they choose a new calendar period (year, month, week, or day). With this option set they will move to a day that conforms to the time period they were viewing before they switched. Requires session tracking which is not ordinarily enabled for anonymous users.

I use Drupal 7.14 and the latest development-snapshots of calendar, date, ctools and views.

# Answer
> 4 votes
```
<a href="event/<?php print format_date(time(), 'custom', 'd f y'); ?>">Event of today</a>

```

Do something like this in the calendar theme. Change the path and the format API and put it in one of the tpl.php file of the calendar.

Or just put a link on the tpl.php, pointing to the default view without date on the url

```
<a href="event">Event of today</a>

```

Where do you want to put it?

# Answer
> 0 votes
Create a view having in a field whatever you have taken for the Calendar module. Then use "Rewrite result" in the view to create a link.

# Answer
> 0 votes
You can just do that by adding the static link into the footer area of the view. To have it work on all URLs that display your view use:

```
<a href="/event">Today's events</a>

```

No need to use a block or a second view.

---
Tags: 7, views, datetime
---


# Question
Title: Boosting by changing bias of ApacheSOLR has no effect
I am trying to understand the content-biasing. Somehow it has no effect on our installation.

Stepping through the code learns me that the query-string did change: the modified boost values like `&bq=type:audio^1.0` show up, but have no effect on the search-results' sort-ordering or the $result\["score"\] value. the score remains exactly the same, no matter how high or low a bias is set.

Could it be cached somewhere on the solr server? (clear cache has no effect, code does not hint at caching it). Is this a known bug? Or an issue with the `schema.xml`?

Update: Enabling debugQuery=on shows me an explain:

```
1.7849035 = (MATCH) fieldWeight(body:assen in 1952), product of:
  1.0 = tf(termFreq(body:assen)=1)
  4.0797796 = idf(docFreq=900, maxDocs=19600)
  0.4375 = fieldNorm(field=body, doc=1952)
","eskrkz/node/4622":"
1.1041226 = (MATCH) fieldWeight(body:assen in 1682), product of:
  1.7320508 = tf(termFreq(body:assen)=3)
  4.0797796 = idf(docFreq=900, maxDocs=19600)
  0.15625 = fieldNorm(field=body, doc=1682)
","eskrkz/node/8881":"

```

The field=body worries me. Why does it only search in body? Why not just any text? And why

An example querystring:

`&fl=id%2Cnid%2Ctitle%2Ccomment_count%2Ctype%2Ccreated%2Cchanged%2Cscore%2Cpath%2Curl%2Cuid%2Cname&rows=10&facet=true&facet.mincount=1&facet.sort=true&facet.field=type&facet.limit=20&qf=body%5E40&qf=ts_vid_2_names%5E0.5&qf=tags_h2_h3%5E3.0&qf=taxonomy_names%5E0.5&qf=ts_vid_3_names%5E0.5&qf=title%5E5.0&qf=ts_vid_1_names%5E8.0&qf=tags_inline%5E1.0&bq=type%3Aimage%5E0.1&bq=type%3Aaudio%5E1.0&bq=type%3Adoc%5E0.1&bq=type%3Adossier%5E8.0&bq=type%3Aarticle%5E13.0&bq=type%3Apage%5E2.0&bq=type%3Aprogram%5E8.0&bq=type%3Asubsite%5E8.0&bq=type%3Avideo%5E0.3&start=0&wt=json&json.nl=map&q=FOO"`

# Answer
Turns out the `solrconfig.xml` for Drupal was not properly installed on the SOLR server. Which made it unable to parse the querystring properl with DisMax.
> 0 votes

---
Tags: 6, search
---


title: hide module when path is overlay

text:
# Question
Title: hide module when path is overlay
Im developing a module which shows a bar (fixed, top, z-index 99999) with some content. **When im in the admin interface with overlay, I want to hide the module**, right now the bar is overlapping the overlay.

This code is working well if the overlay is not activated

```
if (arg(0) == 'admin' || arg(0) == '#overlay=admin') { $output = NULL; }

```

only the `arg(0) == '#overlay=admin'` part is not working,

any ideas?

Thanks in advance

# Answer
> 2 votes
You should use the following code, if you want to avoid outputting something when the overlay is visualized.

```
if (module_exists('overlay') && path_is_admin($_GET['q'])) {
  // The overlay is visualized.
}

```

`path_is_admin()` is used from overlay\_init(), which contains the following code.

```
  // If this page shouldn't be rendered inside the overlay, redirect to the
  // parent.
  elseif (!path_is_admin($current_path)) {
    overlay_close_dialog($current_path, array('query' => drupal_get_query_parameters(NULL, array('q', 'render'))));
  }

```

# Answer
> 1 votes
Could you not just hide your bar with CSS when the Overlay?

Say for example the parent ID of your bar is `#my-admin-bar` just write the following in a `mymodule.css` file:

```
body.overlay #my-admin-bar {
  display: none;
}

```

Then include the `mymodule.css` file in your module's `.info` file.

You could also take a look at `overlay_get_mode()` which checks the current overlay mode (child, parent or none).

This is completely untested, and may not do even nearly what I think it should do but here goes:

```
//Check if the overlay module is active first otherwise the
// overlay_get_mode() function won't be available and you'll get a WSOD
if (module_exists('overlay')){
  //Get the current path
  $current_path = current_path();
  //Get the overlay mode
  $overlay_mode = overlay_get_mode();
  //This bit should be self-explanatory
  if (path_is_admin($current_path) && $overlay_mode != 'none') {
    //The overlay is active and you are on an admin page!
  }
}

```

Function documentation:

`module_exists()`

`current_path()`

`path_is_admin()`

`overlay_get_mode()` (FYI: this is just a wrapper for `overlay_set_mode()`)

# Answer
> 0 votes
I think the easiest way would be to check whether the overlay module is enabled, and just test the URL for the current page request to see if it contains 'admin'. If the overlay is enabled, by default all paths that start with 'admin' will automatically bring up the overlay so this should work (I haven't tested it though):

```
if (module_exists('overlay') && arg(0) == 'admin') {
  // ...
}

```

Note that this won't work for pages that open in the overlay without 'admin' in the path (e.g. node/add). If you want to do the same for those, you'll probably need to invoke `hook_admin_paths()` to get a list of pages and then test the current URL against those as well.

---
Tags: modal-dialogs, users
---


# Question
Title: Using git over ssh from localhost to my Shared Hosting
I managed to install smoothly git and drush on my Shared Hosting. Cool. Now I created there a git repository:

```
$cd public_html/drupal
$drush dl drupal
$git init
$git add .
$git commit -a -m "My Project"

```

A .git folder has been created

Now all I am trying to do is to clone my remotely Drupal installation on my local computers home or whatever:

```
git clone ssh://username@*.*.*.*:portnumber/public_html/drupal

```

it connects well I enter the password but then I got the message: fatal: /public\_html/drupal does not appear to be a git repository fatal: The remote end hung up unexpectedly

What did I do wrong? All I need is to use git (somehow as svn) as versioning. I don't need to post the project on github as it is a private one.

Help appreciated

# Answer
> 0 votes
Perhaps you are looking for

```
git clone ssh://username@63.23.133.162:portnumber/~/public_html/drupal

```

Note the `~` which is indicating that the public\_html resides in your home directory.

---
Tags: version-control
---


# Question
Title: How can I use the administration theme for the user/%/edit page?
How can I get the *user/%/edit* page to use the admin theme that is used for the rest of the site?

# Answer
That path is already one that will use the admin theme *if* the current user has the correct permissions to access it.

Try going to http://mysite.com/admin/people/permissions and checking the "View the administration theme" permission for the roles you wish to be able to use the admin theme.

It'll definitely work as the User module implements `hook_admin_paths()` to define that path as an admin page:

```
function user_admin_paths() {
  $paths = array(
    'user/*/cancel' => TRUE,
    'user/*/edit' => TRUE,
    'user/*/edit/*' => TRUE,
  );
  return $paths;
}

```
> 5 votes

---
Tags: 7, theming
---


# Question
Title: How to allow content editors to choose from Image Styles during content creation?
Say I have an image field and several different Image Styles (image cache presets) set up. I would like to allow my content editors to be able to choose from the list of available presets during content creation.

Any Ideas on this is achieved? Off the top of my head it seems like a custom module might be in order...

# Answer
Luckily enough there's already a module that does exactly this, Formatter Field. The example use case given on the module page is exactly the same as yours:

> The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
>
> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.
> 2 votes

---
Tags: media, nodes
---


# Question
Title: Accessing taxonomy custom field values (Drupal 7)?
I've added a new vocabulary to Taxonomy, and then proceeded to add several custom fields to that new vocabulary. In the taxonomy\_term\_data table, I see the values for the tid, vid, name, description, format, and weight fields. It also looks like there are now a couple of new tables in the database that are related to the new custom fields that I created for the new vocabulary (i.e. field\_data\_field\_taxonomy\_cip\_code). The values in the new table are entity\_type, bundle, deleted, entity\_id, revision\_id, language, delta, field\_taxonomy\_cip\_code\_value, and field\_taxonomy\_cip\_code\_format. There's nothing that I can see on the surface that would allow me to relate the two tables together.

How would I go about pulling the additional custom field values along with the new vocabulary values?

# Answer
> 0 votes
If I understand your question, taxonomy\_term\_data.tid should relate to like field\_taxonomy\_cip\_code\_value.entity\_id. In Drupal 7 Taxonomy terms are now entities.

Entity Ids and Bundle values in the database aer typically the database keys used to relate "fields" between tables (as drupal "Fields" can be reused across multiple bundles).

# Answer
> 8 votes
If you load the taxonomy term with taxonomy\_term\_load(), you will get any custom field you added to the vocabulary.

I created a vocabulary to which I add a boolean field (field\_test\_boolean); I added a taxonomy term to that vocabulary, and then executed the following code. (22 is the taxonomy term ID for the taxonomy term I created.)

```
$taxonomy_term = taxonomy_term_load(22);
dsm($taxonomy_term);

```

The output shown by `dsm()` is the following one.

If you want to get the field value for the language currently set for the field, you should use the following code.

```
$values = field_get_items('taxonomy_term', $taxonomy_term, 'field_test_boolean');

```

If you need to find the taxonomy terms for which the custom field contains specific values, you should use the EntityFieldQuery class.

```
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', 'fields_test')
    ->fieldCondition('field_test_boolean', 'value', 1, '=')
    ->execute();

  if (!empty($entities['taxonomy_term'])) {
    $taxonomy_terms = taxonomy_term_load_multiple(array_keys($entities['taxonomy_term']));
  }

```

### Note

As noticed in a comment, there is a bug that doesn't allow to use the `EntityFieldQuery` class for taxonomy terms. The code seems fixed in the Drupal 7 development snapshot, but Drupal 7.14 is affected by the bug.

# Answer
> 0 votes
@kiamlaluno is right. And thereby you can join the fields to its entity in the database with:

```
SELECT td.* FROM taxonomy_term_data td
INNER JOIN field_data_field_taxonomy_cip_code f ON f.entity_id = td.tid AND f.entity_type = 'taxonomy_term'

```

Taxonomy terms are entities and their tid is their entity\_id and the entity\_type is taxonomy\_term.

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


# Question
Title: Recoverable fatal error on nodes after leaving Maintenance mode
Our site was in maintenance mode for several days, and when we came out of maintenance mode a bunch (we don't know how many) of our nodes display this error:

> Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase-\>execute() (line 2136 of includes/database/database.inc).

This error can be found on this page -\> http://www.relevantmagazine.com/node/109771 we are able to edit and save the node, but nothing we change fixes the issue.

Any ideas?

# Answer
You probably included an object as an argument to one of your query conditions. If you print\_r the $args at the line number in the database.inc file, you find out what the placeholders are set to.
> 2 votes

# Answer
This error has been discussed here.

> Update: Systematically unchecked all modules, then went and rechecked sections at a time.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How can I export node data the same way you do webform data?
We had previously used webform to collect data and our "power users" got used to being able to export the submissions to Excel easily. For various reasons, we've switched from webform to a custom content type. Is there a module out there (or maybe a module isn't even necessary) that would let these users (who do NOT have access to the admin functions of the site) to do the same kind of exporting of nodes?

# Answer
> 3 votes
Use the Views data export module.

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV
> * Microsoft XLS (or really simple HTML understood by Excel)
> * Microsoft DOC
> * Basic TXT
> * XML

---
Tags: 7, importing-exporting
---


# Question
Title: Does db_query and db_insert escape input values? prevent sql injection?
I've been reading through the documentation, but I feel like it's always a little bit vague on this, perhaps I'm missing something.

```
function foomodule_my_hook_menu_callback($unescapedUserInputString) {
    $sql = "select name from {foo_table} where bar=:inputString";
    $result = db_query($sql, array(':inputString' => $unescapedUserInputString));
}

```

Is the above code vulnerable to an SQL injection attack? Or will `:inputString` get appropriately escaped to make it safe for SQL? (I know I need to sanitize it for proper values in my implementation, but I'm just referring to the SQL safety)

What about with db\_insert()?

```
$insert_id = db_insert('foo_table')
                ->fields(array(
                    'name' => $unescapedUserInputString,
                ))
                ->execute();

```

# Answer
> 4 votes
these functions are abstractions on top of php's PDO library. They are essentially `prepared sql statements` ... passed values to the query are safe from SQL-injection.

Feel free to jump into the PHP PDO Manual.

EDIT:

eg,

> Many of the more mature databases support the concept of prepared statements. What are they? They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
>
> The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
>
> The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

---
Tags: 7, database
---


# Question
Title: CPU spike during image multiupload — how to optimize performance?
I have an image gallery that allows users to upload a huge number of images at a time (this was a project requirement) and when an upload happens, the server's reported CPU usage spikes to 1000%. What modules, settings, or other modifications can be used to ease the load on the server or throttle the image processing (without delaying the loading of the next page so users don't think it's hanging)?

# Answer
> 1 votes
More than likely, the CPU spike is actually happening after the upload and the new gallery is being viewed.

When this happens, each of the new images will be loaded by the browser. Drupal will detect that these images don't exist on the filesystem, and punt to Image module to render out the derivatives that you defined (ie, the images in each style). If the user bulk uploaded a bunch of images, then the server may be rendering out a lot of new images in parallel.

To combat the CPU, you can try enforcing smaller max image dimensions. Smaller images take less CPU to crop/scale/etc.

You can look through the MPM configuration options and see if there is anything you cal tweak. `ServerLimit` may be your only option here; I don't recall per-client option in Apache for maximum parallel connections.

Otherwise, I think you may be better served on ServerFault for this issue.

---
Tags: 7, media, performance
---


title: Using slashes in drupal path parameters

text:
# Question
Title: Using slashes in drupal path parameters
I'm working on my first module. I'm setting up `hook_menu()` to register several URLs. Some of the parameters may be raw strings with slashes in them. For example, "Round 1 / Heat 1" as one parameter. Now, I know that I can make my javascript encode the slashes when constructing the URL, but it makes me wonder if I'm Doing It Wrong™.

It feel natural to me to be able to use GET params, but I don't see any way to access those in menu callbacks.

Am I doing It wrong with these URL-based parameters?
Is it possible to just POST these parameters, and access them in menu callbacks?

# Answer
> 4 votes
There's one additional trick additionally to the options that you already listed. If you look at search\_menu(), you can see that it uses a named placeholder called %menu\_tail and this: `'load arguments' => array('%map', '%index'),`.

This does exactly what the name suggests. It calls menu\_tail\_load() (and passed it's own index/position to it as a load argument), which doesn't actually load anything but takes all additional path elements including it's own position, and returns them as a single argument.

Obviously, this only works for the last argument. If you have multiple arguments like this, use GET/POST variables or escape them.

# Answer
> 1 votes
You could access the parameters in `hook_menu()`. Try the following code.

```
function menufun_menu() {
  $items['menufun/%/bar/baz'] = array(
    'title' => 'Hi',
    'page callback' => 'menufun_hello',
    'page arguments' => array(1), // The matched wildcard.
    'access callback' => TRUE,
  );

  return $items;
}

/*
 * Page callback.
 */
function menufun_hello($a = NULL) {
  return t('Hello. $a is @a', array('@a' => $a));
}

```

---
Tags: 7, hooks, routes
---


# Question
Title: Change the default selection for a Views 2 exposed filter
I have an exposed filter in my View that allows users to choose between two different content types. The default value for the exposed filter seems to be chosen by whichever content type comes first alphabetically. So, if I let users choose between "Band" and "Song" content types, the default is "Band". I want to change this default value to a different content type ("Song" in the example here). I can't find an option in the Views interface for this. Do I have to do this via `hook_form_alter`? If so, how exactly would I do that?

# Answer
> 5 votes
So, I tried the way that @David Lanier suggested, but couldn't quite wrap my head around it. So I went back to Drupal basics and tried it from the `hook_form_alter()` approach. After some troubleshooting, I also found a post about changing default Views filter values. I took the same approach and got it working. Below is the code a used, with a couple of modifications to take out my site-specific stuff. As always, be sure to replace "modulename" with the name of your module.

```
function modulename_form_alter(&$form, $form_state, $form_id) {
 // is this the right form?
 if($form['#id'] == 'name-of-the-views-form-displayed') {
   if (empty($_GET['label-of-the-filter']))  {
    $form_state['input']['label-of-the-filter'] = 'default-value-for-filter';
   }
  }
}

```

Just replace `name-of-the-views-form-displayed` with, you guessed, the name of the views form you want to change. The easiest way to find this is to inspect the source of the View in the browser (I love Firebug for this) and find the `form` element, then grab it's `id` attribute. To find the name of the filter and the value you should set, change the filters and perform the "search". Look in the address bar and you'll see the values you need to use here as parameters in the url.

Hope this helps get others around this issue too!

# Answer
> 2 votes
I did this way

```
function hook_form_views_exposed_form_alter(&$form, &$form_state) {

  global $user;
  $account = user_load($user->uid);
  $term = taxonomy_term_load($account->field_user_industry[LANGUAGE_NONE]['0']['tid']);

  unset($form['field_event_industry_tid']['#size']);
  if ($form['#id'] == 'views-exposed-form-events-events-pane') {
    // get the view argument if defined
    $term_filter=$_GET;
    unset($term_filter['q']);
    $term_arg = $term_filter;
    if (!empty($term_arg)) {
      $terms = $term_arg;
    }

    // change our input as required
    if (isset($terms)) {
      $form_state['input']['field_event_industry_tid'] = $terms['field_event_industry_tid'];
    }
    else{
      $form_state['input']['field_event_industry_tid'] = $term->tid;
    }
  }
}

```

In my case I had to change the default value according to the query, but if it isn't, I use the value I want, this way works perfectly!

# Answer
> 1 votes
Once the filter is exposed, in the configuration options for the filter, you should see checkboxes for each of the content types in your site. The ones that you check here are the ones that are selected by default when an end user sees the view.

If you need only some of your content types to be available in the form, and only some of those pre-selected, you'll need to do something like this: Add two content type filters:

* Filter 1 = only the content types that should be available. Don't expose this filter.
* Filter 2 = the exposed filter. Select the ones here that should be pre-selected by default.

# Answer
> 1 votes
Maybe you already got the answer, but here is how I solved. If you edit the Filter in the View, there's an option called "**Limit list to selected items**". I checked that option, and the Default Value was reset, so now the Default Value of the filter is All (with the tag Any).

# Answer
> 0 votes
See the bottom of the post at:

http://realguess.net/node/28

> If you don't select any of choices under Client Gender, and check the Optional This exposed filter is optional and will have added options to allow it not to be set. box, then will be the default choice. If you select Male item, then your default selection will Male when the view is being rendered.

---
Tags: views
---


# Question
Title: How to theme the $item in views-view-grid.tpl.php
I'm just beginning to learn theming Drupal 7, and have encountered something I can't seem to find any info on (and my experiments have no effect).

In tao/rubik theme, and in many others there is the views-view-grid.tpl.php template which arranges the resulting items from a view in a grid design.

Now, at the very end, after splitting into rows and columns there is a print $item which is the section that prints the actual node content/teaser in the grid square. I'm assuming the content is a node, since this is what I set the view block to display, also I set it to display the full content of that single node.

However, no matter what I do, I can't seem to modify the template of this node... how should the template be called? should it be placed somewhere special?

What am I missing?

# Answer
> 1 votes
If you are asking how to theme the display of a node, those templates have names like node.tpl.php, node--NID.tpl.php, node--TYPE.tpl.php, etc. Lots of information on templates can be found here

---
Tags: 7, theming
---


# Question
Title: Views throw an Ajax error in the admin page
When I go to a View edit page in the admin of Drupal 7, two of them (one that's called front page and was already there, and one that's a jcarousel) throw an error:

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/view/frontpagecarousel/preview/page/ajax
StatusText: error
ResponseText:

```

"ResponseText" is followed by a huge load of unformatted text (not even a newline character). But I believe that it must have something to do with the "Path", which I don't believe exists. I'm not certain, but I think this is interfering with jCarousel's options, as it expects something to appear in the Fields section, but the Fields section says "The selected style or row format does not utilize fields."

So, what's going wrong, and how can I fix it?

# Answer
I've had this problem many times before. For me, it was because I had the `theme developer` module enabled. I think the `firebug` module has the same effect. Basically, they are both adding extra markup to the response text and it isn't able to parse it then.
> 1 votes

---
Tags: 7, views
---


# Question
Title: BLOCK_NO_CACHE with Normal page cache enabled
I'm trying to create a block, which shouldn't get cached, even for anonymous users. But there's "Normal" page caching enabled on the website. As I've read in various places, the BLOCK\_NO\_CACHE setting doesn't really count for anonymous users when page caching is enabled.

As it stands, it's not an option for me to turn off the page caching, as the website receives moderately high traffic.

I've first tried injecting some HTML with `hook_footer` but this function doesn't get called as well when page caching is enabled.

The block I'm trying to implement is a very simple one, it only has a bit of text and a link, which upon clicking, sets a cookie on the user's browser (with PHP), and returns the user back to the page where they clicked the link on. Upon returning to the page, the block needs to attempt to read the cookie, and if the cookie is set, the block should no longer be displayed.

However with page caching turned on, if AnonymousUser-A clicks the link and no longer sees the block, then AnonymousUser-B comes to the site, they also don't see the block.

**Is there a workaround I can use to get around this issue? As you can see from my use of `hook_footer`, I'm not heavily inclined to implement this as a block. Any solution that will fit the above purpose is welcome.**

# Answer
Ajax Blocks or Ajaxify Regions (since you're in D6) allow dynamic blocks within cached pages.
> 2 votes

# Answer
If you want a different example, you can use javascript to read a cookie and hide that blocks div based off of a cookies value. Have the block always be show at the PHP level and use JS to hide it client side.
> 0 votes

---
Tags: 6, blocks, caching
---


# Question
Title: Caching pages for anonymous users prevents other cache logic?
I'm looking to confirm my suspicions as anything but, if I enable caching for anonymous users then any cache logic I've implemented in custom modules, views and blocks is thrown out, is this correct? What I mean is, if I have a block showing some weather information that has a 5 minute cache but I turn on anonymous page caching, the cache logic of my block is never considered.

Is there a way around this?

# Answer
The page cache just takes whatever is generated by the current page, stuffs it into a large string and stores it into the cache. As long as that cache entry is then valid, it is returned and no other code is invoked.

Once the page cache is expired, the page will be regenerated completely and any other element will either be loaded from a specific cache or rebuilt.

If it's important that certain information is kept up to date, all you need to do is make sure that the cache expiration time of the page cache is the same or lower as the one of the relevant block/page/whatever.

There is a concept, called ESI, that basically allows to define placeholders in a page cache string that can be replaced with separate request. However, Drupal 7 doesn't really allow that yet (Drupal 8 will hopefully improve this) but this is for things that actually *are* different based on the user, for example if you have a site that is the same for all users except a single block that is user-specific. Not for something like a weather block that is the same for all users and valid for 5 minutes.
> 4 votes

# Answer
Either of these modules should do the trick for you (quotes included are from their project pages):

* Edge Side Includes integration:

> ... is a high performance caching solution for Authenticated users but can be helpful for Anonymous users as well.
>
> Typically, pages which are personalised for authenticated users (even minor personalisations, such as a block which says "Logged in as manarth") will prevent reverse-proxies (which can easily perform 100 times faster than Drupal) from caching the page, because messages intended for one user could then be seen by another.
* Ajax Blocks

> ... permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user. It is suitable for sites which are mostly static, and the page caching for anonymous users is a great benefit, but there are some pieces of information that have to be dynamic.
> 3 votes

---
Tags: caching
---


title: Easiest way to embed flash in a page?

text:
# Question
Title: Easiest way to embed flash in a page?
I am looking to embed flash in D7 on a simple page. How would I do this?

# Answer
> 1 votes
Or you can create a new text field for embed flash. Be sure that your WYSIWYG filter will allow the embed and object tags.

---
Tags: nodes
---


# Question
Title: Uploading my Drupal Comerce Files to My Web Host
I have installed Drupal Commerce using Kickstart. It is now running on my local server. How to I properly upload and configure it on my Web Host? Any help would be greatly appreciated.

# Answer
> 0 votes
You can use File Transfer tools like WinSCP, FileZilla to transfer you files in your webhost. Then you need to export your database in your local then import in your webhost database. If you have some special configuration like path you may need to update that in your webhost.

1. Create a database creds in your webhost.
2. Export you local database and import it on webhost.
3. Upload your Drupal files
4. Update your settings.php to change the database information.

....

---
Tags: database
---


# Question
Title: Default values not working in multiple select options
I have a form with multiple select options.Other things are working fine. But when I revisit the form I have to select everything again. I have given:

'#default\_value' = *previously selected array()*

But that is not working I guess. Is there any method that the user can add in the selected list without need to select everything again ? Thank you .

# Answer
> 2 votes
check it out - http://drupal.org/node/73077

---
Tags: 7, forms
---


# Question
Title: Drupal 7, show drupal blocks only on specific pages with PHP code?
I were working on drupal 7. In block configuration, under pages i went for an option "Pages on which this PHP code returns TRUE (experts only)"

Added the following code:

```
<?php
global $user;
$username=$user->name;
if($username=="admin")
{
   return TRUE;
}
else
{
  return FALSE;
}
?>

```

It's shows me an error message at the top of the screen:

> Notice: Undefined property: stdClass::$name in eval() (line 3 of C:\xampp\drupal77\modules\php\php.module(75) : eval()'d code).

I don't know, how to fix it out. Please help me out.Thanks

# Answer
How the $username variable's value will be available there? If you want to use current logged in user, write it like `global $user;` and check `$user->name` instead of `$username`.
> 1 votes

# Answer
If I get you right you want to check for the admin user.

A possible code snippet would be:

```
global $user;
return $user->uid==1;

```

Of course you can check for any property of the $user object.
> 0 votes

---
Tags: commerce
---


title: How to add a php to a custom page

text:
# Question
Title: How to add a php to a custom page
Here is what I am trying to do, I have a bookmarklet with the following code

```
javascript:location.href="http://mywebsite.com/getsource?url="+encodeURIComponent(location.href);

```

I want to fill in the url into a field on the page "http://mywebsite.com/getsource"

After asking around a bit, I was provided this piece of code.

```
<input type="text" id="edit-url-field" value="<?php echo $_GET['url']; ?>" />

```

My question is .. how do I implement this in Drupal 7?

# Answer
You need to implement a custom module which defines a form and a path to this form.

In Drupal forms are implemented with the Form API. Please check this links for more information

1. http://drupal.org/node/751826
2. http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7

You can define the path by implementing hook\_menu.
> 1 votes

---
Tags: javascript
---


# Question
Title: How do I add a file upload field to user registration page?
I need to add a file upload field to user profile, during registration. How can I do this?

# Answer
In D7 all entities are field-able, and user profile fields can be manipulated in `admin/config/people/accounts/fields`

and in D6 you can use content profile module
> 1 votes

---
Tags: 7, users, nodes
---


title: Adding comments at content creation?

text:
# Question
Title: Adding comments at content creation?
I'm on D7. I have a content type that I would like users to add comments to WHILE they create it. Basically the content type is a "how to" topic and the comments will be used as different steps to do whatever. Thanks for any suggestions.

# Answer
In this case I'd have a look at the field\_collection module. It may be more suited for your purposes.
> 3 votes

---
Tags: 7, nodes, comments
---


title: Hook block save

text:
# Question
Title: Hook block save
I have to perform certain operations when block configurations are get changed. And I successfully implemented `hook_block_save()` and worked.

But the hook is not called up when we change the 'region' of blocks in page 'admin/structure/block'.

Are there any other methods other than injecting an extra submit handler to the form displayed in 'admin/structure/block' page?

# Answer
The `block_admin_display_form_submit()` function (submit handler for the block admin form) manipulates the region value for the blocks in the database directly, and doesn't invoke any hooks.

That being said, the only 'good' way you're going to be able to do this is to add an additional submit handler to the form in a `form_alter` hook as you've suggested.
> 3 votes

---
Tags: 7, hooks, blocks
---


title: use URL with query as URL destination

text:
# Question
Title: use URL with query as URL destination
I mean can we have something like this? url with double `?` in drupal?

```
http://drupal.org/?destination=xxx/yyy?token=zzz

```

# Answer
> 8 votes
Sort of, but you'll need to URL encode the second `?` otherwise the URL will be invalid.

The best thing to do is use `l()` or `url()` which will do this for you:

```
$query_string = array('destination' => 'xxx/yyy?token=zzz');
$url = url('<front>', array('query' => $query_string));

```

That will produce the string:

```
/?destination=xxx/yyy%3Ftoken%3Dzzz

```

Which is the correctly encoded version of the URL in your question.

Drupal will also respect this method when auto-redirecting based on a form submission etc. So the page you get directed to will actually look like this:

```
/xxx/yyy?token=zzz

```

# Answer
> -1 votes
You can do it like this:

```
http://drupal.org/?destination=xxx/yyy&token=zzz
```

---
Tags: navigation
---


title: How can I find certain queries?

text:
# Question
Title: How can I find certain queries?
I have logged a bunch of slow queries. Now I am wondering how should I find them in Drupal. Any ideas?

# Answer
If it is related to database queries you can use Devel module. You can configure this module http://www.example.com/admin/config/development/devel this will show you a list of slowest queries.
> 4 votes

---
Tags: javascript
---


# Question
Title: _form_comment_form_alter for certain node type
When using the hook\_form\_comment\_form\_alter, how do I only target the comment form of a single content type?

Right now it is targeting all comment forms, and I need it to just target the 'Blog' content type comment forms

# Answer
> 1 votes
You should use comment form ID for that content type: hook\_form\_comment\_node\_xxx\_form\_alter

which comment\_node\_xxx\_form is comment form id for content type xxx:

```
function hook_form_comment_node_xxx_form_alter(&$form, &$form_state, $form_id) {
    ...
}

```

# Answer
> 0 votes
```
function hook_form_comment_form_alter(&$form, &$form_state) {
  $node = $form['#node'];
  if ($node->type == 'blog') {
    // do something
  }
  ...
}

```

---
Tags: 7, comments, forms
---


# Question
Title: How to show how many hits has got one page
I'm trying to get something like this "viewed: 123 times." on every single node a part from the static pages like about us or contact etc..

Is there a module for it or is better to create a flag for this?

Thanks in advance.

# Answer
check the Statistics module. Its already there in drupal, just need to enable it
> 3 votes

---
Tags: 7, flags, nodes
---


title: Content Update Option

text:
# Question
Title: Content Update Option
I'm using Drupal 7. I made a couple of content types and taxonomies. Is there any way to select multiple content in the same content type and modify their fields together?

For instance, I have account type with the fields: `account number`, `test case`, ...

I want to set multiple account contents' test case to the same value.

Note: the test case is just a field with a selection of test case names, sry about the confusion

# Answer
> 2 votes
If you're coding up test cases -- not really. You could build the nodes programatically with some test account numbers, etc. But, you'd have to do that by hand. There are alot of tutorials for SimpleTest and creating nodes in drupal.

If you need a GUI to alter many node fields at once, take a look at Views Bulk Operations (VBO).

---
Tags: nodes
---


# Question
Title: Does my Feature module have to explicitly define the body field in it's components?
When a new content type is created in Drupal it is automatically given a title and body field. Now that I am defining my components for my feature to I have to select it as one of the components of the feature module?

# Answer
> 1 votes
... I always do. :) It should be no problem -- and if for some reason the field doesn't exist on the destination server it will then be created (the Minimal install profile for instance I don't think has the body field by default). If you look in /profiles/standard/standard.install you'll see it creates the fields and basic content types in code, eg:

```
// Around line 229 of standard.install where $type is
// essentially 'page' or 'article'.
node_add_body_field($type);

```

---
Tags: 7, features
---


# Question
Title: Image field - Cant set up number of values
I have 2 content types with image field. Shop and product.

For shop i limited number of images to 1, on products to 10.

Somehow the number changes to 10 for shop and to 1 for products (sometimes product doesnt change at same time for shop but in the end it happens). I noticed that it happens when i clear cache and run cron. I change values back to 10 and 1, and it works ok till the next cron run (or cache clear).

Any idea why is this happening ? All other content types (about 20) are ok, no changes for image fields.

# Answer
> 2 votes
If you're using the same image field on two content types then the cardinality (number of values) will be the same across both.

You'll notice you have 'instance' settings and 'field' settings on the field edit form. The 'instance' settings are unique to that instance, and can be different for each entity type/bundle the field is attached to.

The 'field' settings are global to that field, and the cardinality is one of these global field settings. If you change it for one content type, it will automatically change for the other content type. The caveat to this is that if you have data in the database for those fields already, you might not be able to change the cardinality at all (the select list will be greyed out).

This is by design, and how the field system works (there's no way around it). If you need to have two fields on two different content types with different cardinalities, you need to create two separate fields.

---
Tags: 7, media
---


# Question
Title: Create dummy instances of custom entity with dummy field data?
My module defines a custom entity type and bundle and adds fields to the bundle programatically. Now, I need to create a bunch of dummy data to test the interface. I'm working with various combinations of entity\_get\_controller()-\>create(), entity\_metadata\_wrapper()-\>save(), field\_attach\_submit(), etc. and I have been able to fill the entity base table with new rows. The problem is that the generated entities aren't loaded with:

```
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'my_entity_type');

```

I'm not surprised that the query doesn't return my new entities because I haven't found a place to specify bundle for the dummy entities and I haven't figured out how to generate default or random field data. How do I specify the bundle for my new entities and how can I generate valid random field data for date, taxonomy\_term\_reference and integer fields?

# Answer
> 0 votes
My created entities were not listed by the EntityFieldQuery above because of this issue: Make EntityFieldQuery::fieldOrderBy include NULL field values

My new entities did not include a date field that was used to sort the table. So, the table didn't include the null-field entries.

I didn't figure out how to specify the bundle for my new entities but there is only one bundle defined, so it is the default. I'm still interested in a function that would be able to create random field data valid for each type of field. Heading over to look at Devel module for that function.

---
Tags: entities
---


title: Configure Modules from a Script

text:
# Question
Title: Configure Modules from a Script
I'm interested in created a sort of "deploy" script. I basically want it to take a fresh drupal install (plus my versioned work in sites/) and disable and enable modules as needed and then automatically configure the site.

The first part is easy with a simple script and drush. The second part is the part I'm not so sure of. I can manipulate the database directly (again, using drush) and run queries against it, but I wonder if that is a bad way to do it since the schema of modules can change when they are updated (though I think core will stay mostly the same in 7.x).

I'd like to be able to script things like the CSS/JS aggregation settings or the Facebook APP ID/Secret in fboauth. Is there any "safe" way to do this without worrying about module updates breaking the script?

# Answer
Unfortunately, there is no "right" solution for Drupal 7; in Drupal 8, the configuration management initiative hopes to solve this problem. There are a few things that you can look at to help you out.

* Features: http://drupal.org/project/features: Take database settings and write them to code, making a new module containing your settings. Use "strongarm" module (http://drupal.org/project/strongarm) to be able to save items from the variables table in your features. Once you have your features module, you can copy it to another site and run 'drush fr' to "revert" the feature (copy code back into the database).
* Deploy: http://drupal.org/project/deploy: The counterpart of Features, it allows you to move content from one Drupal site to another.
* drush generate-profile: http://drupal.org/node/1368242: Work in progress: given an existing site, creates a profile that will recreate that site. Create your features first, then run generate-profile. In its current state, it does a good job of creating your makefile and setting up the modules you need, but the template files that generate the profile code are not finished or working yet. I am still working on this command, as time allows.
> 4 votes

---
Tags: 7, drush, installation
---


title: What is this hook supposed to do?

text:
# Question
Title: What is this hook supposed to do?
I need to modify the query of one of my views. I've found `hook_views_query_alter()`, but can't for the life of me figure out what I'm supposed to do with it. According to the API,

> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.

OK, so I know to put the function with the hook in a views.inc file. But what do I need to put in the actual .module file? I can't seem to find any examples of complete module code that uses this hook to point me in the right direction. Does my module code contain the `MODULENAME_views_api()` and nothing else?

# Answer
If your module doesn't need to implement any other hooks, then yep, `hook_views_api()` is all you need in your .module file.

As long as you provide the right path in `hook_views_api()`, Views will know where to look and will dynamically include the files when they're needed.

Usually you need to put `files[] = mymodule.FILENAME.inc` in your module's .info file for the dynamic code registry to pick it up, but from the looks of it that isn't the case for Views.

If you're looking for some code examples for this, take a look at the Administration Views module; it's .module file contains only `hook_views_api()` as well (and it works), so you can be confident you're doing the right thing.
> 6 votes

---
Tags: 7, hooks, views
---


title: Hide Year Attribute in Date Module

text:
# Question
Title: Hide Year Attribute in Date Module
I have created a date field that prints out the time for a list of courses offered at a local employment office. I have used a custom input format (h:i A) for the user to input their course start/end time. When the new course listing is created the date field displays 0000-4:30PM to 6:30PM. I assumed the 0000 is representing the year attribute which is selected by default and I am unaware how to change it’s default setting.

I have also included a screen captures below:

I’m still rather new to Drupal so I’m not sure what step I am missing.

**System Information:**

* Drupal 7
* Bartik 7.12

# Answer
Intrigued by your question, I found the same issue with trying to use a date field to store a time as the date field stores a Unix Timestamp.

A Drupal 7 project called timefield allows you to store a time which has no relation to a date, even has duration, and display configuration. I have not used it in a live environment, but looks like a solution for you.
> 2 votes

---
Tags: datetime
---


title: Syntax for the various query modifiers

text:
# Question
Title: Syntax for the various query modifiers
I'm using `hook_views_query_alter()` and am wondering where I can find the syntax for the various query modifiers.

One of the examples I found looked like this:

```
$query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";

```

I'm not sure what that syntax is saying. Does it mean order by the node.type field, where nodes with story are first, then page, and so on? Or something else? I need to be able to group on multiple fields (and not all fields are on the initial node (relationships.)

Is there somewhere that all of the available modifiers are documented, including their syntax? By modifiers, I mean `$query->orderby`, `$query->where`, and so on.

# Answer
Your question is 2-fold. 1 part of your question is drupal based, the other is (MySQL) SQL based ...

That line of code is as follows:

1. `$query->orderby[0]`: adds an `ORDER BY` clause fragment to the SQL query string. More could be tacked onto using php such as `$query->orderby[1]` or `$query->orderby[123]` ... these just build up an ordered php array of orderby sql clauses ...
2. The SQL expression `FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD')` is used by MySQL within the `ORDER BY` clause and takes an additional value of `DESC` or `ASC`. That function uses the cardinality of the passed in parameters as a weighted list of values for orderby. You are correct in how FIELD() is ordering the results ....

You may order by any selected field in SQL or by an aggregate function in MySQL. Not all DBMS have the same functionality, for example as seen here the above `FIELD()` function in MySQL has to be emulated in Postgres: https://stackoverflow.com/questions/1309624/simulating-mysqls-order-by-field-in-postgresql

So far as I'm aware there is no list of all the functions or values one could order by ...
> 3 votes

---
Tags: 7, views
---


title: AJAX Replace on Select

text:
# Question
Title: AJAX Replace on Select
I've been trying to get an answer to the following question AJAX dependent select. However I think I'm compounding to many concepts. Perhaps I should first master the FAPI AJAX before building upon it. I can not get the following to work properly. After selecting an option I get the drupal clock like it's going to re-render the text field however nothing happens and the value does not change. Where am I going wrong?

```
function main_iosupload_form($form, &$form_state) {
//Define SQL Lookup Query
  $sqlplatform = "SELECT vid, name FROM {taxonomy_vocabulary} WHERE vid >= 4";

  $result = db_query($sqlplatform);
  $options = array();
    foreach ($result as $row) {
      $options[$row->vid] = t($row->name);
    }

$form['platform'] = array(
  '#type' => 'select',
  '#title' => t('Select a Platform'),
  '#options' => array(
    0 => t('- Select -')) + $options,
  '#default_value' =>  0,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_select_callback',
    'wrapper' => 'replace_model_div',
    'effect' => 'fade',
   ),
);

$form['model_wrapper'] = array(
  '#type' => 'textfield',
  '#default_value' => (!empty($form_state['values']['platform']) ? $form_state['values']['platform'] : t("Intial Value")),
  '#prefix' => '<div id="replace_model_div">',
  '#suffix' => '</div>',
);

return $form;
}
function ajax_select_callback($form, $form_state) {
  return $form['model_wraper'];
}

```

# Answer
> 2 votes
Almost a whole week of hitting my head on this. Yeah it helps if in the callback function I call back the correct form name... *sigh*

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


# Question
Title: Drupal + Solr, boost result based on custom node weight
I use Drupal 6 with the ApacheSolr search module.

On my website, all visitors can flag any node with a yes/no answer to the question "Did you find what you were looking for?". Based on those answers, I calculate a custom ranking score for each node which is stored in a separate DB table.

Now I would like to include this score when sorting/boosting the search results in Solr, so that those nodes with the best relevancy / score come out on top.

Can it be accomplished with hook\_apachesolr\_prepare\_query()?

All suggestions are welcome :)

# Answer
> 2 votes
To provide the score as a sort option add it in the prepare\_query hook:

```
function mymodule_apachesolr_prepare_query(&$query, &$params, $caller) {
  $query->set_available_sort('field_score', array('title' => t('Score'), 'default' => 'desc'));
}

```

To boost by it you'll need to either:

* Go to Site settings -\> Apachesolr -\> Search fields and if the score field appears there give it a value bigger than all the other fields to make it the most relevant.
* If the field doesn't appear (due to the type it might not appear) or you want more control (like calculate the boost value on every query) you can add the boost in the modify\_query hook with something like this: `$params['qf'][] = 'field_score^10';`.

---
Tags: 6, hooks, search
---


# Question
Title: Computed field won't update itself or save to the database
UPDATED ISSUE: In the original issue below, I was getting an error when a query was empty. I've now gotten rid of the error, but content no longer saves into the database (where it saved fine before). Also, if the "store value to database" option is unchecked, then the data does not display at all. The new portion is the the second piece of the below code.

```
$entity_field[0]['value'] = "";$nids = db_query('
    SELECT entity_id FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
    )->fetchCol();

if (!empty($nids)) {
    $entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_venue_default_value')));
   }

else {
    $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
    )->fetchField();
   }

endif;

```

If the `array_pop` portion is all that is in the computed field, then the field saves to the database (or displays, if the option is unchecked) just fine. If it's not included at all, the field saves/displays fine. However, when it is placed within `if (!empty($nids))`, no values for the field will save/display at all. This includes both the value of the `array_pop` and independent values calculated by `SELECT AVG`. As always, any help is greatly appreciated (and thanks to both Clive and Tenken for getting me get rid of the initial error).

ORIGINAL ISSUE: I have two content types: Review and Venue. Each review has an entity reference field to relate it back to the correct venue node. On the Venue nodes, I have computed fields to display calculated averages of fields from reviews referencing the current node (i.e. Average Payment Rating for Joe's Nasty Catering). For one of these fields, the code is:

```
$entity_field[0]['value'] = "";$nids = db_query('
  SELECT entity_id FROM {field_revision_field_review_venue_reference}
  WHERE field_review_venue_reference_target_id = :nid',
  array(':nid' => $entity->nid)
)->fetchCol();

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment}
   WHERE entity_id IN (:nids)',
   array(':nids' => $nids)
)->fetchField();

```

The computed field works 100% correctly when a review has already been submitted for the current venue. However, when no reviews have been submitted, I get an error of `PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064`. It seems that this is because there are no entries where the Node Reference field is equal to the current NID.

Is there some way to fix this? I hadn't gone through the steps necessary to create the error until today, and as such I just realized that the site I'm building is essentially broken because of it.

# Answer
If you would print the rest of the MySQL error message I assume your error is a malformed query such as:

```
SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment} WHERE entity_id IN ()

```

Eg, you cant have an empty `IN` primary key list.

Since you want to show an average value you could do something simple like:

```
if (isset($nids)) {
  $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value) FROM
    {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
  )->fetchField();
} else {
  $entity_field[0]['value'] = 0; // no values to average == 0.
}

```
> 2 votes

---
Tags: entities
---


title: Theme inner field collection field(s)

text:
# Question
Title: Theme inner field collection field(s)
I'm looking for a way to theme the inner fields of field collection. Does anyone know, how to do that?

Currently the template output is like this:

```
<div id="someid">
  <div class="somemarkup">
    <div id="someid">
      <div class="somemarkup">
        ... the field collection ...
      </div>
    </div>
  </div>
</div>

```

but as you can see, there are now two ids with the same name

# Answer
What you're experiencing is a bug. It happens quite often with contributed code, since it usually moves faster than it is tested. But don't worry, being contributed also means there are lots of people using, and probably someone else will bump into the same issue as you are experiencing.

When you face an issue that looks like a bug, you should ask yourself whether you've configured everything properly. Check first, but if there's nothing obviously wrong, give the issue queue a visit. Every module, theme or profile has an issue queue where people report bugs, suggest features and ask for support.

Search the issue queue and you may find a patch to your issue. If there is no report of your bug, file a new issue and provide a step-by-step guide to reproduce the error. That means you will have to try installing and configuring the module again on a fresh Drupal install. When the module mantainer sees the bug report, the steps to reproduce will make it a lot easier to debug and provide you with a fresh patch.

Mantaining modules/themes are usually voluntary work, and if you don't provide the steps to reproduce nor reply to mantainer questions, your issue will probably be postponed. Get involved with the community, it pays off.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: Single value "db_query": How to SELECT value that related to the node
From this page, if what we need is SELECT single value, we can use `fetchField` method like below:

```
$nbr_records = db_query("SELECT count(nid) FROM {joke}")->fetchField();

```

I've created single value `Integer` field type with machine name `field_subscription_period` attached to node type `yearly_rent`.

I'm using this in Rules Action.

I've tested many db\_query example with no luck.

Below is what I'm using, which it will get value of `entity_id` `2`:

```
$result = db_query("SELECT field_subscription_period_value FROM {field_data_field_subscription_period} WHERE entity_id = 2")->fetchField();

```

Above query will get value of `entity_id` `2`... but I want to SELECT `field_subscription_period` value that related to the node. So, how to get value that related to the node?

**-newly added-**

I still don't understand how to use `$node = node_load($nid);`. Lets say I want to use the value as variable to be calculated in date field.

I've tried below with no luck:

```
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
$newdate = strtotime("+$values year","$value");
return $newdate;

```

..and also I got error:

```
Notice: Undefined variable: nid in eval() (line 1 of /var/www/testd7/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7539 of /var/www/testd7/includes/common.inc).

```

# Answer
> 3 votes
You should not use direct queries to the database tables used for fields, for the simple fact the fields could not use database tables to store their value; this is what happens by default, but if a different storage implementation is exposed by a module, the information will be saved in another place. That is actually what happens with the Mongodb module.

If you know the node ID, and you want to get the value of a field associated to it, you can use the following code.

```
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');

```

`$values` is an array whose structure depends from the field. It contains at least an item, but the exact number depends from how many values the field can have. (It is normally set in the setting page for the field.)
To see the structure of that array, you should install the Devel module, and use test code similar to the following one.

```
$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
dsm($values);

```

For example, the first screenshot shows the structure used for a node body, while the second one shows the structure used for an image field.

If you need to find all the nodes of a specific content type, and filter out the list basing on the value set for a field, you should use the EntityFieldQuery class, as in the following code.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yearly_rent')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_subscription_period', 'value', $minimum_value, '>')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

```

`addMetaData('account', user_load(1))` is necessary because the `EntityFieldQuery` class respects the access permission associated with fields; if the current user doesn't have access to the field, `fieldCondition()` would fail.
Once you have the node object, you can use field\_get\_items(). If you want to obtain a value to render, you should call field\_view\_field().

---
Tags: 7, rules, database
---


title: Quick question about filter_xss()

text:
# Question
Title: Quick question about filter_xss()
If I'm creating nodes programmatically does Drupal deal with `filter_xss()`, or do I have to add the function to my code?

# Answer
Sanitization functions, which include filter\_xss(), are used when a value is shown as output, not when something is saved in the database.

None of those functions is called when saving a node in the database.

See Writing secure code.

> ### Use check functions on output to prevent cross site scripting attacks
>
> No piece of user-submitted content should ever be placed as-is into HTML.
> 5 votes

---
Tags: nodes, forms
---


# Question
Title: How can I display "new" or "update" in the view that overrides admin/content/node?
I have override the page admin/content/node with Views. The default page of admin/content/node displays "new" for new contents and "updated" for updated contents. How can I display them in the custom View?

# Answer
Just use the "Content: Has new content" field, the same field used from the view that emulates the tracker page.
> 2 votes

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


# Question
Title: Simple: How do I add data into custom field while creating new user with user_save
With each user I create when my form is submitted, I want to insert an id into a field/column I've added to the users table. Trouble is, the column isn't receiving the value. I've tried a few variations of user\_save() to coax it into inserting the value, but at this point I think I'm missing something fundamental of drupal 7. Later I also need to retrieve this value from the current user.

I'd appreciate any help. Thanks.

```
<?php
//Func called in form submit. Values passed from there
function fsa_create_sponsor_admin($sponsor_id, $a_fname, $a_lname, $a_email){

//Misc. code. . . .

//create a new user
$account = new stdClass();
$account->is_new = TRUE;
$account->name = $user_name;
$account->mail = $a_email;
$account->init = $a_email;
//$account->sponsor_id = $sponsor_id; (no error, but not working here)
$account->status = TRUE;
$account->roles = $new_user_roles;
$account->timezone = variable_get('date_default_timezone', '');

//First variation of user_save()
user_save($account, array('pass' => $sp_password, 'sponsor_id' => $sponsor_id));

//Second variation of user_save()
user_save($account, array('pass' => $sp_password, 'field_other' => array(LANGUAGE_NONE => array(array('sponsor_id' => $sponsor_id)))/*end 2nd array*/));
}
?>

```

Column added in hook\_install()

```
db_add_field('users', 'sponsor_id', array('type' => 'int', 'size' => 'big', 'not null' => FALSE, 'description' => 'Sponsor to which user belongs',));

```

# Answer
I had the a similar problem. This code helped me. I put this code in myform\_submit.

```
$fieldvalue = $form_state['values']['fieldname'];

```

//Loading the user object

```
$account = user_load($GLOBALS['user']->uid);

```

//Gettin the user data

```
$edit['data']['fieldname'] = $fieldvalue;

```

//saving the achieved data

```
user_save($account, $edit);

```

//Retrieving the user value

```
global $user;
$whatever = $user->data['fieldname'];

```
> 1 votes

---
Tags: hooks, entities, users
---


# Question
Title: how to prevent warnings from displaying to anonymous users
As in subject: how to prevent warnings from displaying to anonymous users? They contain paths etc. Even better, how to display warnings only to priviledged users?

# Answer
> 8 votes
First you should turn down the error\_reporting options on your production server. This will erase most of PHP's warnings and notifications.

Also you can configure drupal to only log the errors. To do that go to `Administration > Configuration > Development > Logging and errors` or directly to the path `/admin/config/development/logging` and set "Error messages to display" to none. Drupal then still logs errors but doesn't display them to users.

If you still need finer control over messages surely the module disable\_messages can help you.

---
Tags: 7, status-messages
---


# Question
Title: How can I unpublish the content profile node when users update their user account?
I would like to unpublish automatically the content profile node of the users who updates their user account at user/%/eidt.

I found a event "User account details have been updated" in Rules but didn't find the action to unpublish their content profile node.

# Answer
There's also a hook you can use to react to user operations. Could do something pretty simple like this (untested code btw, you'll also have to adapt it for the name of your content type):

```
<?php
  /**
   * Implements hook_user()
   */
  function MODULENAME_user($op, &$edit, &$account, $category = NULL) {
    if( $op == 'update' ) {
      $type = 'name_of_your_profile_content_type';
      $profile = content_profile_load($type, $account->uid);
      $profile->status = 0;
      node_save($profile);
    }
  }
?>

```
> 0 votes

# Answer
You can use the "Set data"-action to set the profile node's status to 0: `status=1` means published, `status=0` means unpublished.
> 0 votes

---
Tags: 6, rules, users
---


# Question
Title: How do I override field_multiple_value_form()?
I have to override the standard field wrappers which add additional divs.

Drupal uses the following code, in field\_multiple\_value\_form().

```
$field_elements += array(
  '#theme' => 'field_multiple_value_form',
  '#field_name' => $field['field_name'],
  '#cardinality' => $field['cardinality'],
  '#title' => $title,
  '#required' => $instance['required'],
  '#description' => $description,
  '#prefix' => '<div id="' . $wrapper_id . '">',
  '#suffix' => '</div>',
  '#max_delta' => $max,
);

```

I implemented `hook_form_alter()`, but this form needs extra data that are passed as argument: `$field`, `$instance`, `$langcode`, `$items`, `$form`, and `$form_state`.

How do I define `hook_form_alter()` in this case?

# Answer
> 1 votes
You need to implement hook\_field\_widget\_form\_alter(), which is invoked from `field_multiple_value_form()` using the following code.

```
  $element = array(
    '#entity_type' => $instance['entity_type'],
    '#entity' => $form['#entity'],
    '#bundle' => $instance['bundle'],
    '#field_name' => $field_name,
    '#language' => $langcode,
    '#field_parents' => $parents,
    '#columns' => array_keys($field['columns']),
    // For multiple fields, title and description are handled by the wrapping table.
    '#title' => $multiple ? '' : $title,
    '#description' => $multiple ? '' : $description,
    // Only the first widget should be required.
    '#required' => $delta == 0 && $instance['required'],
    '#delta' => $delta,
    '#weight' => $delta,
  );
  if ($element = $function($form, $form_state, $field, $instance, $langcode, $items, $delta, $element)) {
    // Input field for the delta (drag-n-drop reordering).
    if ($multiple) {
      // We name the element '_weight' to avoid clashing with elements
      // defined by widget.
      $element['_weight'] = array(
        '#type' => 'weight',
        '#title' => t('Weight for row @number', array('@number' => $delta + 1)),
        '#title_display' => 'invisible',
        // Note: this 'delta' is the FAPI 'weight' element's property.
        '#delta' => $max,
        '#default_value' => isset($items[$delta]['_weight']) ? $items[$delta]['_weight'] : $delta,
        '#weight' => 100,
      );
    }

    // Allow modules to alter the field widget form element.
    $context = array(
      'form' => $form,
      'field' => $field,
      'instance' => $instance,
      'langcode' => $langcode,
      'items' => $items,
      'delta' => $delta,
    );
    drupal_alter(array('field_widget_form', 'field_widget_' . $instance['widget']['type'] . '_form'), $element, $form_state, $context);

    $field_elements[$delta] = $element;
  }

```

For example, you could implement it using the following code.

```
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  $element['#prefix'] = $element['#suffix'] = '';
}

```

The arguments passed to `field_multiple_value_form()` are also passed to `hook_field_widget_form_alter()`, directly, or contained in `$context`.

---
Tags: 7, forms
---


# Question
Title: Failed SELECT value from Date field (single value)
I've installed date module. the field data stored in `field_data_field_date_start_rent`. The field dont have multiple values

I want to select `field_date_start_rent_value`.

So, I'm testing SELECT it and UPDATE to other date field. It not works.

Below is the SELECT, but I'm using text field to UPDATE to see if it works:

```
$nid = $node->nid;
$startrent = db_query("SELECT field_date_start_rent_value FROM {field_data_field_date_start_rent} WHERE entity_id = $nid")->fetchField();
$endrentf = db_query("UPDATE {field_data_field_cubagan} SET field_cubagan_value = $startrent WHERE entity_id = $nid");
return $endrentf;

```

If using the same SELECT query on integer field, it works without problem. I think it must have something different in the SELECT query for date field.

# Answer
It would be a lot easier to use a different set of API calls to do this, you can avoid having to manipulate the database directly:

```
// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);

// Get the field value
$start_rent = $date_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = $start_rent;

// Save the node
node_save($node);

```

Just as an aside: you're not making the best use of the DB API at the moment, you should be using placeholders and provide arguments to `db_query()` rather than interpolating them directly into the query string. The equivalent of your `SELECT` statement written the recommended way would be:

```
$args = array(':nid' => $node->nid);
$sql = 'SELECT field_date_start_rent_value FROM {field_data_field_date_start_rent} WHERE entity_id = :nid';
$startrent = db_query($sql, $args)->fetchField();

```
> 1 votes

---
Tags: 7, entities, datetime
---


# Question
Title: Custom module stopped executing after 30 seconds
I've written a custom module that adds many users from a database to drupal database. So, it has many database queries to take care of the drupal tables: users, user\_roles, url\_alias, profile and field\_data\_field\_$fieldname and field\_revision\_field\_$fieldname where $fieldname is the profile2 field and has many such fields.

The problem is when I execute this module (the trigger is user selects an option in the form which is specific for this module), it executed for only 30 seconds and inserted some 20+ users where I have to insert 500+ users. After 30 seconds, it didn't display any error. It stayed on the same form.

How can I clear this?

# Answer
You need write batch operation:

> Functions allowing forms processing to be spread out over several page requests, **thus ensuring that the processing does not get interrupted because of a PHP timeout**, while allowing the user to receive feedback on the progress of the ongoing operations.

http://api.drupal.org/api/drupal/includes%21form.inc/group/batch/7
> 1 votes

# Answer
You can implement hook\_cron() in your module. As example, you can look at aggregator\_cron(), which imports new feed articles from a list of feeds.

```
function aggregator_cron() {
  $result = db_query('SELECT * FROM {aggregator_feed} WHERE queued = 0 AND checked + refresh < :time AND refresh <> :never', array(
    ':time' => REQUEST_TIME,
    ':never' => AGGREGATOR_CLEAR_NEVER,
  ));
  $queue = DrupalQueue::get('aggregator_feeds');
  foreach ($result as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.
      db_update('aggregator_feed')
        ->fields(array('queued' => REQUEST_TIME))
        ->condition('fid', $feed->fid)
        ->execute();
    }
  }

  // Remove queued timestamp after 6 hours assuming the update has failed.
  db_update('aggregator_feed')
    ->fields(array('queued' => 0))
    ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
    ->execute();
}

```

I took this implementation of `hook_cron()` because it has a similar task, although the data is not imported from another database, and because it shows how to use Drupal 7 queues.

The other function you should look is aggregator\_cron\_queue\_info(), which is an implementation of hook\_cron\_queue\_info(), which defines the queue cron task would automatically consume. To understand how this work, see drupal\_cron\_run(), which contains the following code.

```
  // Grab the defined cron queues.
  $queues = module_invoke_all('cron_queue_info');
  drupal_alter('cron_queue_info', $queues);

  // …

  foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }

```

To notice that the queue doesn't need to be populated from `hook_cron()`, but it can get populated from any hook.

The reason for using a queue is explained in the documentation for `hook_cron_queue_info()`.

> While there can be only one `hook_cron()` process running at the same time, there can be any number of processes defined here running. Because of this, long running tasks are much better suited for this API. Items queued in `hook_cron()` might be processed in the same cron run if there are not many items in the queue, otherwise it might take several requests, which can be run in parallel.
> 1 votes

# Answer
This is most likely a restriction set in your php.ini . Just search for 30 in the php.ini and set the value to something more usefull for you.

As an alternative you can trigger your code using drush eval or even code your own drush command. Drush is executed as PHP command line (CLI) and does not have any execution time restriction. The drush module itself has nice example code to learn from.
> 0 votes

---
Tags: 7
---


# Question
Title: How do I prevent a module from being loaded?
I am developing a custom module, from this module im trying to disable other modules (for certain reasons).

Let's say I want to disable the search module, how would I do this?

# Answer
You can actually prevent a module is enabled, implementing hook\_system\_info\_alter() with code similar to the following one.

```
function mymodule_system_info_alter(&$info, $file, $type) {
  if ($file == 'search' && $type == 'module') {
    $info['dependencies'] = array('module_that_does_not_exist');
  }
}

```

Then, your module should use `module_disable(array('search'))` to disable the module.

In the case you need to dynamically disable modules basing on some conditions, you can verify those conditions in `hook_system_info_alter()`, but the modules must be disabled in another hook. The reason is that `hook_system_info_alter()` is (indirectly) called from system\_rebuild\_module\_data(), and module\_disable() calls `system_rebuild_module_data()`; that would cause a loop (`system_rebuild_module_data()` =\> `hook_system_info_alter()` =\> `module_disable()` =\> `system_rebuild_module_data()`).

`hook_system_info_alter()` is called for every module Drupal found.

As alternative, as Drupal 7 invokes hook\_modules\_enabled() when new modules are enabled, you can use the following code.

```
function mymodule_modules_enabled($modules) {
  if (in_array('search', $modules)) {
    drupal_set_message(t('mymodule is not compatible with the Search module'), 'error');
    module_disable(array('search'));
  }
}

```

Also in this case, if you need to dynamically disable modules basing on some conditions, you can verify those conditions are met in `hook_modules_enabled()`.
> 1 votes

# Answer
See module\_disable and the comments therein for how to place it within a profile.install or module.install file.
> 1 votes

---
Tags: 7
---


# Question
Title: Can I route individual websites to a multi-site Drupal installation?
This isn't really Drupal-specific, but perhaps someone is already doing this with Drupal and can guide me. I host a few sites for my customers and several of those are Drupal-based, using a multi-site installation. No problems, except that those are not individual cPanel accounts, of course, and the customer cannot manage any part of their account -- I have to do it all.

Is it possible to set up my Drupal customers with individual cPanel accounts, yet route all their web traffic to the multi-site Drupal installation on my reseller account (typical reseller account on a shared host)?

# Answer
> 0 votes
I have never seen this done in cpanel. Maybe under your reseller account you could create a instance of multi-site and then create sub-domains then your clients could domain could be redirected to the subdomain?

Have you tried talking to the guys who created cpanel that might be another resource

http://forums.cpanel.net/forum.php

---
Tags: multi-sites
---


# Question
Title: Unable calculate date field using strtotime
From this answer, the result will be in text field `field_cubagan`.

Actually I want the result in another date field, but I choose text field instead as testing purposes because text field accept wide variety of result.

In below codes, the result will be `2012-06-30 10:05:00`:

```
// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);
$integer_items = field_get_items('node', $node, 'field_subscription_period');
$integer_item = array_shift($integer_items);

// Get the field value
$start_rent = $date_item['value'];
$period = $integer_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = $start_rent;

// Save the node
node_save($node);

```

But under `Update the other field`, instead of get unmodified result from `$start_rent`, I want the result become: "Datetime" + "x years" which "Datetime" is from `field_date_start_rent` while the "x" of the years is taken from `field_subscription_period`

I'm not sure if strtotime only works on unix timestamp or only on `Y-m-d h:i:s` format or works on both.

both below codes giving same result `2012-06-30 10:05:00` because in second codes, it converted to unix timestamp, and then converted back to the time format:

```
$node->field_cubagan[$node->language][0]['value'] = $start_rent;
$node->field_cubagan[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime($start_rent));

```

below codes will result in unix timestamp `1341050700`:

```
$node->field_cubagan[$node->language][0]['value'] = strtotime($start_rent);

```

But strange thing is, I always failed when trying to calculate.

In below 3 codes is example where I always get warning and not works (I'm using `+1 year` as testing purposes):

```
$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',$start_rent);
$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',date('Y-m-d h:i:s', strtotime($start_rent)));
$node->field_cubagan[$node->language][0]['value'] = strtotime('+1 year',"date('Y-m-d h:i:s', strtotime($start_rent))");

```

What actually I've missed and what is the right codes?

# Answer
> 1 votes
I got it. It should be:

```
// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);
$integer_items = field_get_items('node', $node, 'field_subscription_period');
$integer_item = array_shift($integer_items);

// Get the field value
$start_rent = $date_item['value'];
$period = $integer_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("+$period year",strtotime($start_rent)));

// Save the node
node_save($node);

```

---
Tags: 7, entities, datetime
---


title: Oracle database connection in drupal 7

text:
# Question
Title: Oracle database connection in drupal 7
I want to retrieve a list of products from an external oracle database and show it in my drupal site as a catalog. But the problem is that, how can I make the connection to oracle db from a drupal 7 site. Please any suggestion on how to perform this operation is highly welcome. Thanks!

# Answer
> 1 votes
I recommend separate this from Drupal. I mean if you just want a list of products so write an external application to prepare a xml format of this list and feed it to Drupal.

You need install PHP PDO\_OCI to make connection from PHP application into Oracle.

Drupal has an Oracle Driver but I recommend external application instead

---
Tags: database
---


title: How to limit drupal cron CPU usage?

text:
# Question
Title: How to limit drupal cron CPU usage?
when cron is running, apache PID peaks, and blocking the server response. is it possible to limit the cron CPU usage and leave some headroom for HTTP requests?

# Answer
> 1 votes
You can use this module elysia\_cron Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

Elysia cron is usually used in large sites that needs performance optimization.

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


# Question
Title: Drupal 7 Change User Login block link text
I've set up the standard "User Login" block to the "header" region of my theme. I clicked on "configure" and selected "Link" under "Block Type". Now the link to sign in appears as "Log In/Register". How do I change this text? I have also LoginToboggan enabled.

# Answer
Instead of throwing a string override directly into settings.php file, use the excellent String Overrides module. It can help you to manage the string overrides for your login link, as well as possible future UI text changes. All this without hacking core files.
> 0 votes

# Answer
You could use a template, probably named something like 'user-login.tpl.php'

For more information on 'working with template suggestions' have a look at http://drupal.org/node/223440
> 1 votes

---
Tags: 7, users
---


# Question
Title: View with content from Media gallery links to node not working
So i have a couple of nodes I made with the media gallery module. Then made a view called 'most recent photoalbums' with I put inside a block to be displayed on the frontpage. The problem is that characters %5B and %5D are being generated against will and make the links to the nodes not work when clicked. So, hovering over an image in such a view

So with display set as block, everything is left as default except the following: Format:
Show: fields

**Fields:**
**Content: title** \- nothing fancy here when it comes to settings just linked to node

**Content: Gallery media** \- here obviously is the problem

* No labels set whatsoever
* uncheck exclude from display
* Formatter set to Media
* File view mode: Preview
* Multiple field settings fieldset: 'Display all values in same row' checked, Display type: 'unordered list', 'Separator: Display 4 values starting from 0' - 'reversed' unchecked - 'first and last only' unchecked.
* Style settings fieldset: only 'add default classes' checked.
* Rewrite settings fieldset (where it's at):
'Rewrite this output as fied' unchecked,
'Output this field as link' checked,
'Link path': node/\[title\] (I tried all replacement patterns as suggested ),
'use absolute path' unchecked,
'Replace spaces with dashes' checked,
'External server URL' unchecked,

**Transform the case**: no transform, all the textfields under

**Link class, title text, rel text, Prefix Text, suffix text** and **Target** are left empty,
'Trim this field to a maximum length' unchecked,
'strip html tags' unchecked, under 'preserve certain tags' -\> 'remove whitespace' checked, 'Convert newlines to HTML br tags' unchecked.

# Answer
> 0 votes
Looks like you probably have spaces in the field \[title\], try using the nodeid check it works first then come back.

If you have pathauto you could then use this to rewrite the URL to an aliased URL.

# Answer
> 0 votes
Since you're rewritting the output of the field as a link the replacement patterns at your disposal won't help you. What I would do is to add the *Node Link* field to the View and set it as *Exlude it from display*. Rearrange it on top of the Content: Gallery Media field. Go back and edit the Content: Gallery Media and on the *Rewrite settings fieldset* you'll see this new Node Link replacement patern. Use that and your links will be fine.

---
Tags: 7, views, media
---