# Question
Title: What could cause the Features create page to time out?
The site I'm working on is timing out when I try to open the admin/structure/features/create page. I'm not experiencing the problem elsewhere in the admin, just there. What does this page do differently that might take more time?

On a related note, does anyone have any tips for determining what Drupal component/module is causing a slowdown aside from "turn everything off and see what happens"?

# Answer
> 4 votes
The features UI can be notoriously slow for large Drupal sites. We recently experienced a ~50 second delay in loading the aforementioned page (create a new feature). The reason why (after debugging it all) was it was loading every single menu item on the site (\>3000 of them) and trying to render a checkbox for every single one.

I posted a simple workaround on drupal.org https://drupal.org/node/1153028 \- it looks like my patch will never get accepted in features, but at least it got the module maintainers looking at the performance issue.

On a related note, you do not need to use the GUI in order to create a feature. With large Drupal sites I would recommend using drush only as it has the advantage of being much faster. Please see https://drupal.org/node/960926 for more details.

# Answer
> 1 votes
You can use the devel and you can use xdebug with drupal here is a very good tutorial

I also suggest extending the php `max_execution_time` and `memory_limit` in php.ini, Create the Feature, Then lowering them down again if you want.

# Answer
> 0 votes
EDIT: sorry, just noticed this had already been suggested.

It might be worth checking your server's error log for clues too. I was hitting the PHP memory limit and getting a whitescreen; upping the memory\_limit in my php.ini sorted this issue.

---
Tags: 7, performance, features
---


# Question
Title: how to achieve a sliding effect to show the rest of elements in a grid, with views
I have a view set to grid, displaying 5 items per column. I set it to display 5 items at a time too, but I have 10 items total. What i want to achieve is, when I click on page 2, instead of having it load the rest of thumbs, for them to slide into the position of the first 5 items displayed. It would be something like SlideShow effect, scroll to the left, but instead of displaying a single frame, displaying 5 at a time.

Im using drupal 6x, views, (cck of course), and have slideshow installed but I couldn't manage to figure it our on my own. I appreciate any prompt response.

# Answer
Here is an example of jquery slide show.

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Animating an Element</title>
    <script type="text/javascript" src="../jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#right").click(function() {
                $("#theDiv").animate({ width: "500px" }, 1000);
            });
            $("#text").click(function() {
                $("#theDiv").animate({ fontSize: "24pt" }, 1000);
            });
            $("#toggle").click(function() {
                $("#theDiv").animate({ left: "500" }, 1000, "swing");
            });
        });
    </script>
    <style type="text/css">
        div#theDiv {
            position:relative;
            width: 250px;
            height: 180px;
            margin: 10px;
            padding: 20px;
            background: cyan;
            border: 2px solid black;
            cursor: pointer;
        }
        p, span {
            font-size: 16pt;
        }
        button {
            margin: 5px;
        }
    </style>
</head>
<body>
    <p>
        Animating an Element</p>
    <div id="theDiv">Animate Me</div>
    <button id="right">Grow Right</button>
    <button id="text">Big Text</button>
    <button id="toggle">Move Div</button>
</body>
</html>

```
> -1 votes

---
Tags: views, paging, javascript
---


# Question
Title: How can I detect if node is the last one from within node.tpl.php?
There are a number of variables for the node.tpl.php template, like $id that contains the current nodes index number, but how can I figure out if the current node is the last index or how many nodes there are in the current listing?

(I'm using Drupal 7)

# Answer
> 4 votes
In general, it is not a good idea for Drupal objects to not "know" how they are being used on a page. When you make them "self-aware" you introduce artificial dependencies that can make changes down the road harder to make, or inadvertently introduce bugs.

In you case, I would handle this in the views templates. Out of the box, the last row should have a `views-row-last` class on it.

Otherwise, you need to implement a `template_preprocess_node` in your theme. The view object will be available as `$variables['view']`. You would need to add logic to check page, view name, etc, to make sure you are doing things in the right place. Off the top of my head, I forget which properties you need to check; do a `kpr($variables['view'])` and poke around.

---
Tags: theming
---


title: How to change a datatype for a field

text:
# Question
Title: How to change a datatype for a field
How do I change a data type for a field in a table?

To change the field name we can use db\_change\_field().

# Answer
> 2 votes
The same function can be used to change the type of the field.

Suppose you are the following field defined for the "foo" schema.

```
$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

```

You can change its type to "serial" using the following code:

```
db_drop_primary_key($ret, 'foo');
db_change_field($ret, 'foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));

```

The call to `db_drop_primary_key()` is necessary because the field is a primary key; for compatibility with any database engine, it is suggested to first remove the primary keys, the indexes, and the unique keys before to edit them.

If in the call to `db_change_field()`, the third and the fourth parameters contain the same value, then you are not changing the field name.

The documentation for the function contains the following text:

> Change a field definition.
>
> IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

To notice that the first line doesn't say "change a field name"; it says "change a field definition," and the field name is included in the field definition.

# Answer
> 1 votes
For DRUPAL 7 There are 4 places that you have to change when the above answer does not work or you really want to do this by hand. To change my INT file into an VARCHAR 64 I did like this:

1. Change the database table for the field. I created a field with the same name with txt at the end (the value field). Since text fields have a format I created also a format field. I copied the content from one value field to the new one, and deleted the old one. Then I renamed the txt one back to only value.
2. Change the revision table for the field as above
3. Change the field\_config table, I checked other fields that were txt and copied most of it's contents. The tricky part is the blob field of course
4. Change the field\_instance table, here you have to check the blob field and change the widget part

For fields that where created by you with the UI this is sufficient. For module fields you have to check the database definitions and update them. This is tricky stuff, so be sure to make the changes in a dev environment, copy the slqs and then do a fast change in your actual site.

Hope this helps someone.

---
Tags: 6
---


# Question
Title: Drush dl with dependencies on a multisite environment
When downloading a project using `drush dl <project>` in a site specific folder on a multisite environment, the module is being downloaded to /modules. However, the dependencies are being downloaded to /sites/all/modules. Is there a way to force Drush to download the dependencies to the site specific module folder using Drush 5?

# Answer
> 2 votes
Nope; Drush doesn't pass --destination to the command used to download the dependencies. The code is in drush\_pm\_enable\_validate; patches welcome.

The issue is at http://drupal.org/node/1632578

---
Tags: 7, drush, multi-sites
---


title: drupal HTTP POST data

text:
# Question
Title: drupal HTTP POST data
How do i send HTTP POST/GET data to drupal?

for example: I've got a html form:

```
<form action="mydrupalcite.com" method="get">
    <input type="text" name="title" />
</form>

```

how do i get the `title` 's data into drupal's answers module?(or any module?)

I'm looking for the drupal way of doing this(i'm relatively new to Drupal and how it really works)

Does it have anything to do with Services module?

# Answer
> 6 votes
Drupal's form API has CSRF protection built in, so submitting a form from an external domain won't work. You could either look at disabling the CSRF (very bad idea), or as you suggest, use the Services module.

There's no one-to-one mapping between the services module and forms on the site, rather modules implement resources for certain tasks to be consumed from an external client. You get node, user, taxonomy term, and probably others by default. So you can (for example) add a new node/user/term, but you do so by sending xml/json/etc requests to the server after having authenticated, not by submitting a form as such.

Getting data works in much the same way. You can either use Services to do that, or if you can manage/don't need your own authentication see indrock's answer for a good method.

Services is very extensible, so even if the answers module doesn't implement resources, it's a pretty easy job to add your own that wrap around API functions from the answers (or any other) module.

The documentation for services would probably be a good place to start.

# Answer
> 6 votes
You'll first need to create a page(URL) in Drupal to get this parameters. You can do this by implementing `hook_menu()`, in your custom module. Refer this to create your custom module.

```
function MYMODULE_menu() {
  $items['get_details'] = array (
    'title' => '',
    'page callback' => 'MYMODULE_access_variables',
    'page arguments' => array(1),
    'access callback' => TRUE,  // this will be accessible to everyone
  );
  return $items;
}

function MYMODULE_access_variables() {
 // Here you get access to the POSTED variables using $_RESPONSE php superglobal
  echo "<pre>";
  print_r ($_RESPONSE['title']);  // will get you the value of the HTML input type having name='title'
  echo "</pre>"
}

```

This will create a page at your site at url http://mydrupalsite.com/get\_details

Now, from your HTML do the calling like

```
<form action="mydrupalcite.com/get_details" method="post">
    <input type="text" name="title" /> <!-- Note that the value of the attribute 'name' will be used the capture the value which is posted -->
</form>

```

**NOTE:** As per @clive's answer, I'd suggest you use it only for development/educational purpose. This might have security implications.

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


title: Add an Administrator?

text:
# Question
Title: Add an Administrator?
I've added a new Drupal user, so how do I make them an administrator of the site?

I can't seem to find a setting to do this? User roles are Authenticated and Anonymous.

But the default login username definitely has some kind of administrator permission. How do I grant this same privilege to a new user?

In *Config \> People* there is setting *Administrator role* which is a select menu, but it only has the disabled option :S

# Answer
> 5 votes
The 'super user' (user 1) has privileges that you won't be able to completely emulate for other users. There are hard-coded bypasses in functions like `user_access()` that allow that user to do pretty much anything they want.

Permissions are granular in Drupal, so the idea is you give a certain role a certain set of permissions based on what they should be allowed to do.

To get as near as possible to another role being able to do everything the super user can, you just need to go to admin/people/permissions and tick all of the permission boxes for the administrator role. I'd advise checking each permission (if only this once) as you do this, to make sure you're definitely giving that role the access you expect.

When you then assign the administrator role to other users, they'll essentially be able to do anything on the site that you've allowed them to do through the permissions page.

---
Tags: 7, users
---


title: hook_user_insert() vs hook_user()

text:
# Question
Title: hook_user_insert() vs hook_user()
can someone please explain the difference between

hook\_user\_insert() and

hook\_user() with $op='insert'

i mean is hook\_user with $op='$edit' is invoked after a user create an account??

cos i am trying to get some custom field values when a user create a new account. i used this code for testing:

```
function myModule_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'insert' ){
    dpm($edit)
  }
}

```

and it don't return nothing after creating a new user account.

# Answer
The simple answer is that `hook_user` is for Drupal 6 and `hook_user_insert` is for Drupal 7.

Most (all?) of the API functions in Drupal 6 and earlier that accepted an `$op` parameter got split out into individual functions in Drupal 7. This happened with `hook_block`, `hook_nodeapi`, and some others.

For Drupal 7, the full set of user hooks is described at user.api.php.
> 5 votes

---
Tags: hooks, users
---


# Question
Title: Hover a trimmed views field for full text?
I have a text field in a views table which I use the Rewrite results -\> Trim this field to a maximum length with ellipsis option on. Is it possible and how, so that when I hover this trimmed text I get the full version as a popup or that the view updates to show the full text?

# Answer
Hate to answer my own bounty question but this works exactly as I want it.

I found a great way to do this with beautytips module. My field is an address (field\_address). Add field\_address to views and do rewrite-\>trim with ellipsis BUT exclude from display. Add the same field again this time rewriting the output of the field with:

```
<div class="beautytips" title="[field_address_1]">[field_address]</div>

```

(I have "Add beautytips js to every page" enabled in the beautytips settings)

+1 zhilevan's answer which is also a very good solution but is sadly missing the roll-back/rollup/close option which would mean very long tables with a few read mores open!
> 10 votes

# Answer
I suggest in `Rewrite results` put your result in a html element like `<div>` or `<span>` ,specify it with a `id` or `class` . and after it use Jquery Readmore Plugin .

This samples maybe useful for using of jquery readmore plugin
> 7 votes

# Answer
I'd say to do that with JS. It's much easier and will still do the job.

Steps:

1. Output the full field in the view
2. Trim it on page load; clone the original full description in a separate container and give it a special class or ID
3. Add an ellipsis at the end and attach a function on hover/click
4. Once user clicks/hovers, show the cloned description in a popup (if it's more text and would break the layout)

Depending on your needs, instead of this you can wrap the excess characters in a span and hide them. Once you click ellipsis you can just apply another class to the span and show it.
> 1 votes

# Answer
```
(function($) {
    Drupal.behaviors.expalain_popup = {
      attach:function() {
        jQuery('a.open_popup_link').click(function(){
          var node_id = jQuery(this).attr('data-value');
          window.open('/open_popup/node/'+node_id, 'Explain '+node_id,'width=450,height=600,resizable=1,scrollbars=1,toolbar=0,location=0');
        });
    }
  };
}(jQuery));

```

This code may help you to achieve your goal.
> 1 votes

---
Tags: views, entities, theming
---


# Question
Title: Listing Inventory items without being purchasable items
The company website requires a list of large inventory items - engines, pumps, compressors, etc for the oil & gas industry. I was looking into UberCart but unfortunately it does not need to be an E-Commerce platform. What is the most efficient way of displaying inventory items in Drupal 7?

# Answer
You can probably do this with just Drupal core and the Views module if you don't need any e-commerce functionality. It would probably go something like this on a basic level:

1. Add a new vocabulary called 'Categories' and add your terms to it (engines, pumps, etc.).
2. Add a new content type called 'Inventory Item'.
3. Add a term reference field to the 'Inventory Item' content type linking to the 'Categories' vocabulary you just created.
4. Add whatever other custom fields you need to the content type (price, stock, etc).
5. Create a view that lists all content of the 'Inventory Item' type.
6. (optional) Create any other views that you may need to filter the content by whatever criteria is applicable.
7. Start adding content.
8. (optional) Grab the Taxonomy Menu module so you can easily create menus that break your inventory items down by category.

The order of those steps is somewhat interchangeable.

If you're not familiar with views there's good documentation out there.
> 2 votes

---
Tags: ubercart
---


# Question
Title: How to print only src path of taxonomy image
I'm using Taxonomy image 1.6 on D6.19, I'm working on a legacy stack that I can't upgrade, nor do I have direct access to the taxonomy image module. Nice right?

Right now I'm using the taxonomy image in two ways, one is being printed out in the standard functionality of the mod and thats fine, the second is as a popup overlay created by jquery.

The popup is holding it's info in the "data-content" portion of a div, and required that any tag inside using only single quotes. Double quotes end the script early. I need to call the Src of the image so I can dynamically print it into an image tag. or I need to know how to hook into it so I can rewrite it for this particular use.

Any guidance would be welcome. Thanks Stephanie

# Answer
A quick look at a download of the current version of the module (1.7) shows that there is a function based on the $tid that returns a lot of formatted and unformatted information:

```
/**
 * Function to get an image object with more useful data for custom formatting.
 * @param
 *   $tid - the term tid.
 * @return
 *   image object.
 */
function taxonomy_image_get_object($tid, $recursive = NULL)

```

with one of the things being returned being the url to the image. Assuming this function exists in your version, would this work for your use case? If so, there is even a helper function available as well:

```
/**
 * Function to get a url for an image, for use in css, html or other client-side code.
 * @param
 *   $tid - the term id
 * @return
 *   The url string.
 */
function taxonomy_image_get_url($tid) {
  $image = taxonomy_image_get_object($tid);
  return $image->url;
}

```
> 0 votes

---
Tags: 6, hooks, taxonomy-terms
---


title: Subscription OG Group

text:
# Question
Title: Subscription OG Group
I want that user can subscribe to content add in several OG GROUP.

How can achieve that ?

Cordially

# Answer
Yes, By default `og_group_ref` field (organic group field machine name by default add to your content types) accept multi value, if for you it's **Number of values** set `1` value, go to you `content type manage fields` and change it to `unlimited` value
> 0 votes

---
Tags: organic-groups, notifications
---


# Question
Title: How can i add multiple instances of newsletter subscriptions?
I want to display newsletter subscribe in different pages, in different ways. Hence once I have set newsletter : subscribe to home page, it does not apply to other page by default.

How can I can assign it to different pages in different positions?

# Answer
Each block can be configured in different ways. You can by default give different paths to show or not show your block. Go to /admin/structure/blocks and click on "configure".

If you need more advanced settings, then have a look at the Context module. This allows you to define all kind of rules and conditions to show a block. Very powerfull.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: A time field instead of end date in drupal 7 date field
Is it possible to have a time field (for example in minute only) instead of end date of date field in drupal 7?

so that the user select start date and time and due time (in minute) and end datetime will be start datetime + due time?

# Answer
> 3 votes
The Date single day module for Drupal 6 worked great for this use case. There isn't a 7.x version yet, but there is an issue to port it.

---
Tags: 7, datetime
---


title: No result from an SQL query

text:
# Question
Title: No result from an SQL query
I have a view with a custom PHP field containing the following code.

```
$storeArray = array();
$result = db_query("SELECT nid FROM node WHERE type ='emp'");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row[nid];
}

if ($storeArray) {
  echo 'not empty';
}

```

The query doesn't return anything. Why?

# Answer
You're mixing a couple of different things there :)

The resource returned from `db_query()` can be iterated over directly, there's no need for an intermediary function. The resource isn't the same as one that would be returned from `mysql_query()`, as the Drupal database layer wraps around PDO.

This is the standard way to iterate over `db_query()` results:

```
$result = db_query("SELECT nid FROM node WHERE type ='emp'");

$storeArray = array();
foreach ($result as $row) { // An object is returned by default
  $storeArray[] = $row->nid;
}

```

However, the db layer also has a handy shortcut method called `fetchCol()` that will fetch the results of the query's first column into an array. So you can simplify your code to a single line:

```
$storeArray = db_query("SELECT nid FROM node WHERE type ='emp'")->fetchCol();

```
> 4 votes

---
Tags: 7, database
---


# Question
Title: cck fieldgroup tabs appear but all fields in one tab
I am using cck fieldgroup tabs to group various fieldsets under different tabs and I want them to appear in tabs to anonymous user.

Somehow the tabs are not working. The tabs are all there sitting above but all the fields within each fieldset are all shown on the same page and the tab links work as if they are internal links for the same page. You click on any link and you are moved down to the fields in that fieldset on the same page.

I looked into the generated page in firebug and it came out that the classes responsible for generation and grouping of tabs are all wrong in the div and ul tags. when I changed them to the correct ones using firebug , they all looked fine in browser.

Now I dont know how are these classes put into div tags in the backend so that i can rectify it. Can someone help please.?

# Answer
Check the permissions to ensure the fields are available to the anonymous users.
> 0 votes

---
Tags: entities
---


title: How to redevelop a production site?

text:
# Question
Title: How to redevelop a production site?
I'm working on a local version of an outdated Drupal 6 site which can not be shut down for a minute. The goal is to update the modules and give some enhancements, like adding tags, making a better menu and dynamic blocks etc with the least possible down time for the site.

It will probably take a few weeks for me to do so. Meanwhile new content will be added to the production site as per usual.

**My question is**: When I finish developing the requested enhancements on local version, how should I integrate newly generated content to the development version before putting it online? I can not simply import the production database dump since this will undo my whole work. So obviously I need to import only certain tables. But how should I figure out which ones? What would you do in this situation?

# Answer
> 1 votes
It depends on what the enhancements you are making but the way I've done this same process before is to export the finished code improvements to a features module or other custom module from my dev site and use that to update the live site.

You mentioned a few examples:

* "adding tags" -\> you could export the improved taxonomy and then import it on the new site using a number of modules, ex. taxonomy\_xml or taxonomy\_csv
* "making a better menu" -\> the features module allows you to export your menu and import on other sites
* "dynamic blocks" -\> easiest to just code these in a custom module (probably the simplest kind of module to write) and enable on the new site

---
Tags: migrations
---


title: Print out NID of entity reference

text:
# Question
Title: Print out NID of entity reference
I have a custom field that is an entity reference, when using

> print render($content\['field\_call\_to\_action\_1'\]);

in a content type template it prints out the title *Call to Action 1*, and the Title of the content that the entity reference is linked too.

How can I just get it to print out the NID instead?

Thanks for your time!

# Answer
> 3 votes
$content is to be rendered and obeys what you have set in node(other other entity) type's Display Settings (Administer \> Structure \>Content Types).

What you should use is, $node object.

```
<pre>
<?php
print_r($node);
?>
</pre>

```

Now you will see a nicely formatted information of $node object which also has the NID you want.

You will be able to access it with this:

```
$node->field_call_to_action_1['und'][0]['target_id']

```

Quick hint:If you are trying to build a URL link from this value, have a look at url() and l() functions!

---
Tags: 7, entities
---


title: Rebuilding content access permissions

text:
# Question
Title: Rebuilding content access permissions
I have a site with 760123 nodes, and 20123 users.

When visiting any page, I get the warning, "Rebuilding content access permissions." I tried rebuilding the access permissions, but the process is very slow.
I see this post, and tried the proposed solution, but it is not working.

I'm using Drupal 6.

# Answer
> 0 votes
my problem was conflict with xml sitemap module . i disable xml sitemap module

# Answer
> 3 votes
Maybe you're hitting your server's max\_execution\_time. It's quite likely with such a big number of nodes, and this operation taking a long time is normal.

# Answer
> 2 votes
Some of the modules will give you problems. Ex : OG Access module , I disabled it and then rebuilt permissions. Disable any access related modules(like TAC,node access etc) and then rebuild again.

---
Tags: 6, users
---


# Question
Title: Setting Panels category for blocks and other pre-existing Content Types?
When one adds new content to a Panel, they are given a list of categories, each with various Content Types.

Setting the aforementioned category of a Content Type is easy if you're writing your own plugin...

```
$plugin = array(
  'title' => t('My Plugin'),
  'category' => t('YOUR CATEGORY HERE'),
);

```

But what about setting that category for Content Types created by other modules?

I ask because I've created a Menu Block and am wanting to put it in a specific category, where all my other custom CTools Panels Content Type plugins reside.

Any thoughts? I'm using D7, by the way. Thanks!

# Answer
A kinda hacky way of doing it is to hook into hook\_ctools\_block\_info() like so:

```
/**
 * Implements hook_ctools_block_info().
 *
 * @see ctools_block_content_type_content_types().
 */
function menu_block_ctools_block_info($module, $delta, &$info) {
  if ($info['title'] == 'Sub Menu Menu Block') {
      $info['icon'] = 'icon_core_block_menu.png';
      $info['category'] = t('Page Content');
  }
}

```

I just dropped this code in a separate module and I'm off to the races. The only problem is if Menu Block decides to implement its own hook\_ctools\_block\_info function (Indeed, I got the above code from a patch that does exactly that), in which case redeclaration errors will show up. I'll leave this question marked as unanswered for the moment; if anyone can think of a better way of accomplishing the above, I'd be happy to accept that answer instead.
> 1 votes

---
Tags: 7, blocks, panels, chaos-tool-suite
---


# Question
Title: Alter all Webform's form with hook_form_BASE_FORM_ID_alter
What is the base `form_id` for *Webform*'s forms to use in `hook_form_BASE_FORM_ID_alter()`?

My website will have lots of Webforms and I'm looking the proper way to alter this huge amount of forms.

# Answer
> 6 votes
the base form is **webform\_client\_form** and hook look like

> HOOK\_form\_webform\_client\_form\_alter

or if using HOOK\_form\_alter we need statement as

```
if (strstr($form_id, 'webform_client_form_')) {
  //our code for all webforms
}

```

---
Tags: 7, webforms
---


# Question
Title: Does Drupal automatically unlink() orphaned files?
Does Drupal 7 have a way to automatically remove images that are no longer linked to an entity, or do they need to be unlinked manually?

For example, how would Drupal react to the following detachment of a file from a node:

```
$nid = 7;                      //A node containing an image field.
$node = node_load($nid);       //$node->field_image is a populated Imagefield.
$node->field_image = array();  //$node->field_image is set to an empty array.
node_save($node);              //$node is saved.

```

Will the orphaned `fid` sit in the files directory indefinitely or will Drupal remove it automatically?

# Answer
The images will be automatically deleted if they were added through a regular image upload field. In that case Drupal understands that that image is related solely to that one node/entity.

In case you are using some other module for inserting the images, it depends and might not be deleted.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Drupal multisite: Same theme, different colors
I am looking for an answer to a quite specific theming question:

I have a Drupal multi-site installation. *(Well, not yet actually, but I want clarity on my question first before I procees. Just asume that I have one.)*

I have a team, called 'Theme', which has various files in the directory `/sites/all/themes/Theme`. In this folder, there are the `.tpl.php` files and a few folders like `css/` and `scripts/`.

Then, I have 2 sites, which use the same theme: Theme. These sites are located in `/sites/default` and `/sites/alternative.`

What I want to do now is providing a file, `colors.css` in each sites directory (so `/sites/default/colors.css` and `/sites/alternative/colors.css` with something like:

```
@base: blue;
@light: lightblue;
@dark: darkblue;

```

This file should be read and these 'variables' should replace the variables in the css files located in `/sites/all/themes/Theme/css` so that I simply can define the colors in each site, without having to modify or to overwrite bits of the css files located in `/sites/all/themes/Theme/css`.

I already tried a few things, one which could work but I didn't like enough, so I am looking for a general, good and most important, fast method.

What I already have achieved and what (I think) is very usefull:

```
function theme_css_alter(&$css) {
    $css['sites/all/themes/Theme/css/colors.css']['data'] = conf_path() . '/colors.css';
}

```

This function changes the default `colors.css` provided in `/sites/all/themes/Theme/css/colors.css` and replaces it with `/sites/default/colors.css` OR `/sites/alternative/colors.css`, depending on where you are.

I have already tried the following:

* Used PHP to get the correct colors.css file and use PHP-variables all over my CSS-files. This should actually work. But I don't quite like it because you end up with a lot of .php files which are actually .css and a lot of ugly php-syntax in the css files.
* I tried the lessphp drupal plugin. This did it's work for replacing the variables but the caveat was this: If I want to include the correct colors.css file, I need to use php. Therefore, my less file needs to have the extension PHP. LESS is build so that you can only 'parse' files with the less extension, so this wouldn't work. I quite liked this though, it used some nice caching which would also be the quickest way. What I could do here is dive into the lessphp library and change the code that says 'only .less files please!' to also accept .less.php files.

So, my questions are:

* Does anybody see a different approach that would also work and is fast?
* If yes: please elaborate
* If no: Which of my previous methods do you fancy and why? What would be the best approach?

# Answer
Well, I found out something that is quite useful:

Instead of trying to import the color.less file in each 'basic' theme css file, I do it the other way around: I import all the basic theme css files in colors.less, like this:

```
@basis: blue;
@donker: black;
@licht: pink;

@import "../all/themes/Theme/css/basic.less";

```

Then I had to remove all the stylesheet definitions in the .info file and changed the template function to:

```
$css = drupal_add_css(conf_path() . '/colors.less', array('group' => CSS_THEME, 'weight' => 115, 'browsers' => array('IE' => 1, '!IE' => 1), 'preprocess' => FALSE));

```

No hassle with php, and it works, is cached when I want it, and fast!
> 5 votes

---
Tags: theming, multi-sites
---


# Question
Title: Update default value of form element with AJAX
I have an email field on node add form , I want to check if this email exist fill the city field in the same node form , then my code is :

```
function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );
}

function user_ajax_check($form,$form_state){
    // load the user then
    $form["field_user_city"]['und'][0]['value']["#default_value"] ="foo";
    return $form["field_user_city"];
}

```

# Answer
> 2 votes
The value must be set in the `hook_form_alter`, not in the callback of ajax :

```
function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );

  if(!empty($form_state['values']['field_user_email']){
       $form["field_user_city"]['und'][0]['value']["#default_value"] = "foo";
  }
}

function user_ajax_check($form,$form_state){
    // load the user then
    return $form["field_user_city"];
}

```

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


# Question
Title: define custom jquery event to use in ajax form
How can I create custom jquery event to use in event:

```
$form['submitted']['subject']['#ajax'] = array(
  'callback' => 'suggest_ajax_callback',
  'effect' => 'fade',
  'event' => 'change',
);

```

for example I want execute `suggest_ajax_callback` each time user enter `Space` while filling text-field. so "How Can I Pay?" will cause 3 time execution...

# Answer
The solution for your question is not handled compelety by back-end of drupal.

**By default drupal ajax not support customized event**
You can acheive your means by jquery and ajax(non-drupal ajax)
Something like this

For using get data by jquery ajax you need first seta menu link for listen to your ajax requst, and in callback of your menu you passed back a block or any data you want.

```
function yourmodule_menu () {
   $items=array();
   $items['youruniqepath'] =array(
        'title' => 'my menu',
        'description' => 'A menu link to handle ajax request',
        'page callback' => 'yourhandlerfunction',
        'acess callback' => TURE, //you can set it with your permission
      );
  return $items;
   }

```

and in yourhalderjust need pass a block

```
function yourhandlerfunction () {
  //with any method you want get your block,
  // I suggest something like this
    $block = module_invoke('module_name', 'block_view', 'block_delta');
    print render($block);

}

```

and in your clientside get it with something like this

```
  $('#yourelement').change(function() {
    if( checkfor your means) {
         $.ajax({
                       type: "POST",
                       url: 'youruniqepath',
                       //data: {}, you can also pass block name and act more dynamicly
                      success: function (data){
                          $('#yourplace').html(data);
                      },});
         }

```

});
> 1 votes

---
Tags: 7, ajax
---


title: How to show applied filters in a View?

text:
# Question
Title: How to show applied filters in a View?
I have defined some contextual filters to a View, i need to show a string like "Applied filters: filter\_name1:xyz, filter\_name2:ykx". Which is the cleanest way to do it in Views3?

# Answer
The best way is to implement a template\_preprocess\_views\_view. The view object is available as `$variables['view']`. `kpr` this to find the property that has the filters in it. Process them into something readable. Then set a new entry in `$variables`.

Then make a new views-view.tpl.php, and name it appropriately for your view (edit the view, click Theme: Information to see the template suggestions), and add the `print` statements to output the filter info.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Alter the conditions in a DatabaseCondition object
Would there happen to be a way to alter the conditions in a DatabaseCondition object? Say I have this:

```
DatabaseCondition Object
(
    [conditions:protected] => Array
        (
            [#conjunction] => AND
            [0] => Array
                (
                    [field] => search_index.type
                    [value] => node
                    [operator] => =
                )

            [1] => Array
                (
                    [field] => DatabaseCondition Object
                        (
                            [conditions:protected] => Array
                                (
                                    [#conjunction] => OR
                                    [0] => Array
                                        (
                                            [field] => search_index.word
                                            [value] => foo
                                            [operator] => =
                                        )

                                    [1] => Array
                                        (
                                            [field] => search_index.word
                                            [value] => bar
                                            [operator] => =
                                        )

                                )

                            [arguments:protected] => Array
                                (
                                )

                            [changed:protected] => 1
                            [queryPlaceholderIdentifier:protected] =>
                        )

                    [value] =>
                    [operator] => IS NULL
                )

        )

    [arguments:protected] => Array
        (
        )

    [changed:protected] => 1
    [queryPlaceholderIdentifier:protected] =>
)

```

I would like to make changes on the `conditions`. Any ideas?

# Answer
You can grab the conditions array for the full query like this:

```
$conditions =& $query->conditions();

```

As you're getting the array by reference any changes you make to it (and the conditions within) will be reflected back on the query object before it's executed.

If you want to replace all of the conditions in the query you can simply overwrite that array with a new one (filled with conditions obviously).

It might be safer, though, to loop through the conditions array and remove/alter only the conditions that you need to change. This will make sure that conditions added by other modules will still get their chance to be included in the query.

Editing an existing condition is tricky (I haven't managed to get it to work yet though I haven't tried very hard!). I think your best bet is to rebuild the conditions you need to change from scratch and replace them rather than try to edit them directly.
> 4 votes

# Answer
You could try `DatabaseCondition::condition($field, $value, $operator)`, which adds another item below your `bar` value. But I think that it won't work for you, beacuse there could be another problem with the `$field` value.

This is the same problem preventing you from adding a new `DatabaseCondition` object to `$view->query->where` too.

I figured out that the `$field` value is a refference to an **actual field within fields section** of the `$view` object. Have e.g. a **taxonomy tags field** and a **view filter** that shows nodes only **with both terms** `foo` AND `bar`.

**This will result in:**

* adding two *(hidden)* fields into your query - called sth. like: `field_term_tags_1` and `field_term_tags_2` *(simplified)*
* adding a `DatabaseCondition` object with two conditions like: `field_term_tags_1|foo|=` and `field_term_tags_2|bar|=`

**So the final SQL will look sth. like:**

```
SELECT ..., field_term_tags_1, field_term_tags_2
FROM ...
WHERE field_term_tags_1 = 'foo' AND field_term_tags_2 = 'bar' ...

```

So in this case I'd recommend you to use your own PHP filtering in `hook_views_pre_render()` *(after the query has been made)* rather than messing with the `$view` object.
> 1 votes

---
Tags: views, database
---


title: Taxes in ubercart

text:
# Question
Title: Taxes in ubercart
I'm trying to charge cali sales tax in my ubercart store. I have taxes turned on, and have it set up with

"and: California Sales Tax conditions"

Taxes don't show up at any point in the checkout process.

What am I doing wrong?

# Answer
> 2 votes
I do not know what the California Sales Tax conditions was. I think it might be some kind of stub for generating a custom condition somehow. Anyway, what I ended up doing was using the custom PHP code condition and calling this from it:

```
function check_california_tax($order) {
    $state = uc_get_zone_code($order->delivery_zone);
    if ($state == 'CA') {
        return true;
    } else {
        return false;
    }
}

```

# Answer
> 0 votes
California Sales Tax has three elements. A state tax, a county tax and a district tax.

There are products that are exempt of all three taxes, like digital downloaded goods. State and County sales tax are always charged for a taxable good shipped in the state. The district tax is based on the shipping address of the goods.

There are over 400 district taxes, and multiple taxes can apply to a single address. Being districts, like a school catchment area for a school tax, or a hospital service area fro a hospital tax, the boundaries are not based on zip codes.

Further it is important that the correct districts and amounts are recorded for reporting the tax when paid over. In addition to correct reporting being a requirement of the business license, the districts get 50% of the monies for these taxes (50% to the state) and depend on them being correctly paid over to fund the costs of the local services.

It is not possible to do this using rules, one does need a table of districts, rates and how to determine what districts an address is in. The best way I have found is to use a commercial service from Avalara, Inc. The costs to them are a fraction of the development costs, let alone costs of maintaining the rates table, and eliminate audit issues later in the life of the business.

Google "ubercart avatax" - the results will be obvious.

---
Tags: 7, ubercart
---


# Question
Title: Can the 'update' module be made less aggressive?
Running an update check on all the installed modules on my site takes quite some time, and sometimes even exceeds PHP's runtime limits. Leaving the module enabled makes using the web based administration very difficult, as many different actions cause it to make a full run.

Is there a way to leave the module enabled, but only have full updates triggered by cron instead of every time the status or module pages are visited in admin?

I'm using Drupal 6.26.

# Answer
> 4 votes
As far as I can tell there's nothing about visiting the modules admin page (or any other admin page) that would invoke a check for update data.

## Drupal 6

For Drupal 6 the work is done by `_update_refresh()`, which is inadvertently called from several places within the update module itself. Those of note include:

Since none of those are called for every admin page, and Drupal 6 doesn't have auto-cron (you also mentioned in the comments you don't have poormanscron installed), it doesn't seem like any of the core functions will be the culprit.

There's no way to unset hook implementations for specific modules in Drupal 6 (there is in Drupal 7, see below) so short of editing the module file directly I don't think there's anything you can do about that.

## Drupal 7

The work is done by `update_get_available()`, and that function is only called from 4 places by core:

If the update is happening on any other pages than those listed above it's either caused by a contrib/custom module, or (more likely) because you have auto-cron on, and the cron run is being invoked. There might be more to it than that but I can't find anything looking through the core code.

As far as the status page goes, you could remove the update module's implementation of `hook_requirements()` from the cached list of hook implementations, effectively stopping the check from happening when you go to that page. It means you won't ever get that particular line in the status report, but if you're ok checking for updates manually then this won't be a problem.

The way to do this is to implement `hook_module_implements_alter()` in a custom module:

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'requirements') {
    unset($implementations['update']);
  }
}

```

## Either version

You can slow the frequency of update-checks down a bit by setting the `update_check_frequency` variable to something longer than standard. The variable contains the number of days that need to pass before the update data is checked again.

# Answer
> 3 votes
In regard to the **Update** module, my solution is to never use it on a live website, only in Staging or Devel, but not with the final website.

Also Elysia Cron lets you to choose when you want to run all the hook\_crons. I think this is is a "must have" module in all drupal projects.

# Answer
> 0 votes
Yes. Of course. I don't think it is built-in, so you actually have a pretty cool idea for an easy but useful custom module. I actually made something very close to this not too long ago.

You create a module say updateManager, and in your module file add elysia cron as dependency,

One of the goals of the module could be to have your module add an text field on the update configuration page to easily set the date and time you want update.php to run.

This field supports crontab syntax 0 * * * * syntax,

* Thanks to elysia cron api, it is easy to set, store and retrieve and play with cron task in your code. If you want you could even just create a cron task here that overides the main cron task and would be listed in elysia cron task panel.

+ In your custom module you can easily add the field to the 'update configuration form' with a form\_alter on the form.
    + Another option is to turn off updates, and do it with a cron task that runs update via drush.

---
Tags: updating, cron
---


# Question
Title: How can I debug a Views 2 block argument set via "Provide default argument" and "PHP Code"?
I am using Views 2.16 on Drupal 6. I have the Content Profile module loaded and the profile has a nodereference field to another content type called Project. I would like to show a list of Projects in a block on the side when viewing the user page. I need to provide a default argument to a view since it is a block.

So the urls look like /user/admin, /user/joe who are related to content profile nodes 1867 and 1952 etc. I have the view showing correctly if I feed it a node id for a user profile as a hard coded value.

Now I want to do some stuff in the default argument code such as user\_load(array('name' =\> arg(1)), content\_profile\_load($user-\>uid) and so on but it's not working.

What I have tried: print\_r, var\_export('abc', true), dpm($user), watchdog('php-test', 'a string').

None of these methods gave me any debug output. How can I debug the argument code?

# Answer
> 0 votes
Rather than trying to debug the PHP code in the view, use the devel module's ability execute PHP code `/devel/php` to debug the bulk of your code before putting it in the Views PHP default argument field.

```
$arg = 1;  // admin or root user
$user = user_load(array('name' => $arg);
$profile = content_profile_load($user->uid);
var_dump($profile);

```

Then when you are ready you can drop the first linewhere we used the `$arg` variable for debugging and instead use `arg(1)`

```
$user = user_load(array('name' => arg(1));

```

# Answer
> 0 votes
After more testing it appears that the watchdog function does work for debugging the embedded PHP code in the Argument Validator and Argument Default Value. I believe my validation was too strict previously and was preventing any output. For example embedding the line below in the "PHP validate code: " area gives all the argument components.

```
watchdog('block-args-php', var_export(arg(), TRUE));

```

# Answer
> 0 votes
I think you are using a couple extra steps here.

If `www.yourhost.com/users/joe` is a content profile with nid `1952` its system path is indeed `www.yourhost.com/node/1952`. But you are ignoring the fact that it is also "owned" by user joe, and instead going through the user load to get his (I assume :) uid, all the while it's already in there much like this:

```
 $node=menu_get_object(); // returns everything about the current node (so this won't work in a Views preview :))

```

where `$node->uid` will contain the owner of the node you are looking at, which, if we are sitting on a content profile, is that user's uid.

Further, in Views 3 at least, I've not used Views 2 in a long while, you can use a user id as an argument, and for the default argument needed in your block, have Views grab it from the url/set it to the node author, so, you may be able to do all of this without any custom php.

---
Tags: blocks, views
---


# Question
Title: can i add multiple value in field ? (please see an image)
I need to do the stock management website with 2 Content type Supplier and Product. First I add contents in Supplier content type. Then I add node reference field in Product content type and call it supplier and make it multiple value. it's looks good, i can select suppliers and save it. but in my concept i need to check which supplier sale this product and how price. so i need to add suppliers and price in the same form like my image,

my concept image, create by photoshop, can i do like this ?

the propose of this form, user can check how price of each supplier for this product and they can choose the lowest price for purchase in the next process.

Guys, did you have the idea that i can do like this ?

Thanks for share :D

# Answer
For simmilar needs, i am using this module, for me it is very good! There are some other alternatives too, but for me this module is proven as stable:

http://drupal.org/project/double\_field
> 1 votes

---
Tags: forms
---


title: EntityFieldQuery condition

text:
# Question
Title: EntityFieldQuery condition
How can i ommit an condition in Entity Field Query if variable do not exist, for example

```
->fieldCondition('field_filter_color', 'tid', $filter_color)

```

Recieves in $filter\_color one term id. But there are situations where $filter\_color is not present, so i would like to do: if $filter\_color is empty, ignore this condition.

Alternative is to present it as an array like

```
->fieldCondition('field_filter_color', 'tid', $filter_color, 'IN')

```

and prepopulate all values in $filter\_color, and if $filter\_color is chosen, create array with only one value, but i am not sure it is best way to do it.

# Answer
> 2 votes
You can simply do this:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
// all other conditions go here

if (isset($my_field_val)) {
  $query->fieldCondition('my_field', 'value', $my_field_val);
}
$result = $query->execute();

```

Untried code as I don't have access to my files at the moment.

# Answer
> 1 votes
Unfortunately `EntityFieldQuery` can only query for what is there, it doesn't have the capacity to query based on empty fields.

However cumbersome it might be, your solution is about all you can do other than add a tag to the query, and implement `hook_query_alter()` to manually add the "empty" condition to it.

---
Tags: database
---


title: How to prompt user to download a file?

text:
# Question
Title: How to prompt user to download a file?
How to prompt user to download a file in browser from custom module php code?

I tried first the php way

```
<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>

```

It silently fails. Then I realized there is a "drupal way" to do it. So I tried

```
drupal_add_http_header('Content-Type', 'application/octet-stream');
drupal_add_http_header('Content-disposition', 'attachment; filename='.$fname);
drupal_add_http_header('Content-Length', filesize($fpath));

```

but still not working. I think one possible reason for failure is that I am not sure at each step which is the correct path I should use.

Should it be '/home/mysite/public\_html/sites/default/files/pdfs/'.$filename.'.pdf'

or just the part that starts in the drupal root '/sites/default/files/pdfs/'.$filename.'.pdf'

or even just 'public://pdfs/'.$filename.'.pdf'

as I see it in some other threads. I wonder why it has to be so complicated.

# Answer
> 3 votes
Have you tried the http://drupal.org/project/file\_force Module ?

Some details from the module's project page:

> File Force Download can be used to force the user's web browser to download the file to disk instead of displaying it in the browser window.
>
> Web browsers today are pre-configured to render various types of media directly, such as text files, various image, video and audio formats, PDF documents, and Flash movies. While it is still possible to save such files afterwards by right-clicking on them and selecting "Save As..", it is sometimes desirable to just offer the file for download in the first place. File Force Download solves this issue by supplying a file with certain HTTP headers which instruct the web browser to download the file to the user's disk instead of displaying it in a browser window.

It should be a good starting point for inspiration for your own module.

# Answer
> 1 votes
drupal\_realpath() will give you the absolute path to the file on your server, however, the recommended way is to use file\_create\_url() to generate the URL to the file, which also sets you up for CDN integration.

# Answer
> 1 votes
There is a function called file\_transfer() that will take a URI (like public://pdfs/myfile.pdf) and the HTTP headers in an array, see

http://api.drupal.org/api/drupal/includes!file.inc/function/file\_transfer/7

---
Tags: users
---


# Question
Title: How to redirect to a different URL based on node content while loading a node
I have a site that uses the webforms module to gather user information. On the front page there is a list of previous submissions. Each of which has a link to view the submission (generated by Views module)

Link is like thingie.com/node/115/submission/1763

However, some users are saving the form as draft and coming back at a later date. When they get to the view page they aren't noticing they can click on the edit tab and are filling in a second submission. So we're getting 'weird' duplicates and they're wasting time.

As the submission view node is loading I'd like to check if it is a webform; which is in draft; and they are the submitting user. If so I'd like to redirect them to

thingie.com/node/115/submission/1763/edit

I think know how to do the redirect and the test but I'm being slow and am not sure what hook to catch.

I'm about to investigate the node load hook but wondered if there was a better way.

# Answer
Ah ha... and I just learnt about row and field level templating in Views... isn't views incredible?!

I followed the instructions here http://drupal.org/node/352970 and can alter the link and it's text based on the context of each row.

Super!
> 0 votes

# Answer
You should take a look at hook\_init, it's the best option to make a redirect. But it's not the best option.

You should try to have 1 views with a attachment.

I de user save the webform the main view should show it. If it's a draw the attachment view should show it. And in the main views show a text like "Please finish your lead" or something similar.

Oskar
> 0 votes

---
Tags: webforms, redirection, forms
---


title: reference a field in CCK Drupal 6

text:
# Question
Title: reference a field in CCK Drupal 6
I have two content types: students and chemistry labs. Students content type has a cck field that lists student type (field\_student\_type) with Chemistry.Biology, Math, and etc. And Chemistry labs content type has a cck field (field\_chemsitry\_students) that node references to "students" content type as a list widget. Since it's a chemistry content type, the list needs to pull only chemistry students. With the current setup, it's pulling every student. I can't set the filter in views as it's a drop down list (widget). Views won't let me put operators to be ield\_student\_type = "Chemistry Student". How would I filter this out? Any suggestions? php filter? The question is more about field to field reference using node reference.

# Answer
Views can most certainly filter on CCK field values. In the view filters, select the content group, and then select whatever field you are wanting and then for the operator select "is equal to" and put in whatever you want.

So, in this specific case, you could create view as follows:

filter on field\_student\_type equal to "Chemistry" filter on node type "Student"

sort by node title (so the students are alphabetical perhaps?)

return node title (without a label so the dropdown doesn't say Title: FOO) as the field

Then, in your content type of Chemistry Labs, you would select this view in the "Advanced - Nodes that can be referenced (View)" section and it should return only node references to students with student\_type equal to chemistry.

(Now, if you find it returns only 10 students no matter what you are doing, don't pull your hair out, that's an issue between versions of cck and views, and a solution for another day :)

ADDITION:

Since you seem to be hitting an issue between Views and CCK here as well with respect to how limits are set, I resolved this issue locally by replacing a line of code in the nodereference.module with these lines of code :

```
if (method_exists($view, 'set_items_per_page')) {                // views is defaulting to 10 now
  $view->set_items_per_page($limit);                             // and has changed how to set it
} else {                                                         // so this does it the new way
  $view->display_handler->set_option('items_per_page', $limit);  // if new views and the old way
}                                                                // if old views....

```

after

```
// TODO : for consistency, a fair amount of what's below
// should be moved to content_plugin_display_references

// Limit result set size.
$limit = isset($limit) ? $limit : 0;
$view->display_handler->set_option('items_per_page', $limit);    // REPLACE THIS LINE WITH THE ABOVE

```

in the `_nodereference_potential_references_views()` function.

Whether or not you want to hack up a module or wait for an official fix is up to you.
> 0 votes

# Answer
I have no idea why the maintainers haven't fixed this glaring oversight, but after hours searching and testing I figured his out and want to share.

Total results for views with multiple displays and pager

Inline with the view, drop this in view header:

```
<?php
print $view->query->pager->total_items;
?>

```

Outside the view:

```
<?php
$view = views_get_view('MY_VIEW_NAME');
$view->set_display('MY_DISPLAY'); // like 'block_1'
$view->execute();
print $view->query->pager->total_items;
?>

```

That freakin' easy...
> 2 votes

---
Tags: entities
---


title: List of user names and emails

text:
# Question
Title: List of user names and emails
I have a role called "Secretary" and I would like for the role to be able to access a "view" with a list of usernames and emails. What's the easiest way to do this?

I know how to let only the secretary have access to the page, and I have the views module installed. But I'm not that good with it yet. Any ideas?

# Answer
Simple - on your view, select "Page Settings" -\> "Access: Permission" then chose "Role" and select your "Secretary" role.
> 1 votes

---
Tags: views, 7
---


# Question
Title: Will Drupal or PHP use APC if its installed on the server?
So I have AuthCache installed with XCache but I am not getting any noticeable speed. Im on D6 so its not possible to use APC? I mean if APC is installed on the server , will Drupal use it even if I don't install the APC module?

Thanks!

# Answer
Drupal, like any other PHP app will an APC opcode cache if it's available. Though there are a few settings that may **prevent Drupal from using APC** as it should.

First and foremost make sure APC has enough memory to work with. Drupal can eat up a ton of memory and if your APC cache is too small it may actually *hurt* your performance.

The first memory relevant setting I would look at is the apc.shm\_size. APC's defaults setting have never worked out of the box for any of my Drupal installs. On some servers I have this is as high as 512M.

```
apc.shm_size = <MB Allocated>

```

---

**APC may not be caching .module and .inc files by default!**

Depending on your setup, APC may not be caching .MODULE and .INC files at all. This means that the majority of Drupal's slowest code may never make it to the APC cache in the first place.

The fix? apc.filters

On many of my Ubuntu servers adding the following line to my apc.ini has an enormous performance impact on my Drupal installs.

```
apc.filters = "+module$,+php$,+inc$,-admin"

```

You may also want to monitor your APC cache using the apc.php script that's generally bundled with APC.

You can also use apc.php to verify that .module and .inc files are making it into your APC system cache.
> 3 votes

# Answer
APC is an opcode cache for PHP. When your webserver serve a PHP page, it'll first compile it and then execute it. APC cache the compiled code in order to avoid this extra steps and thus make PHP execution faster.

You can install APC on your server without the need of the related module and it will optimized Drupal speed. Don't forget to tweak the `apc.ini` configuration file by mainly increasing default memory especially if you have a lot of modules.
You can have some interesting statistics using the `apc.php` file provided with APC.

Some (old) benchmark for APC: Benchmarking Drupal with PHP op-code caches: APC, eAccelerator and XCache compared
> 2 votes

# Answer
Drupal is not aware of APC. If APC is running for your PHP code it should improove PHP execution times. Whether this makes a noticable difference for the performane of your Drupal installation is a different question.
> 0 votes

---
Tags: 6, caching
---


# Question
Title: Drupal Menu Page Callback Function went wrong with arguments
I am new to Drupal, and I was trying a small example from Book "Pro Drupal 7 Development", this is an example of basic menu system, here is code:

```
function menufun_menu() {
$items['menufun'] = array(
    'title' => 'Greeting',
    'page callback' => 'menufun_hello',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}

function menufun_hello($first_name = '', $last_name = '') {
return t('Hello, @first_name @last_name'，
    array('@first_name' => $first_name, '@last_name' => $last_name));
}

```

But I got HTTP 500 Error all the time:

> The website encountered an error while retrieving '*http://example.com/SampleDrupalSite/*'. It may be down for maintenance or configured incorrectly. Here are some suggestions: Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

When I tried function menufun\_hello() without page callback arguments, it was all okay. Here is code without parameters:

```
    function menufun_hello() {
    return t('Hello!');
    }

```

May I ask what was wrong with this? (Plus, I've googled before I post it here).

# Answer
> 1 votes
Really embarrassed to say I made one tiny small mistake in this line of code:

```
return t('Hello, @first_name @last_name'，
array('@first_name' => $first_name, '@last_name' => $last_name));

```

I was typing the first comma while switched to Chinese Simplified PinYin, correct code should be:

```
return t('Hello, @first_name @last_name',
array('@first_name' => $first_name, '@last_name' => $last_name));

```

After I changed it, everything is okay now. Thank you all for paying attention to my silly question.

# Answer
> -2 votes
500 Internal Server Error How To Fix a 500 Internal Server Error

By Tim Fisher, About.com Guide See More About:browser error messagesie problemsfirefox problemschrome problemssafari problems How You Might See the 500 Error

The 500 Internal Server Error message might be seen in any number of ways because each website is allowed to customize the message. Here are several common ways that you might see the HTTP 500 error:

"500 Internal Server Error"

"HTTP 500 - Internal Server Error"

"Internal Server Error"

"500 Error"

"HTTP Error 500" 500 Internal Server Error messages can show up in any browser in any operating system.

The 500 Internal Server Error displays inside the Internet browser window, just as web pages do.

Cause of HTTP 500 Errors

The 500 Internal Server Error is a very general HTTP status code that means something has gone wrong on the web site's server but the server could not be more specific on what the exact problem is.

That's not a lot of information to go on but there are a few things you can do.

How To Fix the 500 Internal Server Error

The 500 Internal Server Error is a server-side error, meaning the problem is not with your computer or Internet connection but instead is a problem with the web site's server.

Even though the issue is not yours to fix, there are some things you can try:

Reload the web page. You can do that by clicking the refresh/reload button, pressing F5, or trying the URL from the address bar again.

Even though the 500 Internal Server Error is reporting a general error on the web site's servers and not your computer, the server error may only be temporary. Trying the page again will often be successful.

Note: If the 500 Internal Server Error message appears during the checkout process at an online merchant, be aware that duplicate attempts to checkout may end up creating multiple orders - and multiple charges! Most merchants have automatic protections from these kinds of actions but it's still something to keep in mind.

Come back later. The 500 Internal Server Error message is one of the most common HTTP error message seen when checking out during an online purchase so sales are often disrupted. This is usually a great incentive to resolve the issue very quickly.

Contact the webmaster. Chances are good that the website administrators already know about the 500 error but if you suspect they don't, you can always try to contact the website directly.

Also Be carful about how pass arguments to callback function . You returned `t()` function in where not form exist . hook\_menu documentation
Pass arguments using hook\_menu

---
Tags: hooks
---


# Question
Title: How to create multi-page node views in D7
I have a content type with user related fields that users can fill out, similar to a profile. I would like to split this node into a series of sub-pages/multipages and group fields together on each sub-page, rather than having all fields show as one huge node.

It's very similar to having tabs or a pager system but I don't want the actual tabs or pagers to be visible since I need to have my own links to each "tab"/multipage. I have tried to do this with Field Group module but it doesn't allow multipage groups in the node view (only in the node edit form). If I create Field Group tabs, that does split the node but then I have no way to hide the actual tab labels and (as far as I know) it is awkward trying to link to each of the individual tabs since they don't have a proper url. If it were possible to create additional local task tabs (after View, Edit) each tab would have its own url (node/#/edit, node/#/info, etc), and I could then hide, sort and rename the tabs very easily using Tab Tamer. But it's my understanding that there's no module with this sort of "add a local tab" functionality.

Is there currently a way to create multipages with D7, in the node view?

# Answer
> 1 votes
Have you tried the Book module which comes with core? It will do some bits of what you need but you can build a module to further modify it.

---
Tags: nodes
---


# Question
Title: How was this amazing drupal performance presentation done?
How was this amazing drupal performance presentation ( http://rupl.github.com/high-performance-theming ) was done? Which jQ libraries are needed? And what is the best place to ask?

Thanks

Amnon

# Answer
> 2 votes
It's nothing overly complicated; the 3d navigation makes use of the reveal.js library.

> reveal.js is a framework for easily creating beautiful presentations using HTML.

And then there are a few helper libraries:

* `Highlight.js` \- for syntax highlighting
* `classList.js` \- adds element.classList support to browsers that don't support it
* `carousel.js` \- seems to be custom DOM helper functions.

Reveal is pretty easy to use, it just requires a lot of patience and a will to succeed. Good luck!

---
Tags: javascript, performance
---


title: Omega theme meta tag problem on Google

text:
# Question
Title: Omega theme meta tag problem on Google
I'm using Omega theme. But when search my site on Google, description is site menu items. I want change this area via spesific word.

So, open my template.php file and add this codes:

```
function site_page_alter($page) {
   $meta_description = array(
            '#type' => 'My Site Desc',
            '#tag' => 'My Site Desc',
            '#attributes' => array(
                'name' => 'My Site Desc',
                'content' =>  'My Site Desc'
            )
   );

drupal_add_html_head( $meta_description, 'My Site Desc' );
}

function manualMetaTags($path) {
    $description = "My Site Desc";
    $keywords    = "My Site Desc";
    print "<meta name='description' content='".$description."' />\n";
    print "<meta name='keywords' content='".$keywords."' />\n";
}

```

And add main.js:

```
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
<?php manualMetaTags($_GET['q']); ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>
<script type="text/javascript">

```

After, send sitemap to Google. My description is seen but with menu items.

E.G.

My site desc on Google:

MAIN - NEWS - CONTACT

When add codes:

My Site Desc MAIN - NEWS - CONTACT

But i want only seen My Site Desc. How can i do it?

# Answer
I'm afraid that's not really your decision to make...Google will take what it feels is the best representation of your site's description, whether that be the meta description tag or some text from elsewhere in the body.

The best you can do is make sure that you have `<meta name="robots" content="noodp">` (which Google supports) somewhere in the document `<head>`. That will at least mean your title/description will come from somewhere in your page source, and not from the Open Directory Project (which is a distinct possibility otherwise).

The most important thing...don't expect instant results. Google will revisit your site when it's ready, and there's still no guarantee it will use exactly the text you want it to for the SERP description.

If you're not happy with that outcome, contact an SEO specialist who might be able to point you in the right direction.
> 3 votes

# Answer
Like @Clive said, Google picks a text based on search input. If the user's keyword is in the meta description, the description will be displayed. If the user's keyword isn't in the meta description, Google will assemble a text from the page from top to bottom.

**However**:

In your case you could try to position the content before the menus and then display it the other way round with CSS. This way, when Google assembles a text it will take a snippet from the content, not the menu. This is the way Wikipedia does it (disable CSS to see it).
> 0 votes

# Answer
Try to increase the words in your description tag to prevent Google from assembling other word from the web page content to fill up the description area. and wait until the next crawling to see the result.
> 0 votes

---
Tags: 7, javascript, theming, meta-tags
---


# Question
Title: How to add the value of a drupal field to the class of a wrapper div
Working on a clients drupal 7 site, I have a content type that is promoted to the front page. The content type has a list field, I want to use the value of that field to add a class to the wrapper div on the node teasers populated to the front page. For example the html output would be something like this:

```
<div class="field_value">
content
</div>

```

I'd prefer not to have to use a view or nodequeue to do this as it's easier on the client administering their site to simply promote items to front page.

I've been trying to add the class in the node.tpl.php file but for some reason I just can't get it to work. I've tried creating a preprocess variable in the template.php file but all I get in the output is: div class="Array".

Does anyone have any ideas on why I'm just getting the word "Array" output? or any ideas on how to solve my problem?

Thanks

# Answer
> 1 votes
Something like this should do it:

```
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node'] == 'some_type') {
    $field_items = field_get_items('node', $vars['node'], 'field_name');
    $first_item = array_shift($field_items);

    $value = $first_item['value'];

    // If you want to write <div class="<?php echo $extra_class; ?>">... in your template file:
    $vars['extra_class'] = $value;

    // Or if you want to add this to the classes on the main node <div>:
    $vars['classes_array'][] = $value;
  }
}

```

# Answer
> 0 votes
You should do in the template.php file.

You should look at function my\_theme\_preprocess\_node(){ // custom code. }

You will be able to add the class to the body wrapper there. You should take a look at: \- http://api.drupal.org/api/drupal/modules!node!node.module/function/template\_preprocess\_node/7 \- http://drupal.org/node/1170752

Also when you should know how to use http://drupal.org/project/devel module and http://drupal.org/project/devel\_themer module when you build themes.

Oskar

---
Tags: 7, theming, nodes
---


# Question
Title: How do I add jQuery to specific node form?
I'm using an Omega sub-theme and I want to do this the correct (best practice) way.

Basically I'd like to add some script so that selects a value in a select box based on a previously selected value in another select box. I have the code, just need to plug it in to my theme now.

However, I only want it to load on node creation forms of node type "X".

Any help greatly appreciated, thank you!

# Answer
> 2 votes
Install the JS injector module. Then go to *admin/config/development/js-injector*. Add a new rule. Fill the *JS code* field with your script.

In the *Pages* fieldset select the *Pages on which this PHP code returns TRUE (experts only)* option and enter the following code:

```
<?php
if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'content_type') {
 return true;
}
return false;
?>

```

Replace `content_type` with your content type name.

This is a theme independent solution. Another way is adding your script in `hook_preprocess_page` in *template.php* file of your theme.

# Answer
> 1 votes
Have you take a look to drupal native ajax?

If ahah is not good for you, you should add the jquery in the #after\_build function, because when a validation go wrong, Drupal no add all the js files. With after\_build function it will always add your js (http://drupal.org/node/322290#comment-1189081)

I hope this help you.

Oskar

---
Tags: javascript, theming
---


# Question
Title: Get all user profiles from list of users
I am evaluating some custom code in a rule. I want to get a list of users, then load all of the associated profiles from the profile2 module. My code below, loads all the users, and I got an array of the UIDs to put into the profile\_load\_multiple() function but it is just returning one user profile, I want to return all profiles. Eventually I want to compare a term from a field (project resources) in the node 'project' I am creating with a field (resources) that is in each user main profile. My intention is using rules to accomplish this.

```
$users = entity_load('user');
$arrayuids = array();
foreach ($users as $user)
{
array_push($arrayuids, $user->uid);
}
$profile = profile2_load_multiple($arrayuids, FALSE);
dsm($arrayuids);
dsm($profile);

```

# Answer
> 2 votes
Your first problem is that you send uids instead of pids. First argument of profile2\_load\_multiple is $pids which are profile2 ids.

Try this code:

```
$users = entity_load('user');
$arrayuids = array_keys($users);

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
    ->propertyCondition('uid', $arrayuids, 'IN');

$profile = $query->execute();

dsm($arrayuids);
dsm($profile);

```

I haven't tested it but it should work.

---
Tags: rules, users
---


# Question
Title: automatically reference user to node by date field
I'm totally stuck in this situation, can't find any solution, please help!

i have content profile date field "date of birth" (y-m-d) and node "horoscope" with multiple value date field (m-d). When new user registers his date of birth I need to auto-reference to the horoscope node with same date. Year is not important in that case.

For example:

I have "horoscope" nodes: (title - dates)

Horoscope A - 01.23, 03.11, 05.02 Horoscope B - 02.14, 07.01 Horoscope C - 11.11 Horoscope D - 02.10, 03.02, 05.07, 09.14 After new user registers his account with date of birth: 1977.07.01, I need "horoscope\_reference" field to automatically assign him "Horoscope B" or if entered date of birth: 1234.03.02, "horoscope\_reference" should be assigned to "Horoscope D" and so on...

any suggestions please? (drupal 7)

Thank You..

# Answer
Use the computed field module for this. This lets you add your own conversion logic into the field (using PHP) that will be processed on entry. So download and enable the module, then add a field for your horoscope, then in the settings field, you want to add your PHP logic, ex (roughly):

```
$date = new DateTime($entity->field_profile_dob[LANGUAGE_NONE][0]['value']);
$month = $date->format('m');
$day = $date->format('d');
if (($month = 1) && ($day < 21)) {
    $answer = "some sign";
} else if .. etc.

```

That will take some time to write that logic. You might be better off putting this in a module then leaving it in the settings. There are dozens of examples in the documentation that should help you get started on this.
> 0 votes

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


# Question
Title: Can authenticaded users publish own content and see only own content?
Besides the module which has many interesting features, what's the best way to allow authenticated users publish content (based on a custom node type), but only allow such content to be seen only by an administrator (an specific role), or that same user only? Such content when published, will only be visible to a role type (administrator) and the user who published it.

# Answer
For node access, you should set permissions based on role.

It is /admin/people/permissions on Drupal 7.

Yo can set who can view, edit , create any of your content type based on role.

For more grained field permission based on role, use Field Permission module
> 1 votes

---
Tags: 7
---


# Question
Title: Taxonomy term name alias in taxonomy term autocomplete
I'd like to have two or more names for one Term-ID in my custom taxonomy dictionary. As for now I've added a custom field and named it "Synonyms". The field can have multiple values.

How can I display values of the "Synonyms" field in the autocomplete taxonomy widget (or even a list control) together with original names of the terms (is there any way to do this?).

Real life example:

```
tid  |name              |synonyms
_____|__________________|___________________________
1    |sneakers          |gym shoes, tennis shoes

```

The main name would be: sneakers but while tagging a user may also type: "tennis shoes" into autocomplete and it will link the node field (for example: "Shoes type") with sneakers (tid 1).

# Answer
> 0 votes
Two options to maybe investigate (neither are easy...):

1. You could create a custom module using hook\_field\_widget\_form() to define a custom widget. There are several good tutorials on hook\_field\_widget\_form out there, here's one I found quite useful, and the Form API Reference will help too. You might also want to look at Autocomplete Deluxe as a possible base.
2. You could create a Views table with autocomplete exposed filters, and some custom javascipt that binds a click event to each row controlling the form element, and you could use the 'Node edit' override in Ctools page manager to customise the form page and add it in. If you want one autocomplete box to filter both 'Name' and 'Synonyms', you might need some custom javascript again: maybe hide one input box and control its input with a jquery keyup event on the other box, and set the contextual filters to 'Or' in Views

Of these I'd recommend the first way - much cleaner and probably less work!

---
Tags: 7, taxonomy-terms, ajax
---


# Question
Title: What is the Context column for in String Overrides module?
With Drupal 7 I have the String Overrides module and there's a coulmn called "Context." I was wondering what this is for?

I was thinking maybe I could type in something like 'user/*' and the string replacement would occur only on 'user/*' pages?

# Answer
Currently, not much!

It appears to mostly be for D8.

http://drupal.org/node/1477568
> 4 votes

---
Tags: 7, string-overrides
---


# Question
Title: Render Profile2 field out of Profile2 page
Is it possible to render one of Profile2 fields elswhere on the page, in some node ?

I would like to present user with opportunity to edit only one field on custom link or node.

Thanks

# Answer
> 7 votes
**Retrieve Profile2 Profile Data Programmatically**

* Implement profile2\_by\_uid\_load() to get the data.

$profile2\_data = profile2\_by\_uid\_load($user-\>uid, 'profile\_id');

$profile2\_data will be an object containing all the data from profile\_id for the requested user.

---

**Retrieve Profile2 Edit Form Programmatically**

```
module_load_include('inc', 'profile2_page', 'profile2_page');
$profile2 = profile2_by_uid_load($user->uid, 'profile_id');   // profile_id = machine name
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit');
return $entity_form;

```

---
Tags: users
---


title: Dynamic View for Car

text:
# Question
Title: Dynamic View for Car
I have made a view that contains only car manufacturer logos.

What I want is that when a user clicks on a logo they will be taken to a page that will display all cars for this manufacturer (in a view), depending on a link or something.

How to make this or to assign some arguments and where?

# Answer
> 1 votes
**The Views Module and Contextual Filters**

I believe the Views module can accomplish all of your requirements.

Contextual filters will allow you to feed arguments into View using URL components. You can customize your URL's using Views re-writing features.

---

**Video Tutorials:**

Check out Johan Falk's video series called "Taming The Beast: learning Views With NodOne"

Video 17 will show you how to rewrite field output so you can build the proper links.

Videos 19-24 should cover most of what you need regarding Contextual Filters.

# Answer
> 0 votes
Try adding the link to the view with arguments using the Field Redirection module. Here is a quote about it (from the module's project page):

> A Drupal 7 field formatter for Link, Node Reference & User Reference, Term Reference (as of v2.4) and EntityReference (as of v2.4) fields that will perform a HTTP redirect to the given URL, node, user, term or entity object page. A field settings widget is provided to allow selection of the appropriate HTTP status code.
>
> The recommended usage is to create a custom display setting for the "Full content", pick one of the redirect status codes above, e.g. 301, and hide all other fields to reduce processing & load time.

---
Tags: views
---


title: Drupal Quiz Module for retake exam

text:
# Question
Title: Drupal Quiz Module for retake exam
I am trying to implement Quiz module in Drupal 6

The quiz scores will be tied to their accounts, with the ability to retake a quiz if permission is granted by Admin. How can I do this?

Also someone should not be able to advance to the next video unless they have scored a high enough score on the quiz or they have a password to open the next video.

Does anyone have any ideas?

# Answer
> 1 votes
You can look at the Quiz module. It also has an active Drupal Group :)

> The Quiz module provides tools for authoring and administering quizzes through Drupal. A quiz is given as a series of questions, with only one question appearing per page. Scores are then stored in the database.
>
> This module provides tools for
>
> 1. Online courses (Audio and Video enabled)
> 2. Self-learning programs
> 3. Training programs
> 4. Supplementary classroom activites

---
Tags: views, quiz
---


title: Cv website development problems

text:
# Question
Title: Cv website development problems
I am trying to achieve something like this http://www.vooshthemes.com/gallery/jamba/ in Drupal. Its a CV website, what confuses me is how to deal with fields. If u visit the link i provided above u'll see Experience, Expertise,Education and Training Category in which u can mention from which year to which year u worked where and what was you task.

My problem is how do i enable the user to add more fields just like in the Cv example page?? i will be using Drupal 7. any suggestion will be apppreciated.

# Answer
There are a number of ways you could do it, depending on how friendly you want the ui to be and how comfortable you are customising drupal.

I would look at the Field Collection module - http://drupal.org/project/field\_collection. It should let you create a group of fields that can be treated as a single field.

ie you could create an 'Experience' field collection consisting of Title, Experience, Duration, Summary and whatever else you need. Then the end user should be able to add multiples of these if you set the field to allow multiple values.

I am saying should because I haven't directly used this module myself, in a similar situation I have created a custom form widget containing the multiple elements. Thats is potentially a more complicated exercise. You could see an example of what might be required there in the Examples for Developers module : http://drupal.org/project/examples
> 2 votes

---
Tags: entities
---


# Question
Title: How to group li element via using Drupal.behaviors?
A newbie question here.

How can I select a range of li so I can moved them inside new element?

For example:

```
<ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>

```

To be like this:

```
<ul>
  <li>
    <div class="column1">
      <ul>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
      </ul>
    </div>
  </li>
  <li>
    <div class="column2">
      <ul>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
        <li>test</li>
      </ul>
    </div>
  </li>
</ul>

```

So far I tried using Jquery:

```
(function ($) {
  Drupal.behaviors.menu = {
    attach: function (context, settings) {

    $('#navigation ul li.expanded').hover(function() {
      $(this).find('ul').css('display', 'block');
    }, function() {
      $(this).find('ul').css('display', 'none');
    });

    var $lists = $('#navigation li.expanded ul.menu');

    // Loop through all target lists.
    $lists.each(function(i, e) {
      var $list = $(e);

      //These are temporary variables.
      var $new_list = $('<ul>');
      var $list_item, $sub_list, $sub_set;

      // The number of items per column.
      var per_column = 6;

      // Calculate the amount of columns needed.
      var n = Math.ceil($list.find('li').length / per_column);

      // Loop through all columns.
      for (var i = 0; i < n; ++i) {
        // Creates the sub list for the current column.
        $sub_list = $('<ul>');

        // Gets the first set of list items from the original list and adds them to the sub list created above.
        $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);

        // Creates a new list item and adds the sub list to it.
        $list_item = $('<li>').append($sub_list);

        // Add the newly created list item to the new list.
        $new_list.append($list_item);

        // Create a div with the class 'columnX' and wrap the sub list with it.
        $sub_list.wrap('<div class="column' + (i + 1) + '"></div>');
      }

      // Replace the original list with the new one.
      $list.html($new_list.html());
    });

  };
})(jQuery);

```

The above approach generates "

But I'm having difficulty in manipulating elements via Jquery or JS. Any thoughts will be appreciated. Thanks

# Answer
This can be optimized but you should atleast get the gist of it :)

See a fiddle here: http://jsfiddle.net/XQAde/2/
Revised fiddle from new spec can be found here: http://jsfiddle.net/XQAde/3/

```
$(function() {
  // This is the list selector you want to manipulate.
  var $lists = $('.expanded .menu');

  // Loop through all target lists.
  $lists.each(function(i, e) {
    var $list = $(e);

    //These are temporary variables.
    var $new_list = $('<ul>');
    var $list_item, $sub_list, $sub_set;

    // The number of items per column.
    var per_column = 6;

    // Calculate the amount of columns needed.
    var n = Math.ceil($list.find('li').length / per_column);

    // Loop through all columns.
    for (var i = 0; i < n; ++i) {
    // Creates the sub list for the current column.
    $sub_list = $('<ul>');

    // Gets the first set of list items from the original list and adds them to the sub list created above.
    $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);

    // Creates a new list item and adds the sub list to it.
    $list_item = $('<li>').append($sub_list);

    // Add the newly created list item to the new list.
    $new_list.append($list_item);

    // Create a div with the class 'columnX' and wrap the sub list with it.
    $sub_list.wrap('<div class="column' + (i + 1) + '"></div>');
    }

    // Replace the original list with the new one.
    $list.html($new_list.html());
  });

});

```
> 1 votes

# Answer
I am not completely sure I understand what you are trying to do - I am assuming the html is some kind of Drupal menu you are trying to add some kind of dropdown/flyout action to?

I am not sure whether you want to be doing all this DOM manipulation on mouseover/mouseout either? At least I think that's what you are doing from looking at that code snippet.

Taking your html example at face value, this bit of javascript should do the job of splitting it out into 'columns':

```
var $list = $('ul'),
    $items = $('li', $list),
    column_counter = 1,
    $current_list,
    items_to_column=6;

$items.each(function(index,item){
  if (index%items_to_column==0){
    var new_column = $("<li><div class='column"+column_counter+"'><ul></ul></div></li>").appendTo($list);
    $current_list = $('ul', new_column);
    column_counter ++;
  }
  $current_list.append( $(item).detach());
});

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Give permissions to user of the same role
I'm working in a site and I've to set node permissions (edit) so that a user can edit a node that is owned by a user of the same role. If I have the role "redactor" I can edit any node that is owned by a user that as the role "redactor". Is there a module that do this?

Or I've to write a custom module?

# Answer
You can used module content access, he does that easily.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type

Or you have node access which add a tab on each node to control permission for this node (you can configure role or user) I never really used it because there's no very stable version for d7.
> 1 votes

# Answer
A simple solution could be the use of http://drupal.org/project/nodeaccess\_userreference or http://drupal.org/project/nodeaccess\_userreference

With this modules I can set programmatically, when I save the node, a user-references field to all users of a role.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Are node data stored in the render array $page?
Are node data (e.g. title, body, comments) stored somewhere in the renderable array `$page`, and converted into HTML during rendering? Or does a renderable array just contain properties that indirectly cause to load particular templates files?

Where are variables that store these values printed?

# Answer
> 1 votes
Yes, it's probably in there somewhere. However, it much easier to get the current node object (if there is any) with the menu\_get\_object() function:

```
if ($node = menu_get_object()) {
  // Do stuff with $node.
}

```

# Answer
> 1 votes
I can advice three places where you can alter node render array:

1. hook\_node\_load . Called when node is just have been loaded from DB.
2. hook\_node\_view . This hook is called after node load. (As for me this is the best place to alter node render array). You can find render array in $node-\>content.
3. After this two hooks node render array goes to themming. You can alter node in your node template file(node.tpl.php). In node tpl file variables are printed using php print. E.g.

print render($content);

# Answer
> 0 votes
yes, A render array is an associative array which conforms to the standards and data structures used in Drupal's theme rendering system. for more info check out: Render Arrays in Drupal 7

---
Tags: theming
---


title: jQuery effect after pressing button

text:
# Question
Title: jQuery effect after pressing button
Drupal 6. I try to add jquerry effect after pressing button

```
$(function(){
    $('.node-add-to-cart').click(function() {
      $(".prod-pic").effect("transfer", { to: $("#block-uc_cart-0") }, 1000);
    });
});

```

But I get error object# has no method 'effect'. I created a custom js file with this code and put a link to the template.php using drupal\_add\_js. According to status report Jquerry UI 1.6 is installed. However, when inspecting html code, among scripts there is no jquery.ui loaded. Should I call it from my custom js file?

# Answer
Drupal 6 version of JQuery is 1.26 and after install jquery\_update it will be updrade to 1.3.2

If you want persist use jquery method likes `effect` maybe this article,but I think you can't using jquery 1.6 or upper in Drupal 6 .( I don't told you it's impossible but achieve this job is more struggle and maybe cause problem in other part of your site ).

maybe this question be helpful for you.
> 1 votes

---
Tags: javascript
---


title: Use date as Views Contextual filters

text:
# Question
Title: Use date as Views Contextual filters
I need to retrieve all nodes where updated date is between date A and date B. I had a look at contextual filters and they seem to allow only the equality operator (SELECT where date = X) whereas I need greater than and lower than operators (SELECT where date \> X).

Any idea to achieve this? Any help would be much appreciated. Thanks!

# Answer
No need adition module but date module.
go to your views add a `filter` with type `date` choose `Date: Date (node_revision)` pass `Configure extra settings for filter criterion Date: Date (node_revision)` with your optionals ,and in `Configure filter criterion: Date: Date (node_revision)` select **Is between** option.
If you want expose your filter check `Expose this filter to visitors, to allow them to change it`
> 1 votes

# Answer
you could use this sandbox project views arguments in filter. It permit to use arguments in filter criteria and then all the operators of the filter criteria with the arguments of contextual filter.

You can read the post below wich discuss about this (possible) evolution of views http://drupal.org/node/357082
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to combine 2 exposed filters (String and Taxonomy field)
I need to create a View with a search box for my content type; the search string has to match both title OR a CCK taxonomy field. Is there a Views module that permits to do it? I've tried http://drupal.org/project/views\_filters\_populate but it only works with 2 string fields.

# Answer
> 3 votes
Yes,by default drupal handled this. in `Filter criteria` in your views click and hold `arrow sign` beside `add`.open menu with `And/Or, Rearrange`.In this section(`Rearrange filter criteria`) you can determine gorup for your filter and criteria between your filters.

---
Tags: 7, views
---