# Question
Title: Simple Drupal page loads very slowly; slow 'DrupalDatabaseCache::getMultiple' query
I've installed Drupal (and CiviCRM within Drupal) on shared hosting my group's host assures me is adequate (though they refuse to enable PHP caching like APC on it). It's generally far slower than my installs on other servers or my home Mac. Even the simple, completely default Drupal front page (which just shows one promoted story, the only extra blocks being from the Devel module) loads slowly. Just now it took a minute, and the Devel block reported the following slow queries. Any help solving or at least diagnosing the problem very welcome!

> ms | # | where | ops | query | target
>
> 41.05 | 21 | DrupalDatabaseCache::getMultiple | P A E | SELECT cid, data, created, expire, serialized FROM drupal\_cache\_menu WHERE cid IN (:cids\_0) default
>
> 32.97 | 21 | DrupalDatabaseCache::getMultiple | P A E | SELECT cid, data, created, expire, serialized FROM drupal\_cache\_menu WHERE cid IN (:cids\_0) default
>
> 28.13 | 21 | DrupalDatabaseCache::getMultiple | P A E | SELECT cid, data, created, expire, serialized FROM drupal\_cache\_menu WHERE cid IN (:cids\_0) default

# Answer
Devel is telling you how slow the query is. From what you wrote on your question it does not appear however to be telling you what is executing that query. I would attempt to locate the source of that query first, since your doctor can't issue you a prescription, if he does not know your ailment first.

I tried searching my D7 codebase for the string "drupal\_cache\_menu" and did not find anything. So perhaps that is coming from a contrib module? Otherwise it would have shown up in my search. Regardless, you can see the pattern I used to locate the code responsible for that query:

1. Select a unique string from the query (I tried using an individual word).
2. Search your whole codebase for that string.
3. See if the matches returned from your search could possibly relate to the slow query.

Once you locate the source of the query then you will (most likely) be able to determine if the slow query was caused by:

1. An error.
2. A view (in which case all you have to do to solve the problem is set the caching for that View).
3. Legit custom code (without errors) that just needs optimization, in this case you could implement Drupal's Cache API (the cache\_get() and cache\_set() functions) and maybe static caching as well. The nice thing about the Cache API is that you can benefit from implementing it even when you don't have external persistent cache stores such as Memcached and APC installed. Lullabot's now classic Caching guide for beginners might well help you out as well.
4. Legit contrib code (without errors) that just needs optimization. In this case you would probably be better off consulting the module mantainer.

As you see, the corrective actions are too many to list, and which one you will take will depend on the source of the query.
> 1 votes

# Answer
Given the total time of one minute, a query that takes 40ms is slow but really not that relevant. That's ~0,06% of the total request time.

Make sure that you don't trigger a known issue in Drupal 7: When you have modules enabled which are not found on the file system, this triggers a complete scan of the file system on every request, see http://timonweb.com/advice-may-help-you-if-your-drupal-7-has-started-run-slowly
> 0 votes

# Answer
The query causing that is in core drupal cache.inc, inside `getMultiple()`.
> 0 votes

---
Tags: 7, caching, performance
---


# Question
Title: Trouble with session ID and Drupal cookies when trying to establish a connection with Service Module and http-post
I am trying to complete an http-post between my common lisp application and my Drupal Site running Services and a Rest server. Currently I have my rest server set up to accept user login, and using Poster (Firefox plugin to create http requests) I am able to connect to my rest server. Also, using Poster if I am currently logged in I get a response "406 Not Acceptable: Already logged in as.." and if I am not logged in I get "200 OK" and when I go back to my browser I am logged in to my Drupal site.

Now I have been trying to simulate this same behavior using an http-post from my lisp application and I have been having a lot of trouble. For a long time I was always getting "200 OK" if I had correct username and password in the body of my post looking something like this:

```
username=ender2012&password=password&form_id=user_login

```

but it would not actually login and if I was already logged in I would never receive the 406 response that I expected. Finally I downloaded HttpFox which showed me the actual post that Poster was sending and I noticed that Poster was sending a Cookie header that looked like this

```
Cookie: Drupal.toolbar.collapsed=1; CAKEPHP=10e32669174a611c8919eeff471a2a1c; Drupal.tableDrag.showWeight=0; has_js=1; SESSdc0685ed01f285dab628a3700259e6bc=3qqK5XPaLRhEx7o4wAbIq5qK9qHEzRxz5qUnYZsaXG0

```

Now if I add a Cookie header to my lisp application's post with the Cookie I saw in http-post from Poster and I am logged in, I will get the 406. So it seems that there is some sort of session information stored in this cookie that I will need to use for my lisp application but I am unsure about how this would all work inside my application. Could anyone help me understand all of this?

Details:

• I am running Drupal 7

• I am using Services 3.0

• I am using a rest server with session authentication

• I am using application/x-www-form-urlencoded

• I am running this server on MAMP localhost currently

# Answer
All of the cookie information is set and returned in the response header of the login call.

This might also be of some help which explains how to make authenticated calls via a remote client. http://drupal.org/node/910598

Also note that if you use a Firefox plugin, it will be able to access the cookie set in Firefox. Thus if you use a different application that cookie will be different, so you will not be able to auth via your custom app and simultaneously see yourself as logged in in Firefox.
> 3 votes

---
Tags: services, users, sessions, cookies, 8
---


# Question
Title: What's the difference between $user login and access?
I'm migrating users and I came across the $user object.

What's the difference between the login and access field? Does access get updated with every page request?

# Answer
The *access* field is updated in Drupal's session write handler \_drupal\_session\_write. This means it is potentially updated at every page request. If you look at the source code, you'll see that the *access* field is, by default, only updated every 180 seconds. This interval can be changed by setting the `session_write_interval` Drupal variable.

```
// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}

```
> 18 votes

# Answer
According to the the comments for the fields in `user_schema()`:

`access`: Timestamp for previous time user accessed the site.

`login`: Timestamp for user’s last login.

So `access` would get updated for each page load, `login` only when the user actually logged in.
> 10 votes

---
Tags: 7, users
---


# Question
Title: Redirect user to login page when they have to access to a view?
I have a view which is only accessible to authenticated users. However, there are links to it on the site. Can I make it so that an unauthenticated user gets redirected to the login page, instead of the 403 they're seeing now?

# Answer
> 5 votes
The Redirect 403 to User Login module should do what you need.

# Answer
> 1 votes
I would use Rules, it is very configurable and should allow you to do what you require.

# Answer
> 0 votes
With LoginToboggan, the login form can be added to Access Denied (403) pages. No redirects needed.

---
Tags: 7, views, redirection
---


# Question
Title: Keeping track of date when user profile has been updated
I couldn't find a module or feature in D7 that keeps track of the date/time when a user updates their profile (any of the fields). I'm not using profile2 and I'm not planning to switch to that, otherwise I could probably do it with the node revision.

Is there another way of doing it other than adding a "last\_update" date field to the user and then using a hook\_user\_update() or hook\_user\_presave()?

# Answer
I used the Rules module for this. There is a condition like "User Profile Updated" or something like this which you can use. You have then the changed and the unchanged values as tokens available for example to e-mail somebody about the changes.
> 6 votes

---
Tags: 7, users
---


# Question
Title: Print #field_suffix with drupal_render($form['field_custom_text_field'])
I have a custom module that defines a field\_suffix for a custom text field

```
function custom_check_form_user_register_form_alter(&$form){
$form['field_url']['und'][0]['#field_suffix']='text goes here';
}

```

I then am calling the field in a user-register.tpl.php as

```
print drupal_render($form['field_reg_site_url']);

```

However, the #field\_suffix isn't printing (checked that the value is in the array - yes). It does work (same code pattern) for username. Any ideas what I'm missing?

# Answer
Try

```
$form['field_url']['#field_suffix']='text goes here';

```

Also, in your example, the suffix is being set on `field_url` but you are printing `field_reg_site_url`. That could be causing some confusion.
> 1 votes

---
Tags: entities, theming
---


title: Custom actions kicktart commerce cart

text:
# Question
Title: Custom actions kicktart commerce cart
Hi I've been struggling with this issue for a while, look for it from google to the official Drupal Commerce documentation without any luck. So i have a cart and I am customizing the looking and the behaviour, tpl and preprocess function have been my friend until now.

I need to custom the bottom actions of the cart

But I haven't been able to look for a tpl and I still don't know how to change the behaviour of this actions if you can give a hint of how to:

* Change the value of the of both of this action
* How to add more actions.
* How to change the behaviour of the items.

BTW. I look for it on the setting of the Views without any luck, but I'm kind of noob in drupal. Thanks!

# Answer
You need to create a custom module and use hook\_form\_alter to modify the form.

That particular form id is `views_form_commerce_cart_form_default`, so in your custom module, you could have something like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //cart form
  if (strpos($form_id, 'views_form_commerce_cart_form_default') === 0) {
    //change the value
    $form['actions']['submit']['#value'] = "New Update cart value";
    $form['actions']['checkout']['#value'] = "New Check-out Value";

    //add additional callback functions on the checkout button
    $form['actions']['checkout']['#submit'][] = 'mymodule_callback';

    //replace callback functions on the checkout button
    $form['actions']['checkout']['#submit'] = array('mymodule_callback');
  }
}

```

Refer to the Form API Reference to see what else you can do.
> 2 votes

---
Tags: commerce, entities, actions, javascript
---


# Question
Title: How to use field value as class? Drupal 7
Not sure that is the best title...

I want add a field to a content type eg. Priority. My preference would be to make this a taxonomy reference (with Autocomplete term widget (tagging)).

Then probably through a preprocess I would like to add any terms entered as classes to the node (in particular when a teaser but that's not important).

I am not the world's greatest php coder and apologise if this doesn't make a great deal of sense. I have been banging my head against the wall for three days now and any help would be greatly appreciated :)

I gather it has something to do with `MYTHEME_preprocess_node` and `$variables['classes_array'][]`, but I don't seem to be able to put my finger on it.

# Answer
> 4 votes
This should be a start.

```
function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];

  if (isset($node->field_foo["und"][0]["taxonomy_term"])) {
    foreach ($node->field_foo["und"] as $foo) {
      $term = $foo["taxonomy_term"];
      $variables["classes_array"][] = "term-" . str_replace(" ", "-", strtolower($term->name));
    }
  }
}

```

Note, this is barely tested and your exact situation may vary. It assumes `field_foo` is the machine name for your taxonomy reference, and your theme is flattening `$variables["classes_array"]` for use in `node.tpl.php`.

# Answer
> 0 votes
It's not that hard.

Your problem is that you are chaining the wrong variable, this should work:

```
function MYTHEME_preprocess_node(&$vars) {
  $vars['classes'] .= ' foo bar baz'; // $classes is a text string.
}

```

---
Tags: 7, taxonomy-terms, theming
---


# Question
Title: Views with node references result redundant records
I have three content types - Leg, Transport and Ticket. **Transport** has a node reference to **Leg**. **Ticket** has a node reference to **Transport**.
Thus, **Leg** and **Ticket** have an indirect way of relationship. But,**Transport** and **Ticket** have optional relationship.

I'm creating a view which lists transports of the given leg ( contextual filter ). In the list, ticket is needed to join to show ticket price. Here is my views settings :

The view result is not what I expected. It lists unnecessary and duplicate records as shown in the screen shot.
The first two records ( in the red box ) should not be listed here. They are redundant of the last two records ( in the red circle ). You can see prices are not showing for the first two.

Aggregation did not help me in this case.

# Answer
> 1 votes
I have found the most possible answer. It may need to update the query from `hook_views_query_alter()`. The generated query from views is here :

```
SELECT node.nid AS nid,
    field_transport_node.nid AS field_transport_node_nid,
    field_transport_node__field_data_field_price.field_price_value AS field_transport_node__field_data_field_price_field_price_val,
    node.created AS node_created,
    'node' AS field_data_field_dept_time_node_entity_type,
    'node' AS field_data_field_travel_time_node_entity_type,
    'node' AS field_data_field_transport_type_node_entity_type,
    'node' AS field_data_field_price_node_entity_type,
    'node' AS field_data_field_travel_optr_node_entity_type,
    'node' AS field_data_field_ticket_office_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_transport} field_data_field_transport ON node.nid = field_data_field_transport.field_transport_nid
LEFT JOIN {node} field_transport_node ON field_data_field_transport.entity_id = field_transport_node.nid
LEFT JOIN {field_data_field_leg} field_data_field_leg ON node.nid = field_data_field_leg.entity_id AND (field_data_field_leg.entity_type = 'node' AND field_data_field_leg.deleted = '0')
LEFT JOIN {field_data_field_price} field_transport_node__field_data_field_price ON field_transport_node.nid = field_transport_node__field_data_field_price.entity_id AND (field_transport_node__field_data_field_price.entity_type = 'node' AND field_transport_node__field_data_field_price.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('transport')) AND (field_data_field_leg.field_leg_nid = '2' ) ))
ORDER BY field_transport_node__field_data_field_price_field_price_val ASC, node_created DESC
LIMIT 20 OFFSET 0

```

I just need to add a condition with "OR". It gives me the correct result.

```
AND ( ( field_transport_node.nid IS NOT NULL AND field_price_value IS NOT NULL ) OR ( field_transport_node.nid IS NULL AND field_price_value IS  NULL ) )

```

How can I add this kind of OR condition from views UI ?
How can I do it with query object of the views ?

```
function mymodule_views_query_alter(&$view, &$query){
    switch($view->name){
        case 'my_view_name' :
            $query->where[0]['conditions'][] = array(
                'field' => '',
                'value' => '',
                'operator' => ''
            );
            break;
    }
}

```

# Answer
> 0 votes
My best guess here is that the relationship being optional is resulting in the use of a LEFT OUTER JOIN query that is joining with both some NULL row as well as the actual relationship row.

Why is the relationship between Ticket and Transport optional? If all Transports have ticket prices, it seems the easiest solution would be to mark the relationship as required in the view, so you are only pulling distinct transport/ticket combinations, and no transports w/o tickets.

I think that approach is also preferable to filtering out rows with no price, since it gets to the issue at the JOIN level.

---
Tags: views, nodes
---


# Question
Title: After programmatically creating a token, it does not get overridden
I have the function below in a module. After it runs once, the token never changes again. I have to disable the module, and re-enable it, to get the token to run. Do you have any idea why this happens?

```
function my_token_values($type, $object = NULL, $options = array()) {
    global $user;

   $rand = rand();
   if ($type == 'global') {
        $tokens['random-number-replace'] = $rand;
   }
   return $tokens;
}

```

# Answer
This ended up being a completely unrelated issue, but what was happening is that the token was getting set once, and then somewhere a custom module was checking if the token was set before setting it again.
> 1 votes

# Answer
Where are you using the token? Drupal may be caching information at a higher level (like the filtered output of a node, for example) and only calling the token generation code once.
> 2 votes

---
Tags: 6, tokens
---


# Question
Title: When switching themes in blocks, theme stays the same
I'm trying to add a block to a specific theme (garland), but no matter what theme I switch to, I'm always shown the admin theme.

If I only have a single theme (garland) enabled, I can access the blocks I need, but there has to be a reason for this.

Edit: Discovered that this is being caused by the module "RealName" I have no idea where to look for the culprit though. Any suggestions?

Edit2: Found this explanation, but no real fix. Suggestions?

# Answer
> 1 votes
Ended up using hefox's (from Drupal comments) fix

```
<?php
function realname_user($op, &$edit, &$account, $category = NULL) {
    global $theme;
  if (!$theme) return; // prevent realname from overiding theme on block pages
?>

```

I did add in my own code as a safeguard, in the if statement, the condition that we were on the blocks page.

---
Tags: 6, blocks, theming
---


# Question
Title: $user not updating and "Validation error, please try again." on form in block
I have a form that I am using in a block that was generating the error:

> Validation error, please try again. If this error persists, please contact the site administrator

Doing some research shows that it is to do with $session mismatches with the form token that cause this error.

Further to this I noticed that a default value I was using from the $user variable wasn't updating when I changed login.

Both of these together led me to the realisation that my block was being cached (confirmed by debugging and seeing that my form builder function was only being called after I cleared caches) so I changed caching of my block to `'BLOCK_NO_CACHE'`.

I am still getting the error and my $user isn't updating. Any ideas?

# Answer
> 2 votes
Just to answer my own question. In this answer to another question, Berdir mentions that Drupal 6 will not update your block information. The example given to do it in code is here but I just updated the cache field to -1 (BLOCK\_NO\_CACHE) in the blocks table.

---
Tags: blocks, users
---


# Question
Title: Drupal CSS broken in Internet Explorer 7/8, but works as static page
The CSS layout on my Drupal site was suddenly found to be broken in IE 7 & 8. No idea what happened to cause this, but the strange thing is, if I save the source/files, then upload and test as a static page, it works fine (well, good enough for Internet Explorer). I'm using Adobe BrowswerLab to test. I've turned off caching in performance and boost. I have also turned gzip compression off on the server, and added 10 second delay to browserlab load-time. Nothing seems to make the CSS work straight from the actual site. I haven't found any threads about this specifically. Does anybody know what might be going on?

I am using Drupal 6.24.

# Answer
Do you have CSS and Javascript caching enables? IE7 & IE8 can only load a certain amount of external files and you maybe exceeding the limit. Retry with CSS and JS caching enabled.
> 4 votes

# Answer
I had this issue too in a Drupal Commons 6x24 site: On a quick step I did toggle the CSS-aggregation, and switched it off.

Just have a closer look at this, here: Your lack of styles on the site is due to inadequate file permissions on your server. Your site is unable to save the auto-generated compressed CSS file, thus there is no style information to be displayed.

Installing a different theme would do nothing to fix this situation. If you cannot manage to get the proper files permissions set up, you may try disabling CSS aggregation by navigating to Administration -\> Site Configuration -\> Performance, and toggling off the CSS aggregation setting, then clicking the save button.
> 2 votes

# Answer
Looking at your source code and the number of modules noted in your jquery settings, it does look this is the IE CSS loader limit issue. IE will load 32 css files and only 32 -- any more than that and it just quits and refuses to load any. Here is a good testbed of this issue:

http://john.albin.net/ie-css-limits/993-style-test.html

When developing for IE, you will need to temporarily turn off css aggregation (which is on in your site) to get the styles to load. Another option (for Drupal 6.x) is to install the unlimted css loader module:

http://drupal.org/project/unlimited\_css

Which offers another option around this.
> 1 votes

# Answer
Also you could open the css file in another tab and check if IE found it or if return a error or something like that.

Sometime this happened to me when the css file had another encoding.
> 0 votes

---
Tags: theming
---


# Question
Title: Render user login form with custom theme
I have written a custom module, inside which I would like to create a custom user login block with custom theme applied. Now my question is "Inside my custom module, how do I get the user login form?"

# Answer
> 4 votes
You can use `drupal_get_form()` to get the rendered form:

```
$form = drupal_get_form('user_login');

```

To override the default theme for the form have a look at Theming the contact form in Drupal 6 which goes through all the necessary steps very thoroughly.

---
Tags: 6, users
---


title: Increment field value in update query

text:
# Question
Title: Increment field value in update query
I am converting some module from d5 to d7, and in old code there is an update query like this:

```
<?php
db_query("UPDATE {a_table} SET count = count + 1 WHERE field1 = %d", $some_value);

```

As we see, it is incrementing a field value (AFAIK it is a mysql feature). But, if I use new style of update it won't work.

```
<?php
db_update('a_table')
    ->fields(array('count' => 'count + 1',))
    ->condition('field1', $some_value)
    ->execute();

```

Are there any workaround within new style of db update without running an extra query to get existing field value to increment it?

# Answer
You can do it by adding an expression to the query:

```
db_update('a_table')
  ->expression('count', 'count + 1')
  ->condition('field1', $some_value)
  ->execute();

```
> 21 votes

---
Tags: 7, database
---


title: Terms in tree view - wrong order?

text:
# Question
Title: Terms in tree view - wrong order?
I wanted to list the terms that a node has in a tree view. I've gotten that far that the list, sorted by the parent, is done, but the terms is in wrong order. Some terms becomes childterms to the wrong parent.

How do I fix that?

```
function my_module_cmp($a, $b) {

$a = (array) $a;

$b = (array) $b;

return strcmp($a['name'], $b['name']);

}
// A block with the current nodes linked categories in a tree view

function myfunction_category_block_contents($delta) {

// get nid from URL

$nid = arg(1);

$node = node_load($nid);

// get the terms using that nid

$terms = taxonomy_node_get_terms($node);

usort($terms, "hr_torget_cmp");

// create the head

$html = '<div class="category-title">Kategorier</div>';

$html .= '<ul>';

$i = 0;

foreach ($terms as $term){

    // the tid

    $tid = $term->tid;

    // the name

    $name = $term->name;

// DEBUG    $html .= $tid.'<br>';

    // get terms

    $parents = taxonomy_get_tree(10,$tid,NULL);

    // if the term is a parent
    if ($parents) {
        $html .= '<li class="parent"><a href="'.base_path().'kategori/'.$name.'">'.$name.'</a></li>';
    }
    // if it isnt
    else {
        $html .= '<ul>';
        $html .= '<li class="child"><a href="'.base_path().'kategori/'.$name.'">'.$name.'</a></li>';
        $html .= '</ul>';
    }

$i++;

}

$html .= '</ul>';

$html .= '<img src="'.base_path().'sites/all/themes/hrtorget/images/verksamhet-bottom.png" alt="Bakgrundsbotten">';

return $html;

}

```

# Answer
If I only get your goal correctly, I would suggest: for each node - get attached terms - for each term - get taxonomy\_get\_parents\_all \- reverse the array to have parent-to-child chain - form a list into a tree

Forming a tree could be yet another function with logic allowing to merge terms that share branches.
> 1 votes

---
Tags: taxonomy-terms
---


# Question
Title: Live site still taking nodes url as localhost/
I have developed a Drupal site on localhost; I then exported it to a production site, and made the required changes in settings.php. The index page opens fine, but when I log in, the URL is still referring to localhost. I tried to set the base URL in settings.php, but it did not help.

I am using Drupal 7.10.

# Answer
> 0 votes
Try clearing all Drupal caches at yourwebsite.domain/admin/config/development/performance

---
Tags: nodes, uri
---


# Question
Title: Check performance of drupal websites using some modules or tools
My website starts well and after few days of access it goes terribly slow. Is there any module or any external tool to check the performance of the drupal website. So that we can point out where we are facing issues in drupal so that we can solve them. My pages are built out of average 5-6 views, does this effect the performance of the website ?

# Answer
> 7 votes
You could try new relic, it will give you insight into how expensive database queries are or where you have a bottle neck which is slowing down your site. It has some integration with Drupal and could also show you if you have a problematic module...

Also if your pages use a lot of views, have you tried caching the views? It is part of default views module, go into your view edit under "advanced" on the right. Click caching and turn this to time based. This means that rather than running each view query / view rendering on every page load - It will run it on the first load and retrieve a cache until it expires. The caveat here is that you will have a lag on the results for how ever long you choose to cache.

# Answer
> 5 votes
If you have ssh access to your server you can install XHProf and than add the Drupal module.

> XHProf is capable of reporting function-level call counts and inclusive and exclusive wall time, CPU time and memory usage. Additionally, it supports ability to compare two runs (hierarchical DIFF reports), or aggregate results from multiple runs. Originally developed at Facebook, XHProf was open sourced in Mar, 2009 (source)

I'm using it frequently and it really helped me find some bad bottlenecks.

# Answer
> 3 votes
You may use the Boost module. Here is more info on it: http://www.onyxbits.de/content/quick-drupal-performance-test-boost-module-makes-huge-difference.

> Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic. Boost is very easy to install and has been throughly tested on Shared, VPS and Dedicated hosting. Apache is fully supported, with Nginx, Lighttpd and IIS 7 semi-supported.

---
Tags: 7, performance
---


# Question
Title: How many web pages can the Panels module handle?  What's the performance impact?
I'm creating new site in Drupal 7, and I must use about 400 panel pages with Views. I'm wondering how many panel pages I can use in my site without affecting performance? Can Drupal/Panels handle 400 panel pages?

# Answer
There is no reason to believe that "Panels is slow". This is a misconception created by the fact that Page manager and Panels modules are complicated, and not easily understood.

Panels is actually sometimes faster than core is on it's own. And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.

At NodeOne, we build *all* our sites using Page manager, Panels, and Panels Everywhere. I have yet to see a performance problem caused by the use of Panels itself. That said, you should consider using Caching, as a website utilizing Panels well is most likely a complex one. (I'm no longer with that business, but this remained true for as long as I was)
> 4 votes

---
Tags: 7, views, panels
---


# Question
Title: i18n 1.4: Use of undefined constant MENU_PREFERRED_LINK
Has anyone run into trouble following i18n update to version 1.4? My site crashes badly with multiple notices about use of undefined constant MENU\_PREFERRED\_LINK. This is caused by Menu translation submodule.

Submitted a bug report but thought maybe someone found out a cure for that.

# Answer
In case someone bumps into that: apparently the i18n module is not compatible with Drupal 7.9. After I updated the core to 7.12 - all problems went away. Haven't seen the module to mention a particular D7 release as a requirement, though.
> 2 votes

---
Tags: routes, i18n-l10n
---


# Question
Title: Take all sites in a multisite environment offline at the same time
Is there an easy way to take all sites in a multisite environment offline at the same time, in just one step? I really don't want to log in to each one and do it one at a time when I do something that involves all of them.

# Answer
Assuming you have drush working, and have proper site aliases set up, the following should work:

```
drush @sites vset maintenance_mode 1

```

Turn take them all out, do

```
drush @sites vset maintenance_mode 0

```

If you are on Drupal 6, use `site_offline` instead of `maintenance_mode`.
> 2 votes

# Answer
If you have drush installed you could use this snippet:

```
#!/bin/bash
sites[0] = "http://www1.example.com";
sites[1] = "http://www2.example.com";
sites[2] = "http://www3.example.com";

for site in $sites; do
  drush vset --always-set --uri=$site site_offline 1
done

```

I'm not an expert in sh scripting but something like that should work.
> 2 votes

---
Tags: multi-sites, maintenance-mode
---


# Question
Title: How to create a path alias with a query string in the target?
I want to link `/myownstuff` to `/stuff?owner=myself`

It should at least be possible to do with some module, and with httpd-level configuration, but I don't know how to achieve either of them.

# Answer
> 4 votes
I *think* you can do this with the Redirect module (it won't provide an alias in its truest form but it will forward you on to the right page.

In `.htaccess` you could a custom RewriteRule before Drupal's main index.php rule:

```
RewriteRule ^myownstuff$ stuff?owner=myself [L,QSA,R=301] # QSA and R=301 are optional here

```

If neither of these work there is a quick and dirty way in a custom module:

```
function MYMODULE_init() {
  if ($_GET['q'] == 'myownstuff') {
    drupal_goto('stuff', array('query' => array('owner' => 'myself')));
  }
}

```

If you've got more than one path to forward/a pattern etc. you'll have to extend this a bit but the logic will work.

I think the `.htaccess` is probably the best way as it doesn't actually forward on to the URL but masks it internally which I guess is what you're after.

You might also want to look at `hook_url_inbound_alter()` which I believe you can use to get this kind of functionality...I've not used it before so I can't comment further though.

---
Tags: path-aliases
---


# Question
Title: Alter and set a id attribute for a field in drupal 7
Can anyone help me how to alter a field attribute in drupal 7. Let say i have created a field name hello\_test with label as hello.Now I need to alter the label and set a attribute for the filed in template.php file in my theme.Can anyone help me

# Answer
> 2 votes
You will want to implement template\_preprocess\_field() in your theme's template.php

Also helpful to you will be the drupal.org documentation on Overriding Themable Output.

---
Tags: 7, theming
---


title: A Content Type with custom fields

text:
# Question
Title: A Content Type with custom fields
How would you suggest approach this using Drupal 7?

I'd like to create a 'Video' content type with the usual videos fields but I would also like each individual video content type to have many images attached, with each image having fields of it's own.

Basically, each content type would require one video and many images, with fields relevant for each image.

I've looked for duplicate questions and can't see anything that fits but if you know of something please point me in the right direction.

Thanks,

# Answer
> 6 votes
Field Collection is a good option if the images will not be re-used across multiple Video content types. If you need to re-use the Images (and their field values) across multiple Video nodes, another option is to create a separate "Image" content type and use the Entity Reference module to link the Image nodes to the relevant Video nodes.

# Answer
> 1 votes
It sounds like the Field Collection module might help you out.

---
Tags: 7, nodes, entities
---


# Question
Title: Proper backup procedure for remote site?
I know variations of this question have already been asked here, but I could not find proper information on details for a backup procedure for a remote site. I am still new to Drupal.

Assuming a host handles multiple Drupal 7 sites under a `/public_html` directory, using the same MySQL installation:

```
/public_html/my_drupal_site_1/...
/public_html/my_drupal_site_2/...
/public_html/my_drupal_site_3/...
...

```

I see two situations to consider: i) Drush is not installed on the remote host, ii) Drush is installed on the remote host.

Regarding i), that is, Drush is not available:

1. What would be the proper step-by-step procedure to backup and restore `my_drupal_site_2` on the remote host from a local pc, assuming the `Backup & Migrate` module is installed on this site?
2. Which part of the directory tree should be copied (eventually with FTP)?
3. Which part should be restored?
4. How to make sure only the part of the database for `my_drupal_site_2` is backup and restored?
5. Does one need to create a database before restoring the back up?
6. Does one need to create an 'empty' Drupal site before restoring?

Regarding ii), that is, Drush is available, say via SSH on the remote site:

1. What would be the proper step-by-step procedure to backup and restore `my_drupal_site_2` on the remote host from a local pc, assuming the `Backup & Migrate` module is installed on this site?
2. Is there a way to synchronize a local directory tree from the remote directory tree? The idea is to put this content under subversion or git for example.

At last, is there a all-in-one solution? Like a script that could do everything at once? Thanks.

# Answer
> 1 votes
1. You set a path for manual and automatic backups in Backup & migrate module. You get the resulting tar.gz file using ftp to your local machine for backup. If you want to restore, from within the module you choose file to upload.
2. For the db backup just the generated file, for the files the /my\_drupal\_site\_1/sites/ directory
3. See #2
4. You can create a new profile in Backup & Migrate module and select which tables to backup (restore only restores what was backed up so you are ok there). Partial backup requires a lot of caution as to not forget necessary tables.
5. If you are restoring to an existing site NO, if it is a migration you are after YES
6. See #5

I think you are better of using i rather than ii, as using drush is a lot more "technical" and mistake prone.

As for you last question, yes... use Backup & Migrate to create a DB backup file on the server and then get everything using FTP. Even better use CPanel or Plesk and backup Home and mySql alltogether.

---
Tags: 7, migrations, backups
---


# Question
Title: How can I create a Drupal "Page" (not a block) without any theme?
How can I create a Drupal "Page" (not a block) without any theme? I do not want this "Page" to include any header / footer / left / right column. My understanding is that this isn't possible but could I create an additional theme for my site which is just completely blank, and apply this to the appropriate pages? We have a salesman that wants to build his own set of pages within Dreamwever and then I would apply this blank theme against just these pages without impacting the existing theme that is utilized for the other pages.

# Answer
> 0 votes
If your user is going to create pages in Dreamweaver, then just have him upload the files into a subfolder of the Drupal root directory...and they will load completely independent of Drupal.

IE:

Drupal Directory == /foo/bar/htdocs/mydrupalsite Drupal URL == blah.com/mydrupalsite

User's DW files directory == /foo/bar/htdocs/mydrupalsite/dwsite User's DW URL == blah.com/mydrupalsite/dwsite

His pages will not be affected by Drupal at all. You just have to be careful when upgrading/updating that you leave his folder structure intact.

With this method, you don't have to do any htaccess redirects or anything like that.

# Answer
> 3 votes
Try the ThemeKey module.

This module has a number of really useful options; relevant to your question, you can have it use a different theme or a stripped down version of your existing theme on certain paths or conditions.

---
Tags: 6, theming
---


# Question
Title: How to change date format to custom in Views? (drupal 6, views2)
I have a view that includes a CCK date/time field. It automatically displays the date like this if I choose Long as the format:

Tuesday, April 17, 2012 - 13:30

I need it to display in 12-hour time, not 24-hour, but the view field config doesn't allow me to enter a custom format for my date (for the label, yes - the actual value, no). How can I override the date formatting for just this one view?

**EDIT**

Never mind; I found a way to do it here.

# Answer
Answer found here. Basically, you create a new date format in admin that is then available sitewide in any date format dropdown.
> 0 votes

---
Tags: views, 6, entities
---


# Question
Title: Attach jQuery behavior to AJAX loaded content
I would like to add some jQuery behavior to a page using the FAPI #ajax behavior (a Commerce product reference add to cart form)

I used a custom module (Commerce Taxonomy Field Product Attribute) to replace the standard text output of the taxonomy term attribute by an image, and hide the radio button of the add to cart form via CSS (display: none). The goal is to let the user click on the image label to select his product's color or size. See a screenshot without css, and with css

I added some custom jquery that adds a "hover" and "selected" class to the label (on mouse over and clicked event) in order to have a ui feedback via CSS - as the Commerce add to cart form uses radios element, there is no "hand" mouse pointer on hover, which can be quite disturbing for the UI. --\> It works fine the first time the page is loaded but doesn't get attached when a product is reloaded by ajax.

I have a JS file with

```
Drupal.behaviors.custom_danity_afficheur_produit_label_hover = {
  attach: function (context, settings) {
    //All the code that attaches the click / hover event functions using jQuery.once()
  }
}

```

I tried loading the JS file at different level :

1. in the template .tpl.php file
2. in the add to cart form alter hook in
3. a function callback on the add to cart form #post\_render attribute

None of these work, the AJAX only works the first time it is loaded.

It's not the first time I try to add jQuery code to an ajax loaded content - I managed last time to modify the code and use FAPI Ajax to make it work - but here i don't know how to do it as the product attributes already have an Ajax behavior implemented by Commerce... and as far is i know, it's not possible to attach multiple ajax behavior to an element with Drupal FormAPI

Any help would be much much much much much appreciated :-)

# Answer
> 1 votes
Ok I managed to make it work.

Drupal did try to re-attach the behavior on my content after it was added by AJAX, but my selectors were starting from too "early" in my DOM - as such, when drupal.attachBehavior got called by the system, it couldn't find the right selector.

Example : My DOM look like this :

```
<div id="product-add-to-cart">
    <div class="class1">
        <input ... class="input1" />
        <input ... class="input2" />
        <input ... class="input3" />
    </div>
</div>

```

My jQuery selector looked like this $('#product-add-to-cart .class1 input.input1").hover(...);

As I understand, FormAPI was replacing what was INSIDE `#product-add-to-cart .class1`, while the context passed to Drupal.attachBehavior only had part of this markup (the input elements..) : hence `$('#product-add-to-cart .class1 input.input1").hover(...);` couldn't return anything in this context.

I replaced my jQuery `$('#product-add-to-cart .class1 input.input1").hover(…);` with `$('input.input1").hover(…);` and it works like a charm.

---
Tags: ajax, javascript, commerce
---


# Question
Title: Given a field for Content Profile for a user, how can I extract that field via code?
I have a location field for a user that is created via the Content Profile module.

How can I access that field in code for the logged in user? Is it something like $user-\>content\_profile\['location'\]

I can't seem to grab this info.

# Answer
> 4 votes
You'll have to load the content profile node into a variable first using `content_profile_load`.

This should work:

```
$user_profile = content_profile_load('profile', $user->uid);

```

That will return an object ($user\_profile) that you can call the fields which you've set up. Use

```
echo '<pre>'.print_r($user_profile,1).'</pre>';

```

to see which fields are available.

---
Tags: 6, users
---


# Question
Title: Trouble populating text field widget while executing node.create through Service using Rest server
I have a Rest server running using the Services module which is setup to receive node and user requests. I have also created a new content type with the following fields:

I am able to add new instances of this content type using Poster (a Firefox plugin for creating http-post requests) using an http-post to my rest server with the following body (using application/json content-type):

```
{
  "title":"online submission",
  "type":"basic_content",
  "field_text":[
    {
      "value":"Some Text"
    }
  ]
}

```

I have tried many different variations of this json string (including make it all one line) and it never seems populate the text field. Could anyone shed any light on this? I am willing to use a different content-type if necessary.

# Answer
Field values need to be surrounded by an array, which holds all the potentially multiple entries for the field, and yet another array which holds all of the potential translations for the field.

In PHP that looks something like this:

```
$node->field_text['und'][0]['value'] = 'Some Text';

```

I haven't tested it but I'd guess the JSON equivalent would be something like this:

```
"field_text":
{
  "und":
  [
    { "value": "Some Text" }
  ]
}

```

That may need a bit of tweaking.
> 1 votes

---
Tags: 7, nodes, services
---


# Question
Title: Creating an "unzip" module that can interface with Content created through the GUI and through node.create by was of Services module (Drupal 7)
I am creating a website that will allow users to upload projects. Project submissions will consist of a couple of text fields, a screenshot and a .zip file. Once the user uploads their project, I need to unzip the .zip file and catalog its contents. Also, it needs to be possible to upload these projects through the web interface "Add New Content" and through Node.create by way of the services module.

So my first question, is there a way to hook up a module that will be triggered after a content type is created? I built my project content using the built in Drupal 7 CCK editors but I see no way to hook up some code to this that could unzip my file and then do whatever else needs to be done.

Now if the above is not possible using CCK does that mean I need to recreate this content type by making it into its own module?

Finally, where would be the best place to put this unzipping code? I could see it might be cleaner to make a standalone module for unzipping but might it be easier to put this code directly in the content module (if I have to make one)?

# Answer
I think the best place for your code is in a custom module, in `hook_node_insert()` and `hook_node_update()`; they're fired when a node is created and updated respectively. As the services module uses the standard node save/submission functionality these hooks will be fired even when using services.

It would make sense to keep your un-zip code in that same module.

This is a brief example just to show what I mean:

```
function MYMODULE_node_insert($node) {
  // Get the file ID from the node field
  $fid = $node->field_file[$node->language][0]['fid'];

  // Load the file
  $file = file_load($fid);

  // Pass the file path off to the unzip function
  $result = _my_unzip_function($file->uri);

  // Do the rest of your processing...
}

```
> 1 votes

---
Tags: 7, entities, nodes
---


title: triggering email from custom module

text:
# Question
Title: triggering email from custom module
I have a module that uses hook\_menu to create several pages that are populated with SQL query results.

I have been trying to configure drupal\_mail and hook\_mail to send these results via mail when the pages are visited, but so far I haven't succeeded.

I used the info I found here and indeed, the module works: whenever I run cron the sample mail is sent, but I haven't found the way to customize it in my module so when I load my custom pages the results are sent via mail.

Also, if my data is the result of:

```
function mystats_all() {

$header = array('Nombre', 'Status', 'Rol 5 = Alumno', 'Email' );

$query = "
SELECT name, status, rid, mail
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@example.com'
AND users_roles.rid =5
AND users.status =1
";

$result = db_query($query, $some_value);
    while ($row = db_fetch_object($result))
    {
        $rows[] = array(
                    array('data' => $row->name, 'align' =>'left'),
                    array('data' => $row->status, 'align' => 'left'),
                    array('data' => $row->rid, 'align' => 'center'),
                    array('data' => $row->mail, 'align' => 'left'),

        );
    }

    $table_attributes = array('id' => 'my_id_for_table', 'align' => 'center');
    $output .= theme('table', $header, $rows, $table_attributes);

    return $output;

```

how can I correctly send my table via mail? I don't know (and I would like to have the drupal\_mail function working to make some tests) if I should use $query or $result.

Thanx in advance.

Any ideas or help, please?

# Answer
You need to implement hook\_mail() in your custom module and then call drupal\_mail() in your page callback function to get the result you want. You should save your table html in the `$params` array that gets delivered to `hook_mail()` and then set it as the `$message['body']` value there (with additional html/data if needed). The linked tutorial and API pages should give you enough information and examples to work out the rest of the details.
> 1 votes

---
Tags: 6, hooks, emails
---


# Question
Title: Suggest a page template for a specific view
I have a view **news** how do you a suggest a particular theme file for it? For example page--news.tpl.php?

# Answer
> 1 votes
In case of Views 2, One of the option would be to name your template file "views-view--news.tpl.php".

There are other useful options like "views-view--news--page.tpl.php" or "views-view--news--block.tpl.php" depending on your display type.

You may find This tutorial useful .

---
Tags: views, theming
---


title: Rule for when content is published?

text:
# Question
Title: Rule for when content is published?
I have the scheduler module installed, and i am using rules to notify users when new content is published.

The scheduler module is working perfect, i enter a future date and time for the content to be published. The content is published on the exact date and time.

Rules cannot action on this because there is no event coming with rules that allows me to perform some action when content is published, only when content is saved.

So my question is, how can i rules perform an action when content is published in a future date?

thanks in advance

# Answer
> 3 votes
I believe you are looking for something like this module

> Rules: when Triggers won't do, use the event-condition-action paradigm of Rules. More complicated to set up than Trigger, but very powerful. Revisioning adds its own events and conditions to Rules, for example "content is about to be published" and "content has pending revisions".

and

> Revisioning is integrated with Rules, adding a number of revision-specific conditions and events.

---
Tags: 7, rules
---


# Question
Title: Getting a true http address from file object's uri (Drupal 7
I have created a little module to try and unzip files that has just been uploaded through node creation. Here is my unzip function (the $file parameter is a file object):

```
function unzip($file) {
  watchdog('beep','Unzipping a project!!');
  $zip = new ZipArchive;
    //This Works
    $res = $zip->open(drupal_realpath($file->uri));
    // This does not
    //$res = $zip->open($file->uri);
  if ($res === TRUE) {
    $zip->extractTo("/Applications/MAMP/htdocs/sites/default/files/");
    $zip->close();
    watchdog('Zip sucess','Unzipping worked!' . drupal_realpath($file->uri));
  } else {
    watchdog('Zip Failure','Unzipping failed for ' . drupal_realpath($file->uri));
  }
}

```

Included in this snipet are two different ways I attempted to open the zip file.

This first one works on my local MAMP server but would not work on a producitons server:

```
$res = $zip->open(drupal_realpath($file->uri));

```

This created a path like this:

```
/Applications/MAMP/htdocs/sites/default/files/Tumble arcade file_5.zip

```

and

```
$res = $zip->open($file->uri);

```

creates a path like this:

```
public://Tumble arcade file.zip

```

Now the first path is interpreted correctly by $zip-\>open and the file is unzipped correctly but with the second path, the zip open fails. I believe this is happening because php does not know how to handle the second path and needs something more like this:

```
http://localhost/sites/default/files/Tumble%20arcade%20file_5.zip

```

Am I on the right track and if so how would I get this other kind of path? If not, any idea what might instead be the problem?

# Answer
> 2 votes
There's a nice in-built function, `file_create_url()`:

> Creates a web-accessible URL for a stream to an external or local file.

e.g.

```
$url = file_create_url($file->uri);

```

---
Tags: files, uri
---


# Question
Title: Saving default field values on node_insert
I would like to automatically save a CCK field which will be determined by the data in the `$node` object. Using `node_save` in this instance will cause an error so I need a way to simply insert the additional field into the database.

One obvious way is to simply call `db_insert` but I'm not sure that this is the best way to do this since most of the information in this table is automatically generated and I'd like to leave that up to Drupal if I can.

What is that standard approach in this case?

Thanks!

# Answer
> 3 votes
You could probably do this in `hook_node_presave()`, e.g.:

```
function MYMODULE_node_presave($node) {
  // Get a value made up of other submitted fields, e.g.
  $computed_val = $node->field_first[$node->language][0]['value'] + $node->field_second[$node->language][0]['value'];

  // Assign that value to the other field
  $node->field_computed_field[$node->language][0]['value'] =  $computed_val;
}

```

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


title: Use views to create a custom sql query?

text:
# Question
Title: Use views to create a custom sql query?
I'm still not comfortable writing sql queries. As i'm pretty new to drupal module writing.

Are there any potential issues with using views to generate a sql query? In terms of security or future considerations?

**Example:** Generate a form dropdown on the usermenu of number of users by role.

**Grabbed this query via creating a view**

```
  $query = "SELECT users.uid AS uid,
   users.mail AS users_mail,
   users.name AS users_name
   FROM users users
   INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
   WHERE users_roles.rid = 7";

```

Convert database object into array:

```
while ($user = db_fetch_object($result)) {
  $reps[$user->uid] = $user->users_name . ' - ' . $user->users_mail;
}

```

Spit out the options and create a form dropdown:

```
// Generate output of all the client reps
$form['Business']['profile_txi_account_rep']['#options'] =  $reps;

```

# Answer
The only real downside that I can think of is that the SQL that is generated can be really verbose, as it is not meant to be read by humans.

Very often, I will take a first pass at functionality for something using Views, grab the SQL, and then refine/optimize. In fact, using Views to generate the initial SQL can be very handy for figuring out what you need to do your JOINs on.

One catch is that Views knows about internal structure. If you do something that changes underlying table structure, Views will compensate automagically. You would need to update your SQL manually. One place this happens is with Drupal 6 and CCK, when you change fields from single value on a single content type to multiple value and/or add them to multiple content types.

All of that said, the new database abstraction layer and EntityFieldQuery does make life easier, and you may not need to use Views as an intermediate step.
> 4 votes

---
Tags: views, 6, database
---


# Question
Title: How to print the url and the filename from image field in views-view-unformatted.tpl.php in Drupal 7?
I tried using this code, but it does not work.

```
<?php print $node->field_slider_image['und'][0]['filename']; ?>

```

# Answer
The full file object isn't necessarily loaded into the node object, you could try loading it manually and grabbing the filename/URL that way:

```
$file = file_load($node->field_slider_image['und'][0]['fid']);

// Filename
print $file->filename;

// URI e.g. public://image.jpg
print $file->uri;

// URL e.g. /sites/default/files/image.jpg
print file_create_url($file->uri);

```
> 3 votes

---
Tags: views, media
---


title: Creating an exam system

text:
# Question
Title: Creating an exam system
I am trying to create an examination system with Drupal, and I am not sure how to implement it. I can see many ways to do it, but I am not sure which one is the best way to achieve it.

These are the features am looking at:

* Users should have the ability to add questions under different subjects.
* Users will take test by answering optional answers (radio buttons).
* Users can move back and forward between answers and mark for later reviewing.
* In the end the result will be shown.
* Users can also choose the number of questions they want, and the difficulty level.

What is the best way to achieve this? This is what I am doing.

1. I added a content type question.
2. I added `options` field for answer option and `right-option`field for the right answer.
3. I added a drop down field for difficulty level.
4. I created a taxonomy term list for subject and connected with content type.

From here, what is the best thing to do?
Is creating a view page and giving the limit as per page one a good idea? If so how will I give the options of answer as radio/options, or should I create a custom page from module and take the answers using JSON?
What will be the right and easiest way to achieve this?

# Answer
> 2 votes
Maybe you could use the Closed Question module.
You can find more information about the module here.

> ### Features
>
> * Designed for practicing: students can take as many attempts as they like.
> * Many feedback options, feedback can change with attempts.
> * Many question types.
> * Questions can be added anywhere in a site.
> * Only Questions. Ordering questions in a quiz or case is done by a separate module.

# Answer
> 2 votes
I am looking to perform something similar for a project. I have not gotten into more than a cursory consideration yet, but would immediately recommend looking at the Quiz contributed module. Its V7.x version is still a dev. level module, but if it appears to do everything and more that you could want. If not, check out the related modules on the project page.

At the very least, it will provide a reference for how to accomplish many of the tasks you will need to meet your requirements.

As Kolo mentions, Closed question also relates to your concept and it has another list of related projects. Please return to this question and let us know what you find out as you investigate, I am interested in what you learn!

---
Tags: 7
---


# Question
Title: Get all orders that contain a certain product
I am trying to create a rule so that when a node containing a commerce product is update will notify all customers that have made a order containing this product.

I act on event "After updating existing content" and get to the commerce product using entity has field (field\_product). How can I get from the product to all the orders containing it so I can loop through them?

# Answer
I ended up creating a module for it as it didn't seem possible to implement using rules.

here is the function that is called on hook\_node\_update

```
//load all pending orders
$orders = commerce_order_load_multiple(array(), array('status'=>'pending'), TRUE);
//go through the loaded orders
foreach($orders as $order){
    //load each order as an entity
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
        //check if the order contains this node's product
        $product = $line_item_wrapper->commerce_product;
        $node_product = $node_wrapper->field_product;
        if($product->sku->value() === $node_product->sku->value()){
            //change the status of the order to processing
            $order_wrapper->status = 'processing';
            $line_item_wrapper->save();

            $order_wrapper->save();
        }
    }
}
return TRUE;

```

Now since I got the respective orders to processing status, I can go on using rules for the rest of the implementation.
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Populating file fields with an http-request with the Services module and a REST Server (Drupal 7)
I need to add content trough a node.create and one of the fields in the content type I am adding is a file field. So far I have been able to get my Services module set up with REST server to accept user and node resources and I have been able to make http-requests to add content containing text fields. Now I need to expand on this to work with a file field but I have not been able to find any resources about creating nodes that contain file fields. I am wondering how would this be done? Would it be done in one pass or two? Would I upload the file with a first post then do the association next? Does anyone have any good resources related to this topic?

# Answer
> 4 votes
Currently services doesn't offer the ability to add a file to a node in ONE method call, but thats easily within the scope of what services can offer, its just not in services core.

Currently you can make a request to create a file and get the returned FID, then you can process to submit a node with the field structure for a file field.

Which is something like

{"nid":1, "field\_image":{"und":\[{"fid":2}\]}}

Forgive me thats very rough, but you can can use devel to look at an already existing node with an image attached and mimic that in your submission and it will work.

The current process is:

POST to /file

get returned FID

PUT to /node make sure to have nid and field\_\* in the correct structure or it won't stick.

---
Tags: files, services, 8, nodes
---


title: How to to write Computed_field code?

text:
# Question
Title: How to to write Computed_field code?
I'm testing the computed\_field module on a taxonomy field. I want to get the number of nodes that have a term reference to the current term:

```
$tid = 1;
$entity_field[0]['value'] =  db_query("
SELECT count(*)
FROM node n INNER JOIN taxonomy_index t on n.nid = t.nid
WHERE n.type = 'discussion'
and n.status = 1
and t.tid=$tid")->fetchField();

```

How can I get the tid of the term? Is there a better way of writing the query?

# Answer
A query like that should do the trick, but if you want something more elegant, I recommend EntityFieldQuery.
> 1 votes

---
Tags: 7, database
---


# Question
Title: can't find how to use Backup and Migrate module
I've installed the module and enabled it.. the brief readme instructs me to go to `mysite.com/admin/content/backup_migrate` but when I go there I just see the same content as `mysite.com/admin/content/` how am I supposed to use this module?

Any idea what might be wrong?

# Answer
In Drupal 7 it is mysite.com/admin/config/system/backup\_migrate
> 2 votes

# Answer
Also, be sure to have the help modules installed and go here for help using the module:

yoursite.com/admin/help/backup\_migrate
> 1 votes

---
Tags: 7, database, backups
---


title: hook_menu not rendering page or form

text:
# Question
Title: hook_menu not rendering page or form
I'm using 6, and I CANNOT get hook\_menu to take me to the page where the form is. I go to www.myurl.com/test\_form (and for good measure, www.myurl.com/?q=test\_form) to check.

If I clear the caches, then I get a WSOD. If I don't, I get a 404. I have changed permissions and cleared caches and tried to figure out what Drupal wants with no luck. What did I do wrong?

```
function module__menu() {
      $items = array();
      $items['test_form'] = array(
            'title' => 'New Form',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('module_form'),
            'description' => 'Form',
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
      );
      return $items;
}

function module_form($form_state) {
$form = array();

    //my form stuff.....

    return $form;
}

```

UPDATE: Thanks for the advice. Did what you guys said. Still no luck. Error log doesn't show any errors either, so I'm totally lost here.

# Answer
> 3 votes
You've got two underscores in your menu function declaration, try changing it to:

```
function module_menu() {

```

Other than that your code is fine, although on the off chance you're using this module to create a custom content type I'd recommend changing the name of your callback function so you don't get a collision with `hook_form()`.

# Answer
> 2 votes
You have 2 underscores in hook\_menu():

```
function module__menu() {

```

should be

```
function module_menu() {

```

Edit: Also, your module name should not be "module" (in the assumption that the code you provided is your actual code). Also `hook_form()` is already a Drupal hook so you should not be using a function called `mymodule_form` to provide your own standalone form. Try `mymodule_form_description_form()`.

# Answer
> 1 votes
Try clearing the cache; it happened a lot of times to me, due to the menu being cached.

---
Tags: 6, routes
---


# Question
Title: Strange question pertaining views as forms?
I am attempting to provide quizzes in Drupal. The Drupal quiz module is out of question as a version for Drupal 7 does not exist. The way to go about doing this then IMHO is using web-forms. I am treating each question that is part of the quiz as a separate node entity.

The idea is to cluster these questions based on taxonomy vocabularies and establish a quiz. Clearly the best way to have nodes together would be VIEWS with some filter criterion. However, this clearly backfires. It establishes the required set of questions as a view. But this does not necessarily establish them a single quiz form, but rather a set of individual forms all present in the single page. Essentially, if my view has 10 questions, then it has 10 SUBMIT buttons.

My aim is to try and create this view as a form, but I think that is not possible anymore. I feel I should just post this here, regardless to get an answer or alternative ways to go about doing this.

# Answer
> 0 votes
I'm not sure Views would be the way I'd go with this. It's for getting data displayed from the database and this just seems like you're stretching the scope of what it's designed to do.

Is there any reason each question has to be on a different node? That seems to be adding even more complexity.

My suggestion would be to use webform to a the form for each different quiz. Especially if site administrators will have to create the quizzes regularly as webform offers the best UI for doing this. The difficult bit then is to write some sort of add on to webform (I don't know how much of an API webform has) that changes how the form is submitted and validated to be more 'quiz like'.

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


# Question
Title: Commerce - Views - Taxonomy - Add to cart issue
I am constructing an e-shop using Drupal Commerce. I've arranged my products in Categories and Subcategories using taxonomies and taxonomy-menu. All is nice till now. I also created a view, that displays the subcategory's items, with an 'Add to cart' form as a field.

Clicking the 'Add to cart' button **does** adds the item to the cart.

The cart's block **is** is configured to link each line item to it's display path.

The issue occurs here: products added from their perspective nodes, are linked correctly (to their perspective display paths) in the cart. Products that were added via the view's 'Add to cart' button, are plain text, and their 'Display Path' field is empty.

I'm puzzled. Any help?

# Answer
> 0 votes
Quoting Ryan from the Commerce Guys that answered the question clearly in Drupal.org (http://drupal.org/node/1430146#comment-5577538):

"The problem is the "Add to Cart form" Views field that you're using doesn't have the node context. As far as the node and the View are concerned, that View is the sole place you're displaying that Add to Cart form. What you'd really need to do is to have the actual Product Reference field from the node rendered. When that happens, Views will load the full node and its field will be rendered individually - and it's during that process that it adds the node context to the Add to Cart form for use in the display\_path field."

And problem solved!

# Answer
> 0 votes
Instead of rendering fields including the 'add to cart' form as a field, try rendering the full node using a particular view mode which includes the 'add to cart' form. See http://drupal.org/node/1399434#comment-5450456

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


title: Quicktabs: output divs instead of list

text:
# Question
Title: Quicktabs: output divs instead of list
I am quite new to theming, and I am trying to figure out the right way of theming Quicktabs in D7. I would like to output the tabs as divs instead of as a `<ul>` list. Looking at info from Theme Developer tells me that the Quicktabs are defined by `qt_quicktabs_tabset` which in turn calls `theme_item_list()` .

I could override `theme_item_list()` in my `template.php` file, but it would require a lot of tweaking because the `theme_item_list()` is designed for outputting a list. So for the moment my approach is to make a new theme function available in a custom module like this

```
function mymodule_theme() {
  return array(
    'mymodule_hook' => array(
      'variables' => array ('parameter' => NULL),
    ),
  );
}

function theme_mymodule_hook($variables){
  //here I can output my tabs as divs
}

```

and calling this in this way in `template.php`:

```
/**
 * Theme function to output tablinks for classic Quicktabs style tabs.
 *
 * @ingroup themeable
 */
function mytheme_qt_quicktabs_tabset(&$vars) {
  $variables = array(
    'attributes' => array(
      'class' => 'quicktabs-tabs quicktabs-style-' . $vars['tabset']['#options']['style'],
    ),
    'items' => array(),
  );
  foreach (element_children($vars['tabset']['tablinks']) as $key) {
    $item = array();
    if (is_array($vars['tabset']['tablinks'][$key])) {
      $tab = $vars['tabset']['tablinks'][$key];
      if ($key == $vars['tabset']['#options']['active']) {
        $item['class'] = array('active');
      }
      $item['data'] = drupal_render($tab);
      $variables['items'][] = $item;
    }
  }
  //normally theme_item_list() is called: return theme('item_list', $variables);
  return theme('mymoduletabs_hook', $variables);
}

function mytheme_mymoduletabs_hook($variables){
  //here I can finally output my tabs in divs
}

```

It's the first time I try this approach and would appreciate feedback. The intricacy of my solution worries me a bit - am I on the right path here?

# Answer
> 1 votes
jQuery seems to be the way to go if you want to manipulate the markup output by Quicktabs.

```
 /*we only want to append the data once hence the condition */
 if (!($('#quicktabs-my_tabs .quicktabs-tabs li img').length > 0)) {
   $('#quicktabs-my_tabs .quicktabs-tabs li.first').prepend("<img src='sites/all/themes/mytheme/images/my_img1.jpg' alt='desc'>");
   $('#quicktabs-my_tabs .quicktabs-tabs li.first').next().prepend("<img src='sites/all/themes/mytheme/images/my_img2.jpg' alt='desc'>");
   $('#quicktabs-my_tabs .quicktabs-tabs li.last').prepend("<img src='sites/all/themes/mytheme/images/my_img3.jpg' alt='desc'>");
   $('#quicktabs-my_tabs .quicktabs-tabs li a').append('<span></span>');
 }

```

Note that this example works for 3 tabs - it should be modified for your setup.

In order to make the whole quicktab a clickable link, add appropriate css to the `span` inside the `a` element, as described in this post: Make a div into a link

---
Tags: 7, theming, blocks
---


# Question
Title: Is there a way to limit how much storage users have to store their content?
I have a video sharing site where members can upload and embed videos.

When members upload videos, is there a way to limit how much storage they have to store their content? Is there an existing module or one that can be modified in order to achieve this functionality?

It uses FFMPEG to convert the videos in the format that is required and I believe it is using the video module. The storage API sounds like it has promise.

# Answer
With a support request and a little bit of work, Storage API could probably do this for you. In Storage API terms, I believe what you would do is create a "container" per user, and then use the sub-module "audit" to check how much space is being used. This number in turn could be used by the field widget you are using to limit uploads.
> 2 votes

# Answer
IMCE (http://drupal.org/project/imce) supports user storage limits really well. Not sure how that would tie into your video stuff... are users uploading raw videos that are then encoded or are they all ready to use as soon as they're uploaded?
> 1 votes

---
Tags: entities, files, nodes
---


# Question
Title: Create page with different content types
This should be something simple but I didn't figure out how to do it. Let's say I have three different content types: Client information, client projects and client updates.

I would like to have a "New client" node that will automatically create the three above content types.

Is that possible?

# Answer
Yes, you can use Node Reference field on the "Client" content type. So you can reference from this node to another node like the Client Information which belongs to this Client.

To show all information at once, you can set the Node Reference field on "Manage Display" to render the full node.
> 1 votes

---
Tags: entities, nodes
---


title: D7: Batch resave menu items

text:
# Question
Title: D7: Batch resave menu items
Is there a way to resave all items in a particular menu batch-style?

I'm trying to avoid saving each menu item manually, there are so many of them...

# Answer
There isn't a menu-specific function (that I know of) but you can use the aptly named `menu_rebuild()` function to rebuild the entire menu cache in one go.
> 0 votes

---
Tags: routes, batch-operations
---


# Question
Title: Re-render current form in submit-hook under certain conditions
I have a form:

```
function _scratch_tests_for_users() {
  $current_user_number = current_user_number_from_session();
  $form = drupal_get_form("_scratch_forms_test_for_user", $current_user_number);
  return drupal_render($form);
}

```

With the form callback:

```
function _scratch_forms_test_for_user($form, &$form_values, $current_user_number) {
  $form["user"] = array(
    "#type" => "value",
    "#value" => $current_user_number,
  );
  $form["submit"] = array(
    "#type" => "markup",
    "#markup" => "Play number {$current_user_number}",
  );
  return $form;
}

```

And a submit callback:

```
function _scratch_forms_test_for_user_submit($form, &$form_values) {
  if ($form_values["values"]["user"]) > 3) {
    _store_some_stuff();
    return "ready";
  }
  else {
    //...re-render the form.
  }
}

```

In above example code, I would want to render that form three times, the fourth time, values should be stored.

Note that my actual code is a lot more complex and has more complex criteria then simply "the first three times"; just to avoid answers like "just copy-paste the form three times" :).

# Answer
> 0 votes
The problem is that forcing rerendering on that level is not possible. Logic for rendering, or re-rendering needs to be at the level where the "`drupal_get_form`" is called.

# Answer
> 1 votes
drupal\_rebuild\_form() constructs a new $form from the information in $form\_state.

I think you can also set $form\_state\['rebuild'\] = TRUE; in a validation or submit hook as well to trigger the form rebuild.

---
Tags: 7, forms
---


# Question
Title: Send data from a Drupal site to a web service
Is there an existing module that sends data from any form from my Drupal site to a web service?

UPDATING my PROGRESS:

Ok, I decided to continue my project using cURL. I created my form that contains 2 fields: "Name" and "Phone" and a submit button. (All in my own module)

Then I show my code that I just did. However, when I see the web service. The shipping data, not shown. I did a debug and uh I realized that when running: "curl\_exec ($ch)" returns me FALSE.

```
function mymodule_form_submit($form, &$form_state){
    $name = $form_state['values']['name'];
    $phone = $form_state['values']['phone'];

    $att = array(
        'name' => $name,
        'phone' => $phone
    );

    $attendee = http_build_query($att, '', '&');

    $url = 'http://[IP]/event/management/attendee';

    $headers = array('Content-Type: application/x-www-form-urlencoded');

    $userpasswd = 'user:pass';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($ch);
    curl_close($ch);
}

```

The params,in the web service, are: attendee\['name'\], attendee\['phone'\]. What is my error?

UPDATE 2: NOW with this code, the variable $result return me a bool(TRUE). That tell me that the data was pass to the webservice. But, when I see the web service, I see no records with the data that I supposedly sent.

# Answer
Well, it probably depends on the type of web service you want to send data to, but there is this module, REST API Query, for REST web services (http://drupal.org/project/rest\_api\_query).

This week we needed to send an issue report form data from a Drupal site to a Redmine issue tracker, using the Redmine web API. We played around with the above module, but finally decided to do it in plain PHP, using CURL.

Here's the code we are using (inside the custom Drupal module we made), so you can get a general idea. You can easily adapt to your specific needs.

```
$url = {The API url here};
$userpasswd = {api-user}:{api-pass};
$xml = {XML payload};

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);

```

UPDATE: There is a drupal core function that performs the same task, drupal\_http\_request. I guess it would be better to use that one, doing it the drupal way and all :-) I have not yet tried it out though. http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_http\_request
> 6 votes

# Answer
I think your best bet would be to create a mini module yourself that will hook on the form submit event and gather all the data from your form and send them over to the other side. I have done something similar by getting some data out of the db, encoding them onto a url and posting it to the remote server.

Actually consider storing the info before sending it over, as services and connections are not always available and you might need to retry in a few minutes or the next cron.

```
function mymodule_form_alter(&$form, $form_state, $form_id) {
   if (isset($form['#node']) && $form['#node']->type .'_node_form' == $form_id) {
        $form['buttons']['submit']['#submit'][] = 'my_custom_function';
   }
}

```

Then you create a custom function:

```
function mymodule_custom_function(){
    drupal_http_request(urlencode('http://www.service.com/la.php?id=15&code=mpla'));
    //if that fails add the failed data on the DB to retry later.
}

function mymodule_cron(){
     //retry failed attempts
}

```

Or something like that.
> 2 votes

# Answer
Check out the Services module. You might have to write a bit of a plug-in to get it from your form (Webform?) but Services provides the framework.

**SERVICES:**

> A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.
> 1 votes

---
Tags: services
---


# Question
Title: Is there a module or functionality to export/import roles and permissions?
I have been searching for a module or functionality to export/import roles and permission from one installation to another, but could not find it. Is there such a functionality or module for Drupal 7?

# Answer
> 3 votes
Have a look at the Features module.

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


title: Drupal 7.12 : views filters

text:
# Question
Title: Drupal 7.12 : views filters
i have a mark as checkbox field with two options - published and unpublished. i want articles marked as 'published' to appear on a view page and those marked as 'unpublished' to appear after the published items as an attachment to the view. the unpublished articles will only be visible to the author. How can i go about achieving this? I have tried using the filter but to no avail. i chose the field name and selected 'is one of' then selected publish, but this did not work. Any suggestions?

# Answer
Drupal contains a published/unpublished feature by default, which can be filtered in views using the `Content: Published` filter.

If you want to use a custom field though it should be as simple as you described. Assuming the published field is a taxonomy reference, you should be able to apply a filter to that field and select 'is one of' and the appropriate term (published). I tried this and it works.

As for the second part, you can clone the view and change the field filter to unpublished. Then add a `Content: Author` relationship and a `User: Current (Yes)` filter to filter it to content that the current user has authored (you might also want to put some access restrictions on this view). This view can then be added to the 'Footer' section of the first view.
> 3 votes

---
Tags: views
---


title: Granting restricted permission roles

text:
# Question
Title: Granting restricted permission roles
As well as the three standard roles for a D7 site, I have created a role for a lesser admin / content creator. This role is essentially an administrator role with some of the juicy bits taken away.

I would like that users assigned this role can manage other users, but I need to restrict it so that they cannot assign or remove the administrator role, or edit an administrator's profile and account. I can't see a way to do that on the standard installation, is there a module that could help me?

**Edit:** I have looked into the userprotect module. While it does prevent a lesser admin from editing an administrator, it does not prevent them from granting the administrator role on themselves.

# Answer
As you mentioned, User protect should work well. Combine this with Role Delegation to restrict what roles they can assign.

Might also be worth keeping an eye on the Administer Users by Role module, although there is no D7 port yet (in progress here).

Let me know how it turns out as I'm going to be solving this issue on the site I'm working on soon.
> 3 votes

---
Tags: 7, users
---


# Question
Title: "An illegal choice has been detected" error on user creation
When creating a new user, I got this error:

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

I'm sure I entered all the required information. This is when I am logged-in as administrator.
I'm using drupal 7.10.

\[Edit\]
I have a few lines of code in my `hook_form_alter()` which alters the user registration form :

```
if($form_id == 'user_register_form'){
    $form['profile_main']['#weight'] = 10;
    # Password and Confirm password
    $form['account']['pass']['#weight'] = -9; # move above E-mail address
    # User role
    $form['autoassignrole_user']['#weight'] = 2;
    $form['autoassignrole_user']['user_roles']['#attributes'] = array('onclick' => "Drupal.mymodule.toggleProfile(this)");
    if(in_array('administrator', $user->roles)){ # if master administrator, hide it
        $form['autoassignrole_user']['#required'] = FALSE;
        $form['autoassignrole_user']['#type'] = 'hidden';
    }
}
elseif($form_id == 'user_profile_form'){
    if(!in_array('administrator', $user->roles)){ # if not administrator
        $elems[] = 'timezone';
        $form['timezone']['#required'] = FALSE;
        $form['timezone']['#type'] = 'hidden';
    }
}

```

# Answer
I think the error is most likely generated when I changed radio selection to hidden type. `$form['autoassignrole_user']['#type'] = 'hidden';`
I often used the type **hidden** when I want to hide a particular field on the form. It seems it cannot be done for check boxes and radios.

The main problem is that I had to use Auto Assign Role module to allow the end user the option of choosing their own role ( with radios ) on user registration. This duplicates user role selection for administrator. Drupal core provides a role selection with check boxes, whereas Auto Assign Role adds role selection with radios. Thus, I tried to hide Auto Assign Role for administrator, then I got the error.

Actually, as I don't want check boxes for role selection, I changed my mind to hide Drupal core role selection and raised Auto Assign Role. Here is my steps :

1. Hide the check boxes by wrapping a DIV as I cannot use `['#type'] = 'hidden'` which would generate the error.
2. Although they are hidden on the form visually, leaving them unchecked would generate the same error. Why Drupal don't make them required instead of issuing this security error ? Authenticated user role is checked by default, but it would not be in the POST array as it is default-disabled.
3. Thus, I created a javacript function to check the associated user role upon a role selection of Auto Assign Role.

This put the error away. Here is some code snippets of `hook_form_alter()` :

```
    # Roles ( Drupal core user roles check boxes )
    $form['account']['roles']['#prefix'] = '<div style="display:none">';
    $form['account']['roles']['#suffix'] = '</div>';
    # Auto Assign Role ( user roles radios )
    $form['autoassignrole_user']['#weight'] = 2;
    $form['autoassignrole_user']['user_roles']['#attributes'] = array('onclick' => "Drupal.mymodule.toggleProfile(this)");

```

Here is javascript code snippet :

```
        $('#edit-roles input[type=checkbox]').each( function(i, elem){
            if(elem.disabled == false){
                $(elem).removeAttr('checked');
            }
        });
        $('#edit-roles-'+$(obj).val()).attr('checked', 'checked');

```
> 1 votes

# Answer
When you submit a form Drupal checks the integrity of it, i.e. it checks that the submitted values fall in line with the list of possible values for each element in the original form definition.

So, if you've got a select/checkboxes/radio buttons element on the form and you change the possible options for this using javascript on the client side, the new options won't match up with the ones Drupal knew about when the form was built. In this instance Drupal will rightly inform the user "An illegal choice has been detected.", because it has. This is an excellent security feature and is the default behaviour. It can't be switched off without some serious effort.

I would take a guess in your case that this problem is happening in the JS you're attaching to the `autoassignrole_user` element.

If you want to change a form's structure using JS you need to do it the 'Drupal' way, using AJAX to update the form on the server-side:

```
function MYMODULE_my_form($form, &$form_state) {
  // If the checkbox is ticked, load one set of options
  if (isset($form_state['values']['check']) && $form_state['values']['check']) {
    $options = new_options();
  }
  else {
    // Otherwise load the default options
    $options = default_options();
  }

  $form['check'] = array(
    '#type' => 'checkbox',
    '#title' => 'Click to change options',
    '#default_value' => isset($form_state['values']['check']) ? $form_state['values']['check'] : 1,
    '#ajax' => array(
      'wrapper' => 'options-wrapper',
      'callback' => 'my_form_ajax_callback'
    )
  );

  $form['options'] = array(
    '#type' => 'select',
    '#title' => 'Options',
    '#options' => $options,
    '#prefix' => '<div id="options-wrapper">',
    '#suffix' => '</div>'
  );
}

function my_form_ajax_callback(&$form, &$form_state) {
  // Return the options element which will have been changed in the re-build of the form
  return $form['options'];
}

```

The above is a very simple AJAX example that uses a checkbox change event to change the values in a select list on the form. Doing it this way will keep the internal structure of the form intact and you will no longer get the error message you're currently getting.

Have a look at the Form API documentation and AJAX framework documentation for a lot more information on this.
> 2 votes

# Answer
Drupal checks the option values before submitting values to the database. Its check it with the option values which was there when form was created. Its a security measure od drupal.
> 1 votes

---
Tags: users
---


title: Scaling images on upload

text:
# Question
Title: Scaling images on upload
I'm using managed\_file in a form to uplaod multiple images (D7).

```
$form['img_upload1'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg')),
'#default_value' => variable_get('img_upload1', ''),
'#upload_location' => 'public://uploads_users/mydir/'.$userId,
);

```

Allowed file-extension are checked when the user chooses an image and in the form-validate-function the filesize is checked. The images should have a max hight of 730px or max width of 970px.

I can find the dimesions of the uploaded picture bud don't know how to resize it. Is there a way to add a scaling-function (an image-style?) to the managed\_file-formfield or to the validation-function to resize the image before ore after the upload?

Thanks

UPDATE Thank you for your hints. The idea behind all was to have the original files available in a defined dimensions for an other purpose. Bud I see the benefits of using the "Drupal-way".

# Answer
> 1 votes
There's no need to scale your images when you upload them, the usual method is to serve a cached version of the scaled image when it's displayed. This is usually accomplished by setting up an image style in the Drupal admin UI that has the effects you need, and then using `theme_image_style()` to output that image:

```
$file = file_load($fid);
$options = array(
  'style_name' => 'image-style-machine-name',
  'alt' => 'Alternative Text',
  'path' => $file->uri
);

$image_output = theme('image_style', $options);

```

Doing it this way gives the added benefit of your having the original uploaded file available at any time (for example to link through to as a full-sized version of an image, or in a lightbox, etc.)

---
Tags: media, files
---


# Question
Title: Generate slideshow of images present in a folder
I want a module which gives user just a screen to upload images to a folder and it will generate a slideshow of the images and place it on a certain block in my website. Is there any module to do this or any custom code to do this?

# Answer
> 2 votes
You could try something along the lines of the following:

```
function mymodule_get_folder_images() {
$directory = "path/to/your/images";
//Check this...my regex is crap
$mask = "(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)";
$options = array(
'recursive' => TRUE
);

//This should return an array of images
$images = file_scan_directory($directory, $mask, $options);

//Loop through the array once to get an array of paths.
foreach ($images as $k => $v) {
$imagearray[] = $v->uri;
}

//This should probably be passed to a theme function to be more Drupally.

$output = '<div id="slideshow">';

foreach ($imagearray as $k => $imagepath) {
if ($k == '0') {
$output .= '<img class="first" src=". $imagepath." />';
}
else {
$output .= '<img src=". $imagepath." />';
}

$output .= '</div>';

return $output;
}

```

This will give you an unordered list of images that you can use to create your slideshow. Then just hook the jQuery Cycle plugin (or any other slideshow plugin) into your site and you're off. I can't really help with the slideshow integration as it's going to be pretty custom for your needs, but it becomes much easier when you already have the image urls formatted nicely. Obviously, if you need a list instead then you just re-format the last `foreach` loop.

---
Tags: 7, javascript
---


# Question
Title: Drupal's version of Wordpress' wp_insert_post()?
I just started playing with Drupal and I'd like the user to be able to add a custom node(or content) outside the admin by providing a form and then add that to Drupal's database once submitted. How do I do this programmatically and securely? Wordpress has a wp\_insert\_post() function for this functionality, what's the Drupal version?

# Answer
Are you sure you want to do it programmatically? You can just create the Content Type and use Permissions to control which user's roles can add/edit/delete that type of content.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to I get an extra field for a user profile when using EntityFieldQuery()
I'm currently using something like this:

```
$users = new EntityFieldQuery();
        $users->entityCondition('entity_type', 'user')
        ->propertyCondition('status', 1);
$result = $users->execute();

```

Which is great, but it returns a list of 1000 ids. How do I get an extra field with this, without loading 100 user profiles (which would be quite time consuming). So for example I need to get the profile field - `field_profile_company`

I tried user `user_load_multiple($result['user']);`

Thanks.

# Answer
> 1 votes
The result that comes from `EntityFieldQuery::execute` contains an array of entity types, and within each of those is an array of the entities found in the query.

The caveat is that the entity ID is actually the *array key* of said array, so to use `user_load_multiple()` you would use syntax like this:

```
$users = user_load_multiple(array_keys($result['user']));

```

---
Tags: users, entities
---


# Question
Title: Taxonomy term AND (,) operator does not work
In contextual filters, with

* validator = taxonomy term
* Filter value type = term ids separated by , or +
* allow multiple values = true

Giving argument **"1+2"** works as espected: *OR* operator

Giving argument **"1,2"** works as **"1+2"**: *OR* operator instead of expected *AND* operator

In both cases, conditions uses operator "IN":
**WHERE (( (field\_data\_field\_tags.field\_tags\_tid IN('1', '2') ) )AND(( (node.status = '1') AND (node.type IN ('flickr\_photo')) )))**

This is the contextual filter part of my view:

```
/* Contextual filter: Content: Tags (field_tags) */
$handler->display->display_options['arguments']['field_tags_tid']['id'] = 'field_tags_tid';
$handler->display->display_options['arguments']['field_tags_tid']['table'] = 'field_data_field_tags';
$handler->display->display_options['arguments']['field_tags_tid']['field'] = 'field_tags_tid';
$handler->display->display_options['arguments']['field_tags_tid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['field_tags_tid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['field_tags_tid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['field_tags_tid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_tags_tid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_tags_tid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_tags_tid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['field_tags_tid']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['vocabularies'] = array(
  'tags' => 'tags',
);
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['type'] = 'tids';
$handler->display->display_options['arguments']['field_tags_tid']['validate_options']['transform'] = 0;
$handler->display->display_options['arguments']['field_tags_tid']['validate']['fail'] = 'empty';
$handler->display->display_options['arguments']['field_tags_tid']['break_phrase'] = 1;
$handler->display->display_options['arguments']['field_tags_tid']['not'] = 0;

```

How can I set a *AND* filter? I want to display contents with all values of *tags*.

# Answer
> 2 votes
I am not the best with deciphering exported settings, but I think you should remove that Contextual Filter and use "Content: Has taxonomy term ID" instead. Make sure you tick "Allow multiple values" under the More section. That will result in a chain of `AND` clauses in the `WHERE` for the view (well, it does in one that I just looked at).

# Answer
> 0 votes
Set them as separate arguments, and it will filter to only things where both match.

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


# Question
Title: Help adding multiple blogs / content areas on a page
Hi how do I set 4 editable content/blogs block/nodes on a page... i'm trying to do this format https://i.stack.imgur.com/xFoCY.jpg

main Box 1: width 556 x length 630

right Box 1 : width 210 x length 275

right Box 2 : width 210 x length 185

right Box 3 : width 210 x length 150

also how can I edit the style/css for the blocks/nodes on this page?

# Answer
> 1 votes
You define new block regions in your theme, and structure your page.tpl.php to print the regions in the desired structure. You should look through the theming tutorials

If that is the layout for a single page only, you might want to look into Panels, though be warned that there is a bit of a learning curve.

For styles of blocks, you can override the default CSS in your theme. Your theme's CSS files will load after the defaults, so it will take precedence.

---
Tags: nodes, blocks, theming
---