# Question
Title: Can Drupal nodes and taxonmy be used to store "data" rather than "content"?
I'm very new to Drupal so please excuse the noobishness of this question.

After combing through the documentation and considering the flexibility of Drupal (Version 7) in defining it's own content, I find myself asking where the lines between content and data are drawn. Some insight and advice on the limitations of things like nodes, content types and taxonomy would be appreciated.

Here's a basic overview of what I'm looking to accomplish at this stage:

* I need to setup a website that will be able to keep track of a community of users that are segregated into clubs;
* Clubs will be able to offer courses to their members;
* Club members will be able to apply to take said courses;
* A history of courses a user has taken will be recorded;
* This information will be used to create reports by the administration.

My first instinct is to create separate tables for this information and handle all this through modules (WordPress being my previously relatable experience). With that said, I find myself pondering the idea if these things could be handled through nodes, content types and taxonomy.

Would this, or some variant thereof, be a **valid** use of Drupals mechanisms or would this basically be the hack & slash approach that I'll end up lamenting down the road?

# Answer
I recommend leaving the database structure to Drupal, its modules will handle all of the management process and you will not have to code anything.

Taxonomy is very flexible for creating categories. These taxonomy vocabularies can be attached to a content type. Create a new type and add fields for each applicable vocabulary. You can make assigning values to each field mandatory if you want and Drupal will enforce the requirement when new content is generated.

You will then use views to filter through all of your content and deliver custom pages. It is incredibly flexible but can take a while to learn. Check out the "Taming the Beast" video series at NodeOne.SE for an excellent video series to master views.
> 3 votes

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


# Question
Title: jQM Theme does not work properly on front page
I've started to use Drupal recently, and installed the jQuery Mobile module and the jQM Theme in order to make a Mobile site / Web app.

I'm having some troubles getting it to work properly.

The thing is, that when I go to my sites front page, I get this view:

However, if I click on, let's say 'Store Locator', I get this view:

So my problem is, that it seems like the jQuery Mobile stuff (js or css) does not load correctly on the front page.

If I inspect the page, it seems to be the right template, but somehow the js og css isn't loaded correctly.

Has anyone had the same problem?

# Answer
Are you including the CSS/JS via your themes .info file? If so, the CSS/JS should be included in the order specified there. The only other thing you should check is that if you have a page override for the homepage (page-front.tpl.php) and verify you have the correct JS/CSS in place in there as well. Good luck
> 1 votes

---
Tags: 7, javascript, theming
---


# Question
Title: How to put a custom login menu in a page?
I'm totally new to Drupal and I'm using v.6.xx.

I've managed to remove the "login" menu via Admin panel.

Now I'd like to create a custom "page" (= no menu) with a customized login form, and once authentified, show a menu with some options and the "disconnect" option.

What is the best way to achieve this?

Thank you very much

# Answer
> 1 votes
ok your question has several parts:

(The standard login form can be accessed through a block, or going to the /user path while logged out)

Custom login form:

Custom 'menu':

* Create a block that has a link to /logout, going to that path will automatically log out your users. Make sure that the block visibility is only for authenticated users.
* Add any other links or options you want.

---
Tags: 6, routes
---


# Question
Title: Hierarchical menu of all Terms of a Vocabulary & Contents of the Terms
I have `Category` *vocabulary* under which there are several *terms*, i.e `Tabs, Smartphones, Cellphones, Umbrellas`. There may me one or more *contents* of custom type under each of these *terms* **(A content could be linked with one term only)**. I want to generate a menu (automatically, if possible) like this:

Now I've installed `Taxonomy Menu` module which allows to generate menu with one level hierarchy only (with only *terms* of a *vocabulary*, but no *contents* of the terms).

Is there a pretty solution of my problem? Thanks for caring :)

# Answer
> 1 votes
I think this is just a straightforward menu - nothing automatic needed. When you add a new node, just choose it's parent menu item.

# Answer
> 0 votes
Here's a module I found that comes with its own caveat: "...if incorrectly configured it could create thousands of menu items."

http://drupal.org/project/views\_build\_menu

# Answer
> 0 votes
What kind of menu block are you using to display the menu? You may need something like the nice menus module to display the hierarchy. I have generated taxonomy menus of three levels using Taxonomy Menu.

---
Tags: 7, taxonomy-terms, routes
---


title: Access node fields in hook_node_grants

text:
# Question
Title: Access node fields in hook_node_grants
In `hook_node_grants()` I want to check if user ID is equal to a node's field value, But there is only two arguments: *$account* and *$op*

How can I access the node object that is being checked for grants?

# Answer
> 0 votes
A better approach to this would be to implement hook\_node\_api that checks the current $user's permissions to the loaded field then does something.

```
function custom_module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  //get the current user
  global $user;

  switch ($op) {
    case 'load':
      //do some logic with $node and with the current $user's roles
    break;

    //(optional)add other cases for other operations

    default:
    break;
  }
}

```

alternatively you can try template\_preprocess\_node

```
function theme_name_preprocess_node(&$variables) {
  global $user;
  $node = $variables['node'];

  //do some stuff with $node and $user
}

```

---
Tags: 6, users
---


title: File upload field in CCK field settings

text:
# Question
Title: File upload field in CCK field settings
Is there a difference in Drupal 7 to add a file-upload field on a "normal" form (i.e. a separate page for a modules' configuration) as opposed to the small settings area for a CCK field (the one that appears after clicking on the cog for the field you'd like to modify under the "Manage Display" tab)?

I have a bunch of configuration options for a custom field using hook\_field\_formatter\_settings\_form, but am stuck at trying to figure out how to create a file upload field. I'd ideally like to have the user able to browse for an image and upload it without having the page reload. This is all I currently have:

```
$element['custom_field_name']['image'] = array(
    '#type' => 'file',
    '#size' => 48,
    '#title' => t('Image upload'),
    '#description' => t("Upload an image."),
);

```

If it is possible to have a file upload field (that uses ajax) in this area, what else must I do?

**Edit**:

My file field now looks like this:

```
$element['custom_field_name']['image'] = array(
    '#type' => 'managed_file',
    '#title' => t('Image upload'),
    '#upload_validators' => array(
      'file_validate_extensions' => array(0 => 'png jpg jpeg gif'),
      'file_validate_image_resolution' => array('64x64', '10x10')
    ),
    '#upload_location' => 'public://default_images/',
    '#description' => t("Upload an image."),
);

```

This is sort of working: it allows me to upload a file and it goes to `sites/default/files/default_images`, but its only temporary. I've been going through the form api reference and it says I need to permanently save it. I am just unsure how where to put this logic. Do I add a `#process` key to my file field and call some private function? Or do I create a submit handler? The API reference doesn't go into as much detail as I'd like.

# Answer
You need to add a `FILE_STATUS_PERMANENT` to the status of the file on form submit then save the file.

```
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

```
> 1 votes

---
Tags: 7, entities, files
---


# Question
Title: Pass URL alias info to default value of Webform field
I'm running the Storm (project management) module and for each task, the user needs to fill out a form regarding information about the task, including uploading images about certain information captured in the form. I'm trying to pass the url alias from the task page to the default value of a field I created in webform. My current URL's look like this: `?q=content/82245940-initial-services` . My problem (well, at least my first problem) is that I use the `%get[q]` but get `node/5` as the default value. I don't understand and know enough about PHP programming yet, to know how to fix this so that I get `82245940-initial-services` as the default value instead. Any help is much appreciated for the noobie. Thanks in advance!

**EDIT** By the way I have read these posts that while I have found helpful to understand the general concept, the details are over my head:

http://drupal.org/node/296453#webform-url-default

http://drupal.org/node/228622

So, I've tried, I just don't know enough yet!

# Answer
> 1 votes
You can get the URI with `$_SERVER["REQUEST_URI"]` and remove the "q=content/" string from it.

---
Tags: webforms, path-aliases
---


# Question
Title: Alter appearance of content types in teaser view through code?
What I would like to accomplish is the following:

When a list of a certain content type is displayed, I would like an "edit" link to be placed at the end of the summary text that, when clicked, would take the user to the node edit page for that particular node.

This list would either be created using the Views module, or through a taxonomy. That part isn't important.

How can I do this through custom module code? I'm trying to learn more about writing modules on my own, and would prefer to avoid using an already built module in this particular case, since I will already be creating the content type in question through a module anyway.

Would I do this through module code, or through theme code?

# Answer
The best example of this I can think of is the Read More module which adds a "read more" link to the end of the body teaser (in teaser mode obviously).

The idea is to use the node view hooks and teaser build mode to target what and when you want to edit.

For Drupal 7 you can look at the read\_more module source for an example.
For Drupal 6 you can look at the ed\_readmore module source for an example.
> 2 votes

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


# Question
Title: Adding rating and commenting to individual fields
I have a node with a CCK field file upload, which is using the image widget. This node can have multiple images uploaded to it.

How can I add fivestar rating (or something similar), and comment to these individual pictures? How could I do it with other fields in general?

# Answer
> 5 votes
The best way to solve this would be to use the Field Collection module. All you would need to do is create a field collection with a rating and an image in it, and every time a new image is added, there would be a new rating next to it. The latest D7 version has come a long way and should work for what you need.

# Answer
> 0 votes
I am not aware of the proper way. I would add a rating field also along with the field you are talking about. So enable it to be rated only when viewing the node.

---
Tags: rating
---


# Question
Title: D7: Newsletter type project.The articles are grouped in a set (newsletter) published on a regular basis
My project is as follows:

News will be published like printed news letters meaning that no ongoing updating&publishing but clear intervals (in other words the articles need to be grouped together on the criteria of issue..issue January, issue February etc... At the moment plan is that publishing interval would be a few months.

What modules and approach would you choose for this? I know prosepoint can do this...but is no longer free and I need to make it in Drupal.

I need to dismiss the confusion with simplenews module. The newsletter doesn't need to be delivered by email (tough this would be one functionality) but displayed on the website.

Regards

# Answer
I think I found a solution. There might be others but **node referencing** a good one.

Need to create 2 content types: one for issue and one for issue article. The issue article needs to have a reference field where to assign it to a specific issue. There are no date fields for articles but there are for issues.

I think the module **Reference** (former Node reference in D6) do that in Field UI. There you can assign a reference node field to the article content type to specify which issue it belongs.

Other module Node Reference URL Widget could be useful.

Also the articles need to be grouped as well using taxonomy. This helps also building the menu system.
> 0 votes

# Answer
IMHO if your newsletter isn't meant to be emailed, the easier solution is using views with a filter on the date of nodes + a module that gives you the pdf display, like Views\_PDF.

Then if you want to send your issues by mail, you may extend with Views pdf mime mail to attach the exact pdf to your mails, but it's still under development and I'm not sure if it works. Please consider than whenever you talk about email newsletters, probably the most complete solution is still Simplenews and its submodules. If I were you, I would use Simplenews Scheduler \+ Insert view, like I did in a similar situation \[D6\].

Hope it helps
> 0 votes

---
Tags: views
---


title: Build menu like this in drupal 7

text:
# Question
Title: Build menu like this in drupal 7
I have always been working on drop down menus which nice menus or sucker fish menus was satisfying. I have a new kind of menus to be satisfied. As show in the image. When destination is hovered its should bring out drop down in that manner.

# Answer
> 0 votes
The Megamenu module looks very promising (especially with JohnAlbin on board) but unfortunately there is no stable D7 version yet. You could try the development version though.

# Answer
> 2 votes
I would use the Superfish module (http://drupal.org/project/superfish), recently this has added an option for megamenu which will allow you to build a display much like your screenshot. You will need to tweak the css to get the display how you would like it.

Demo: http://mehrpadin.net/demo/superfish/ (hover over "products" in the very bottom menu)

---
Tags: 7, routes, navigation
---


# Question
Title: Why is this code to programmatically create a content type failing?
```
<?php

            function news_article_install() {

                // Define node type
                $news_article = array(
                    'type' => 'news_article',
                    'name' => 'News Article',
                    'base' => 'node_content',
                    'description' => 'A news article content type',
                    'body_label' => 'Article Text',
                    'custom' => 1,
                    'title' =>  1,
                    'title_label'   =>  'Headline'
                );

                // Save content type
                $news_article = node_type_set_defaults($news_article);
                node_type_save($news_article);
                node_add_body_field($news_article);
            }

?>

```

Edit: I've simplified the function as much as possible, still having errors. The errors now are...

```
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).
Warning: Cannot use a scalar value as an array in _node_types_build() (line 689 of /Users/ryan/Sites/Drupal/modules/node/node.module).

```

# Answer
You have `node_type_save` and `node_add_body_field` in the wrong order. You can always steal ideas from http://api.drupal.org/api/drupal/profiles--standard--standard.install/function/standard\_install/7
> 2 votes

---
Tags: nodes
---


title: Theming Image fields in page.tpl.php

text:
# Question
Title: Theming Image fields in page.tpl.php
I need to have have something like this:

```
<div class="gal-wrapper">
   <div class="gallery" id="r1"><img src="image01.jpg"></div>
   <div class="gallery" id="r2"><img src="image02.jpg"></div>
   <div class="gallery" id="r3"><img src="image03.jpg"></div>
   <div class="gallery" id="r4"><img src="image04.jpg"></div>....
</div>

```

My CCK Image field name is filed\_image. In page.tpl.php I have the following code:

```
<div class="gal-wrapper">
    <?php foreach ((array)$node->field_image as $item) { ?>
      <div id="" class="gallery"><?php print $item['view'] ?></div>
    <?php } ?>
</div>

```

So with this I am able to print all images form my Image Field.

**But I don't know how to dynamically change the value of id="r1", id="r2", id="r3" ....**

That value **must start from 1 and be auto increment**. For example if I have 3 images the id should be id="1", id="2", id="3" or If there are 10 images I need id from 1 to 10.

# Answer
This code should do it:

```
<div class="gal-wrapper">
    <?php foreach ((array)$node->field_image as $item_id => $item) { ?>
      <div id="<?php print $item_id+1?>" class="gallery"><?php print $item['view'] ?></div>
    <?php } ?>
</div>

```
> 4 votes

---
Tags: theming, media
---


# Question
Title: Removing part of string retrieved from $_SERVER["REQUEST_URI"] in webform default value field
I'm trying to figure out if doing this is possible. I'm not very good at php so I'm trying to avoid having to create a module or something else to do this.

What I am trying to do is this: In the default value field for a section in my webform, $\_SERVER\["REQUEST\_URI"\] to return the URL that the form is on, however, the entire URL is retrieved. (`/cms/?q=content/82245940-initial-services`) I want to cut out the non-identifying part of the URL so that I'm left with `82245940-initial-services`. Is there a way to code this into the default value field(1 line), or do I need to create special code to do this?

Something like this: `$_SERVER["REQUEST_URI"-"http://example.com/cms/?q=content"]`

# Answer
> 0 votes
If you'r working with drupal you should use drupal\_get\_path\_alias()

```
$path = drupal_get_path_alias();
$value = str_replace('content/', '', $path);

```

# Answer
> 0 votes
you could use the prepopulate module to pre-fill a form based on the URL

---
Tags: webforms
---


# Question
Title: How do I automatically approve a user account in Drupal 7 based on a rule
I would have thought that I could find the answer to this by just googling but here I am...

In Drupal 6 it appears that you could setup user access rules in core to do this. So for example approve accounts that match the rule: %@email.com, which would approve any email.com address. http://drupal.org/getting-started/6/admin/user/rules

Does anyone know how to do this in Drupal 7. I would also like to be able to automatically assign a role to the account.

Thanks for your help!

# Answer
> 4 votes
I'm pretty sure you can do that with rules in D7:

Event: "After saving a new user account".

Condition: "data comparison" on "account:mail" contains "@email.com".

Actions: "Unblock a user" and "add user role"

I personally like this tutorial by node.se.

---
Tags: 7, users
---


# Question
Title: db_query() function in a foreach cycle - only the first query is getting executed (D6)
I have a query, which I have to run in a foreach cycle.
I run the query with db\_query() function.
My code looks similar to this one (of course, this is just an example code with example values):

```
$query = '
    UPDATE mytable SET some_fields = "%s"
    WHERE
    some_fields = "%s"AND
    other_field = "%s" AND
    another_field = "%s"
    ';

foreach($blabla as $index => $value){
    $prev_value = 'these variables are set in the meantime too...';
    $other_field_value = 'blabla';
    $another_field_value = 'blablabla';

    if($this_is_my_condition){
        $query_result = db_query( $query,
            $value,
            $prev_value,
            $other_field_value,
            $another_field_value
        );

        $affected_rows = db_affected_rows();

        if( empty($query_result) or empty($affected_rows) ){
            $unsuccessful_queries[] = 'blablabla '.$index.', '.$value;
        }
    }
}

if(!empty($unsuccessful_queries)){
    $errorMsg = NULL;
    foreach($unsuccessful_queries as $index => $value){
        $errorMsg .= 'Setting '.$value.' parameter was unsuccessful!<br />'."\n";
    }
    throw new ParameterSettingException($errorMsg);
}

```

In theory, my query is OK, because it works for just one query perfectly with the same values (if it has to be run depending on my condition ( in the example above, $this\_is\_my\_condition ) ), BUT it doesn't work for multiple queries, the rest of the queries are getting simply ignored: my $unsuccessful\_queries array is full of the other to-be-updated stuffs that would have to be executed.
The values are correct (that's for sure, because these work with the same values, but with just ONE query!!).

What can be the source of the problem? Why can I run only ONE query, why are the others getting ignored?

Thanks in advance!

# Answer
Finally I found the solution. The reason of the problem was a stupid mistake.
Shortly: using `var_export` to convert a boolean value to string (`false` ==\> `"false"`) in every cycle step, and giving its each time converted return result to the `db_query` function as a parameter.

Longer explained:
There is an enum field in my own MySQL table, which looks like this:

```
`is_own` enum('true','false')

```

So `true` or `false` values were stored as a string, this way there were only these two possible values to set. It could have also been set as `0` or `1` (or `enum('0', '1')` is another possible solution), but this way I thought it will be simpler to read later, and I limited the opportunities to just two values.
To pass a boolean value to `db_query()`, firstly I had to convert it to a string, so for example **the `false` value (as a boolean) had to be converted to `"false"` (as a string), not to be casted later to `0`** (because if it's casted, the update doesn't affect any rows, since for example `'false'` (as a string) isn't equal to `0` in a MySQL-query). To do this, I used the following code snippet (**using var\_export**):

```
$is_own = false;

$is_own = var_export($is_own, true);

```

This normally works perfectly (so it converts boolean `true` to string `"true"`), BUT the problem was that for some stupid reason I put this conversion in the cycle like this:

```
$is_own = false;

// ....

foreach($blabla as $index => $value){

    // here's the mistake...!
    $is_own = var_export($is_own, true);

    // ....
    $query_result = db_query( $query,
        $value,
        $prev_value,
        $other_field_value,
        $is_own // <--- !!
    );
    // ....
}

```

so this way `$is_own` variable's value (false) was converted in every cycle step like this:

```
1. 'false'
2. '\'false\''
3. '\'\\\'false\\\'\''
4. '\'\\\'\\\\\\\'false\\\\\\\'\\\'\''
5. etc........

```

This way it's not a miracle that all of my UPDATE querys were executed successfully, but only the first resulted in some affected rows...
After some headbanging, I put my `var_export` function outside the cycle (before `foreach`), and now everything works perfectly. (This would be a bigger job to modify the field to INT values (0, 1), so I leave it this way.)

Anyway, thanks.
> 0 votes

# Answer
I'm not sure if checking the return of `$query_result` against `empty()` is meaningful, since the only indication query failed is if it returns `FALSE`. Same for `$affected_rows`, since the query may be successful but not necessary change any rows.

I'd suggest installing Devel module because it has a feature which records and prints all DB queries on a page load. This would enable you to see the actual query(ies).
> 0 votes

---
Tags: 6, database
---


# Question
Title: Run hook_nodeapi("pre save") but only on inserts, not on updates
For `hook_nodeapi()`, I want it to run on "presave," but only on inserts, not on updates. How can I do that?

# Answer
> 3 votes
You can know if it an update or insert by looking the `$node->nid` value. If you've a number it's an update otherwise an insert.

You can see an example directly on the documentation.

---
Tags: 6, hooks
---


# Question
Title: A module similar to Innovation News Module for Drupal7?
Hello I am looking for a module similar to Innovation News so that news content can be developed collaboratively, placed into editions, and exported as XML documents.

It seems Innovation News is on a dead line.

Anyone could help me?

# Answer
> 1 votes
I think you can easily replace this module by a bunch of other module and that maybe the reason why the module is not anymore maintained. I will try to give you some clues to archive your goal, but maybe you need code a bit.

* Flag \- Flag allows you to associate content to an edition.
* Views \- Flag work with views, that allows you create views for each edition
* Views Bulk Operations \- With Views and VBO you can easily create control panel for each edition.

I hope this can help you.

---
Tags: 7
---


# Question
Title: Custom PHP code in Rules differs from Devel's one
I'm facing an issue which is quite boring since the result displayed into Devel's PHP executer differs from the results of the Custom PHP code. What I want to do is sending private messages (thanks to privatemsg module) to certain users that I can't select with privatemsg Rules integration.

To send a new private\_msg, we have to use the function "`privatemsg_new_thread($recipients, $subject, $body)`".

So I have to write a custom PHP code which is (I made it very simple) ; this one works in Devel but not in Rules.

```
$recipients = array(user_load(1));
$subject = 'hello';
$body = 'ok';
privatemsg_new_thread($recipients, $subject, $body);

```

When i write this ; it works with both modules

```
privatemsg_new_thread(array(user_load(1)), 'hello', 'ok');

```

Is there a problem with loading variables or sth ? And i don't have any error log...

Any help would be highly appreciated !

Thanks in advance

# Answer
> 0 votes
I have finally suceeded by deleting and creating a new rule with the same PHP code ; I guess there must be a bug in there !

---
Tags: 6, rules, debugging
---


# Question
Title: Create a content node from another content
I'm wondering how to create a content from another content. I'll give an example, it will be easier to understand :

We have a content-type "Planning" which has three fields : 2 user references and one date, which can be multiple filled (let's say the dates are appointments). So in result, a planning will link 2 users and this node will display all the dates these 2 are supposed to meet.

Also, we have another content-type "Appointment".

I'd like that after the creation of the Planning, the appointments get automatically created, always linking the 2users.

First, I've looked into the module Flexi-Field but it doesn't create the node. Then I thought about Rules but I don't know how to create the multiple nodes Appointments due to the multiple date fields.

I know I could do it with Rules through a PHP custom code, but if there's any easier solution, I'd like to hear about them :-)

Thanks for any suggestion !

Cheers all !

# Answer
If both your content types are defined for Plannning and Appointment already, you can easily create appoint nodes on-the-fly when a Planning node is saved.

You want to look at the following 2 references:

It would look something like this (NOT TESTED):

```
function mymodule_node_insert($node) {
  if ($node->type == 'planning') {
    foreach (element_children($node->field_appointment_dates) as $a_single_appointment_date) {
      $appt_node = new stdClass();
      $appt_node->type = 'appointment';
      node_object_prepare($appt_node);
      $appt_node->language = LANGUAGE_NONE; // Or your language type ...
      $appt_node->title = 'Some new appointment';
      $appt_node->field_appointment_date = $a_single_appointment_date[0]['value'];
      node_save($appt_node);
    }
  }
}

```
> 3 votes

# Answer
```
function planning_nodeapi(&$node, $op) {
    if ($node->type == 'planning' && $op=='insert') {
    $txt = $node->field_plan_texte[0]['value']; // some text
    $user = $node->field_plan_user[0]['uid']; //user reference
    $date = $node->field_plan_dates[0]['value']; // date of appointments, even if multiples
    for ($i=0;$i<count($node->field_dates);$i++){
       $appt = new StdClass();
       $appt->type = 'appointment';
       $appt->uid = 1;
       $appt->title = "pd";
       $appt->field_appt_txt[0]['value']=$txt;
       $appt->field_appt_user[0]['uid'] = $user;
       $appt->field_appt_date[0]['value'] = $node->field_dates[$i]['value'];
       node_save($appt);
    }
  }
}

```

This is valid for D6 ;-) Thanks @ tenken !
> 1 votes

---
Tags: nodes, 6, rules
---


# Question
Title: References by title (not nid) while creating nodes via PHP code
does anyone know how to create node reference while creating node programmatically? I mean - using TITLE and TYPE, not nid.

I am creating nodes via python script and user is prompted for title of parent node. Nobody's gonna tell you NID in that case. But content type and part of title should be enough.

If there is no way of doing that in Drupal - I am gonna make my own function to fetch all nodes that fits criteria and go further if there's only one or prompt for choosing proper one if there's more than one..

I'll be happy if there's already something that handles my task.. :)

My current code with doing that by NID:

```
    $n = new stdClass();
    $n->type="project_release";
    node_object_prepare($n);
    $n->title = "Kaboom [".date(YmdHis)."]";
    $n->language = LANGUAGE_NONE;
    $n->uid = 1;
    $n->body[$n->language][0]['value']="12345";
    $n->body[$n->language][0]['summary']="123457890";
    $n->body[$n->language][0]['format']="filtered_html";

    $n->field_release_project[$n->language][0]['nid']=85;
    $n->field_project_release_notes[$n->language][0]['value']='AaAAAAAA...';

    $path = 'remotely_added_at_'.date('YmdHis');
    $n->path = array('alias'=>$path);
    if($n=node_submit($n)) {
        node_save($n);
        echo "</br>Node with nid ".$n->nid." saved\n";
    }

```

Cheers

# Answer
The only option you have is querying the node table to fetch the node id and re-ask if there are multiple matches yourself.
> 1 votes

# Answer
I don't think that you need to write your own function, just have a look at node\_reference\_autocomplete\_value(), this functions does exactly what you need (match Node Title to nid)
> 3 votes

---
Tags: entities, nodes
---


# Question
Title: Does hook_node_access_records() and hook_node_grants() change permissions for existing nodes?
When I install a new module containing `hook_node_access_records()` and `hook_node_grants()`, Does it change permissions for existing nodes? Or it affects only on new nodes?

If it doesn't change permissions for existing nodes, Is there a way to rebuild node\_access table?

# Answer
You can implement hook\_enable() and call node\_access\_needs\_rebuild(TRUE), see user\_relationship\_node\_access\_enable() for an example.

That doesn't actually do much on its own, but Drupal will then automatically print a message to administrators and inform them that the permissions need to be rebuild and also includes a link to the place where this can be done.
> 3 votes

# Answer
I don't know if it affect the old node, but I think no. If you need to rebuild the access, can go in Content management -\> Post settings and you'll see a form to allow you rebuild permissions.
> 1 votes

---
Tags: 6, users
---


# Question
Title: 3 columns with main content in front page
I am very new in Drupal and therefore I need your help please.

I would like to have 3 columns in my front page for the main content. Let's say the columns are: NEWS, EVENT and SPOTLIGHT.

When I create an article, I would like to be able to choose in which column I am going to publish the article. I need also to be able to theme the columns... How can I do this?

thank you.

Gilles

# Answer
> 3 votes
Panels module would help you in this regard. In Panels you can place nodes, views blocks, general blocks. All these things can be themed independently.

Panels are themselves nodes and blocks(mini panels).

---
Tags: theming
---


title: Posting to a Drupal Form via HTML page

text:
# Question
Title: Posting to a Drupal Form via HTML page
I have created a plain HTML page. I want that the when ever a submit button is clicked, It submits the values to a form that is present on a drupal Site. Its a simple form with only text field. Any idea ?

# Answer
> 6 votes
A form directly can not be posted to Drupal. But a general callback can receive post request data and can process it to store it somewhere.

For this, a `hook_menu` entry is required to register a callback with a newly created URL . This callback can access $\_POST.

On the other hand post request to Drupal can be invoked with form data either by CURL or jQuery.ajax()

Your custom module:

```
function hook_menu(){
  return array(
     'path/to/submit/post/values' => array(
        'title' => 'Catch Post Data',
        'access arguments' => array('access content'),
        'page callback' => 'catch_post_data',
        'type' => MENU_CALLBACK,
     )
  );
}

function catch_post_data(){
   $values = $_POST;
   // Get post values and store where you like.
   // Do not break the system. Do it carefully using proper entity functions.
   if($success)
       drupal_json(array('status' => 'SUCCESS'));
   else
       drupal_json(array('status' => 'FAILURE'));
}

```

Form can be posted via jQuery.

```
$.post('path/to/submit/post/values', $('#form').serialize(), function(response){
    response = $.parseJSON(response);
    if(response.status == 'SUCCESS')
        alert('Congrats!');
    else
        alert('Something went wrong');
});

```

# Answer
> 3 votes
if your form is very simple you might be able to use the prepopulate module. For example the URL to prefill a title on a blog is:

```
    http://www.example.com/node/add/blog?edit[title]=this is the title

```

Your form would submit with the "get" method to:

```
http://www.example.com/node/add/blog

```

if your form field name is "edit\[title\]" this should work.

# Answer
> 1 votes
For some security and internal process it seems pretty difficult to do it, or even impossible. You must replicate the exactly HTML form Drupal produces.
The main problem is Drupal cache, how Drupal produces a form, and the tokens Drupal adds to be sure it doesn't receive forget data, but data really submitted from a human being using a Drupal form.

I think that you've to use a proxy or create the form directly with Drupal.

---
Tags: webforms, theming
---


# Question
Title: Hide user pictures from guests and web crawlers
I'm using Drupal 7 with Blog and Comments and user pictures enabled. The theme is Bartik.

The user pictures are also used in the Flash game that is embedded in my website, so I can't just turn them off.

I'm looking for a way to hide user avatars from guests and web crawlers.

*The background is that I've gotten a bill for EUR 1000,- from Getty Images, because one of the users has supposedly used their picture as avatar. I'm not looking for any lawyer or pseudo-lawyer advices here, just for the way to hide user pictures from web crawlers.*

I've tried searching in the theme file for picture and bartik\_preprocess, but haven't find any hints yet:

```
# grep -r bartik_preprocess .
./themes/bartik/template.php:function bartik_preprocess_html(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_maintenance_page(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_node(&$variables) {
./themes/bartik/template.php:function bartik_preprocess_block(&$variables) {

```

and **print\_r($variables);** in the above functions does not contain a "picture".

Also I've tried setting **$account-\>picture = NULL;** in the **hook\_user\_view($account, $view\_mode, $langcode)** hook, but then the picture is hidden for everyone including registered users and also this is for user profiles only, not for blog comments.

# Answer
> 2 votes
None of the core themes have all the preprocess functions or template file in use. The best way to find what's available to use is with the devel\_themer module.

Here's what `devel_themer` gave me:

This says we can use `template_preprocess_user_image()` or `user-picture.tpl.php`. When doing logic such as this, it's standard to use preprocess functions. When you're changing HTML structure you use template files.

So you can add the following function to your theme and it should hide all user pictures for anonymous users (web scrapers are considered anonymous users).

```
function YOURTHEME_preprocess_user_picture(&$variables) {
  // this is the currently logged in user
  $user = $variables['user'];

  // this is the user the picture belongs to
  $account = $variables['account'];

  // If the current user is anonymous don't show the user picture
  if ($user->uid == 0) {
    $variables['user_picture'] = NULL;
  }
}

```

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


# Question
Title: How could I create an iframe page like this in Drupal?
I want one of my content type pages to look like this http://flippa.com/auctions/2647380/site The data at the top would be filled by cck fields from that content type. How could I do this?

# Answer
Add a field for URL, and then in your theme spit out the URL field value as an IFRAME tag.
> 2 votes

---
Tags: 7
---


# Question
Title: Getting the display value for a form option with webform 3.x while processing submissions
I want to create an associative array of submitted form data and do some additional processing on the submitted data (namely send the data over http POST). I have the following code:

```
function webformssalesforce_form_alter(&$form, &$form_state, $form_id) {
    if (substr($form_id, 0, 20) == 'webform_client_form_') {
        // Add the submit handler after the existing Webform submit handler,
        // but before the second Webform handler. Pop off the first one and add
        // ours second.
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'webformssalesforce_client_submit');
      }

}

function webformssalesforce_client_submit($form, &$form_state) {
    $node = node_load($form_state['values']['details']['nid']);

    $fields =  Array();
    foreach($form_state["values"]["submitted_tree"] as $key=>$value) {
        if(! is_array ( $value)){
            $fields[$key] = $value;
        }
    }

    //do stuff with $fields

}

```

This works fine for text and email fields, however for select elements I get the option's safe\_value instead of the display value for the select. So for example if an element has the folowing options:

```
1|Display value 1
2|Display value 2
3|Display value 3

```

How can I get the display value instead of the safe\_value (Display value 2 instead of 2) for an element?

I'm pretty sure this code worked fine for me with a previous version of webform.

# Answer
I've run into the same issue, could not find a predefined function and ended up writing one that loops over the select options in the text area and returns an associative array.

The basic principle is described in this article: http://blog.raisedeyebrow.com/2009/01/displaying-webform-results-in-a-block/

For my project I used the webform\_submission\_insert hook instead of form\_alter, but I hope it works for the variables that you have available in form\_alter as well.

If it is likely that you'll need this feature more often you may want to use a function to extract the data for any textarea using the same principle.

```
function mymodule_webform_submission_insert($node, $submission) {

   switch ($node->title) {

    case "Test form":

    $options = array();

    // fill options field with options from select textarea via custom function;
    // field number of my particular webform select field is 12, hence:
    $options = _extract_select_options ($node->webform['components'][12]['extra']['items']);

    // output key and value of chosen select option
    $chosen = $options[$submission->data[12]['value'][0]]);
    drupal_set_message ("key / value: ".$submission->data[12]['value'][0]." / ".$chosen;

    break;
   }
}

// declare function with text area content as parameter
function _extract_select_options ($mytext) {

    $options = $pairs = $temp_array = array();

    // split text into chunks after each line-break;
    // if not visible here, use "backslash n" as explode parameter
    $pairs = explode("\n", $mytext);

    // split each line into pairs of key and value
    foreach($pairs as $pair) {
      $temp_array = explode('|', $pair);
      $options[trim($temp_array[0])] = $temp_array[1];
    }

    return $options;

}

```
> 2 votes

---
Tags: 7, forms, webforms
---


# Question
Title: What steps do I need to take to use Drush Make on a Windows machine?
I have the Drush Windows installer. I download the Drush Make module and put it in the drush\commands folder. Still I don't have any luck with Drush Make on Windows.

# Answer
> 0 votes
I found the solution on this page. There were several steps but it really wasn't that difficult. For some reason it doesn't download items from Github but that might be something to do with the path variable not being set correctly and I just downloaded a few modules from Github manually.

---
Tags: drush
---


title: Rearrange filters option missing?

text:
# Question
Title: Rearrange filters option missing?
How can I rearrange the weight of the exposed filters? In Drupal 6 I had that option, and in Drupal 7 it has disappeared.

Is there something I'm missing?

# Answer
> 4 votes
Select 'And/Or' next to Filter Criteria, this will show a popup where you can rearrange them.

---
Tags: 7, views
---


title: Stop account's activities for 24 hours

text:
# Question
Title: Stop account's activities for 24 hours
How can I temporarily ban an email address for up to one month?

I am using Drupal 6.

# Answer
There is the Troll module, which seems to do what you need; it isn't looked after.
For other options you also have the Cave your trolls module, which hides user's posts from anyone other than themselves, or the Misery module, which makes the site unusable for certain users.
> 1 votes

# Answer
Block the user.

1 month later, come back and unblock the user.

OR post some details about what you're specifically looking to accomplish.
> 0 votes

---
Tags: 7, users
---


title: Override registration page problem

text:
# Question
Title: Override registration page problem
I'm trying to customize the user registration page in a zen subtheme.
The template candidates files suggested by themer devel are page-user.tpl.php and page-user-register.tpl.php, but when I try to create them, page.tpl.php (placed in the subtheme as well) is not overridden.
All other pages are working fine.
I've clean theme registry and checked all file permissions, I still can't get this. What did I miss?

# Answer
If you're using D7, you'll need two dashes between page-user, not one.

Some examples
> 1 votes

---
Tags: users, theming, 7
---


# Question
Title: Help with a D7 database query and update
I am not familiar with the Drupal 7 database API. I want to alphabetized a menu.
Can anyone help me write a database query to retrieve all the menu item links of a certain parent (plid = 228) and order ascending by title? Within that result set, can anyone help me write a database update method to update each menu item's weight sequentially (counter starts at 0 and increments)?

# Answer
> 2 votes
Something like this should work, but I have not tested this code. Please comment on this if you have questions.

```
$result = db_select('menu_links', 'ml')
  ->fields('ml', 'mlid')
  ->condition('ml.plid', $plid, '=')
  ->orderBy('ml.link_title')
  ->execute();

$i=0;
foreach ($result as $row) {
  db_update('menu_links')
    ->fields(array('weight' => $i))
    ->condition('mlid', $row->mlid)
    ->execute();
  $i++;
}

```

At this point they would all be ordered by title, and you could print the menu wherever needed.

---
Tags: 7, database
---


# Question
Title: Mini pager on View in a block does not work
I have a view that is displayed on a rightside block using quicktabs.

In Quicktabs it is the third option and set up as a view (as opposed to set up as a block).

It lists authors on a blog, and has a pagination feature. The mini pagination DOES show up, it just doesn't do anything. The pagination link appears but doesn't actually effect the view in the quicktab.

I've tried changing the Views ajax feature both on and off and neither have an effect.

# Answer
> 2 votes
Okay, so this was a major undertaking, and in fact had nothing to do with using Quicktabs.

The issue was two-fold in my case. The names were being aggregated in Views using the Arguments section with a List style. THIS is what was breaking ajax pagination.

I added the development version of the 'Views Group By' module to do the aggregation instead of using the Arguments section, and that worked.

In addition, I have a module called 'Secure Pages' that was causing a 302 redirect on the ajax request. I had to white-list `/views/ajax*` to overcome this error.

Hope this helps someone in the future.

# Answer
> 2 votes
If you want pagination to work as being a block display, you will have to set `Use AJAX` to `Yes` under Basic settings in your view edit page.

In the page display Pager work as it receives parameter as query string variable `?page=1`.

---
Tags: views, 6, blocks
---


# Question
Title: Uninstalling modules doesn't remove them from modules list
If I install a module, and then uninstall it, for some reason the modules are not removed from my module list (or from my modules folder)- even after repeatedly clearing the cache. Why would this be happening?

# Answer
> 6 votes
The modules on the file system are not intended to be deleted if you uninstall them. Although I can see that the terminology may be confusing.

Uninstalling will delete any references to the module in your site (assuming the module is written to do so), but will not affect the file system in any way.

The only reference to the module will be on the modules page, it will not be used in any live pages on your site. So should be harmless, but if you don't want the module to appear on the modules page you will have to manually delete the files.

# Answer
> 2 votes
Enabling a module automatically creates module schema if this module implements hook\_schema() by invoking hook\_install() and it sets its state as active in the system.

Disabling a module just sets the module's state as inactive in the system.

Un-installing is the next step after disabling to remove database schema and configurations from the system.

Removing modules from the module list can only be achieved by removing them from modules directory.

---
Tags: 7, installation
---


# Question
Title: "Allowed memory size" errors on common tasks
I get this error all the time when I'm doing common admin tasks, such as enabling modules.

> PHP Fatal error: Allowed memory size of 33554432 bytes exhausted

How can I fix this?

# Answer
Edit your `sites/default/settings.php` file, and change the line to set the memory limit:

```
ini_set('memory_limit', '100M');

```

or increase `memory_limit` in your `php.ini` file.
> 7 votes

---
Tags: 7
---


# Question
Title: Can't access module settings (Devel module)
I have a module that's enabled and working, but the configuration options won't show.

The module in this case is Devel, which I've used on other sites with no problem. In this site, whenever I click on 'configure' in the Devel module listing, it takes me to the configuration page, but without a Devel option.

I've cleared the cache and re-enabled multiple times. The module is definitely enabled because I can use functions like `ddebug_backtrace()`.

What else can I try?

**EDIT:**

I've uninstalled and re-installed the module, and still have no luck. I need an advice on how to trouble-shoot this.

# Answer
I Think I figured out the culprit, if not the exact reason- I was getting “Allowed memory size” errors on common tasks like enabling modules, and once I remedied that my config screen showed up.

The memory error issue was addressed here.
> 1 votes

---
Tags: debugging
---


title: Printing thumbnail images in DomPDF

text:
# Question
Title: Printing thumbnail images in DomPDF
My print-friendly version replaces the thumbnail images with the hi-res versions which is fine, but the PDF version replaces the images with the alt tag.

Anyone have any ideas on how I can get the PDF varsion (DomPDF) to behave when dealing with the thumbnails?

# Answer
The problem was a setting in the admin/content/node-type/\[your node type\]/display (Display Fields settings). The "Print" tab was set to show the images, but PDF uses the "Basic" settings. Changing the "Teaser" setting to "thumbnail" fixed the problem.
> 1 votes

---
Tags: files
---


# Question
Title: How to add a custom display field to a content type in Drupal 6
Hi i am trying to add a custom field to a content type which would be un editable. And view able.

A php code to do some database access and prepare a xml file.

call a Swf animation will.

When user wants to post a content of the type he will give all the information in the form except this field, but once he submits it the info he entered will be hidden and this swf animation will show the data from xml.

Is there any way/ module which allows to add a extra display field? and module which executes a php code upon viewing the node.

# Answer
About uneditable custom field, here is a resource with several suggestions: http://drupal.org/node/1034768

about how to use a php code for pull data inside a custom cck field (If I understood well), I guess that you can build a module for use your respective code inside this module, and show the desired data inside a custom cck. This page have information related about **How to create a CCK content type and fields from a module** http://drupal.org/node/1044248

I hope information be useful
> 0 votes

---
Tags: 6
---


# Question
Title: How to invert a contextual filter which is a taxonomy term ID?
I have a view that displays a number of nodes according to a taxonomy. I do this by adding a `Contextual Filter -> Has Term ID` and to get this value from the URL to filter out all nodes related to that taxonomy.

What I need to show in a view is precisely the opposite. I need to show all nodes **except** the nodes filtered out by the contextual filter of term ID. In a way, I need to show all content **NOT** tagged with the taxonomy term in the URL.

Does anyone know how this can be done?

# Answer
> 3 votes
I haven't tested this, but at the bottom of the contextual filter form, under 'More" is a button that reads: Exclude If selected, the numbers entered for the filter will be excluded rather than limiting the view.

Have you tried this? Please follow up with a comment for your results.

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


# Question
Title: Is it possible for a site owner's user account to **ever** have a permissions issue?
I continually read posts like this:

> This may sound dumb, but have you set the proper permissions to use it? I spent a good two hours trying to figure out what I was doing wrong before realizing I hadn't checked the '\[whatever\]' box.

As a Han-Solo of D-developers, I never think of permissions, but at desperate moments when Views repeats the same imperious error, doubt creeps in. Could it be permissions?

# Answer
> 3 votes
User #1 only bypasses `user_access()`; if something runs its own access calls, and doesn't call `user_accces()`, that user won't get any special handling.

# Answer
> 1 votes
Very occasionally yes - my memory is foggy, but I think once instance is if a module doesn't properly use user\_access() to check permissions.

I like to toss Admin role onto my sites, which makes sure users with that role always have all permissions.

If you are debugging issues, Xdebug can be very helpful. /admin/reports/dblog may also help.

Finally, googling the exact error can shed some more light. Someone else has almost definitely run into it before you.

When all else fails, try the simplest possible solutions you can think of.

---
Tags: users
---


# Question
Title: Moving nodes from dev to production (a simple use case)
I want to use the **backup\_migrate** module to move some nodes from dev to production (production is still off-line). But the node is split over so many tables...and I also added custom fields (image field) to the node. How do I use backup\_migrate module to move the tables? How do I know which tables to move? Should I just move the entire db? then what would be the point of using features to export my configuration? Thank you.

# Answer
From my experience, I use Node Export to export some nodes and import in other Drupal site (same versions). To export/import a node, the respective Content type must have been created with his respective fields.

Also, this page Comparison of Content and User Import and Export Modules have information about some import/export modules alternatives (also I suggest see comments). Could be suitable for your needs.

I hope information be useful.
> 4 votes

# Answer
You should take a look at the Deploy module. It uses webservices for moving content from one Drupal instance to another (ie dev to prod). The module takes a little bit of effort to setup, but once done it works well.

Deploy is smart enough to take the dependencies with it too, so you only have to specify the nodes to deploy. Another nice feature of deploy is that you can deploy changes to a live site without wiping out the existing data.

**Note** Deploy for D7 isn't ready for production use, but the D6 version worked well last time I played with it.
> 2 votes

# Answer
Features are meant to move configuration from one db to another (like content types, comment settings, field definitions, etc). Backup\_migrate is for moving your whole database from staging to prod with content. it's your best bet for moving nodes from one DB to another.
> 0 votes

---
Tags: features
---


# Question
Title: Drupal menu management seems lacking compared to WordPress: Am I missing anything?
I'm trying to understand how to best add content links to menus. As far as I can tell, there are two limited ways:

1. In the content edit screen, click the "Provide a menu link" checkbox. **Shortcoming:** This will only add links to the main menu- you can't target other menus from the content edit interface?
2. In the menu edit screens, you can add links. **Shortcoming:** You have to spell out the paths. Seems like it would be a lot easier if there was a content finder on this screen so that you could easily select the content, a la WordPress and every other CMS.

I'm coming from WordPress, which has a basic but robust menu management system. Is Drupal just lagging in this regard? Are there better ways of handling menu links?

# Answer
1. On node edit page, upon checking "Provide a menu link" populates a select box with menus and theirs items which are associated with this content type. To include other menus you need to edit your content type.
2. You are right in this regard but there can be some module.
> 2 votes

---
Tags: 7, routes
---


# Question
Title: How can I add language selection to the user profile in "my account" settings
I'm currently allowing users to switch language with the "Language switcher" block, but I would like have this as part of the user profile that is managed with the "My Account" settings page.

Is it possible to add this as a field? Adding a field is no problem, but can I make it refer to the language setting that is normally controlled by the language switcher block? I'm using Drupal 7.

# Answer
The language setting is already present in the account settings page, I was misguided by the first part of the description "This account's default language for e-mails, ..." and skipped over the rest that read "... and preferred language for site presentation." doh!
> 1 votes

---
Tags: 7, entities, i18n-l10n, users
---


# Question
Title: Why can't Drupal write to the database after migrate/restore?
When I want to do more development on a live site, I usually make a copy of the files and database on my local LAMP install and play with it there.

Now I'm finding that if I copy the database to local using Backup and Migrate or importing/exporting with phpMyAdmin, the local Drupal can only read from the database. It displays pages, but any edits or admin changes don't get saved. No errors, just nothing changes.

I've tried clearing all caches and running update.php. I'm running the same Drupal version live and locally. If I install Drupal locally from scratch, no problems at all.

What am I missing here... or is there a better way to achieve production/live cloning?

# Answer
It was a schoolboy error on my part. I didn't have mod\_rewrite enabled on my local environment, so clean URLs weren't working.
> 2 votes

# Answer
This doesn't sound like a Drupal issue. It's more fitted for webmasters.stackexchange.com.

Make sure your user is granted all privileges. See lamphowto and ApacheMySQLPHP
> 0 votes

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


# Question
Title: Drupal Signup: how to signup to multiple events at once?
I've been looking all over the internet for this, but couldn't find anything about it. The thing is like this:

I am creating a Drupal 7 website for a training institute. On the website I am showing the trainings in a calendar with the Calendar, Views and Date modules (see also http://drupal.org/node/998334#part1 )

With the Signup module users can signup for a single training by leaving their name, address, etc. But I would like to make it possible to signup for multiple events at once. The available events should be listed on the signup page and can individually be checked. The user will then be signed up for all the selected events with only once filling in the form.

Does anybody know if there is a workaround for this?

Thanks in advance!

# Answer
Someone put together a hacky solution for "Signup" module (which is apparently similar to "CCK Signup"). Maybe it's a good starting point: http://drupal.org/node/151898.
> 1 votes

---
Tags: 7, users
---


title: Bypassing drupal cache in template file

text:
# Question
Title: Bypassing drupal cache in template file
is there a way i can bypass the drupal cache for a specific element on my website? in my case i've got 3 header graphics which should be displayed at a random order on every page load.

# Answer
> 1 votes
Using ESI, JavaScript or setting the image to a php file is how to get around the caching issue. http://drupal.org/project/esi\_api
http://drupal.org/project/esi
http://drupal.org/project/ajaxify\_regions
http://drupal.org/project/ajaxblocks
http://drupal.org/project/views\_javascript\_random
http://www.alistapart.com/articles/randomizer

# Answer
> 1 votes
The entire page is being cached, so you'll want to disable caching on those pages that have dynamic elements. I think you'd want to:

a) turn OFF page caching for the needed paths (http://drupal.org/project/cacheexclude) b) turn ON caching for any Views, blocks, or whatever else you can cache on those pages to save bandwidth

Then you'll have more granular caching control.

---
Tags: 7, theming, caching
---


# Question
Title: Drupal 7 views Contextual filters with Page & Blocks
I have an issue and i'm hoping to get some advise.

I have a view created that show content based on the url:

eg:

`domain.com/item/one`

Shows fields for my node with the title `one`

`domain.com/item/two`

Shows fields for my node with the title `two`

etc etc.

The path for the PAGE in views is set to `/item`

What I'm having trouble with is I need to have a BLOCK (becuase I'm making it collapsable) show under that page with the specific URL show the body field for that node.

eg:

`domain.com/item/three`

Shows fields for my node with the title `three` as well as a block that show the body field for node `three`

I have set the Contextual filter for the PAGE to:

```
Content: Title

When the filter value is NOT in the URL
Show "Page not found"

Exception value : Empty (All removed)

Under More:
Case : Lowercase
Case in path : Lowercase

Transform spaces to dashes in URL : Checked

```

This works for the page but please let me know if I have set this up incorrectly.

I have set the same Contextual filter for BLOCK and it works in views preview but not on the page with the URL:

`domain.com/item/three`

I also tried adding `Global: Null` Contextual filter before the `Content: Title` filter which allowed me to put `item/three` in the preview and it works (before worked with just three). This also didn't work on the actual page.

Any advise on this would be greatly appreciated.

# Answer
> 15 votes
Contextual filters works well for any display type that has a path. A path makes it easy for views to determine what information should be passed into the contextual filters.

The problem with blocks is that they don't have a path. Views does not look at the current url and automatically pass values to the filters because it has no idea which parts of the url to use.

You can get around this by using `Default Values` (or page manager/panels, but that's a whole other topic).

In the settings for your block contextual filter, you will want to override the configuration and select `Provide a default value`. Under type choose `Raw value from URL` and set the `Path component` to 2 (the path component will be different depending on your URL, but for domain.com/items/node-title the component is 2)

When you assign your block to a region, you probably want to set the allowed paths so this block won't show up anywhere else. The `path component` is "hard coded" so if your path ever changes you will need to adjust it.

---
Tags: 7, views
---


# Question
Title: Grouping nodes by common CCK values in views
I can't think of a better title than that, but hopefully it makes sense once I describe it.

I have a node type with 3 CCK fields, we'll call them A,B,C and 1,2,3 and X,Y,Z.

Some nodes will be A,1,X and others will be B,3,Z and etc.

I want to create a view which will pull all of my nodes and list each unique option set as a row so all rows that are A,1,X are in a row with the # of results, and all B,3,Z's are in a row with the # of results.

Is what I want to do possible? If so - how?

# Answer
Yes it is possible: On your view you have filters, you can filter results by A, then another view with all the results of B; then, if you want these both in a single page I'd suggest a Panels page.
> 1 votes

---
Tags: views, 6
---


# Question
Title: How do I programmatically create a simple 'page' node?
I have already found Drupal 6 documentation on how to programmatically create a page node.
How is it possible to achieve that in Drupal 7?

---

I've changed my strategy, and I'm using another approach, but I'm getting the following error:

> Fatal error: Cannot access empty property in C:\\...\\...\\...\\...\modules\field\field.attach.inc on line 198

I'm using the following code:

```
$form_state = array();
module_load_include('inc', 'node', 'node.pages');

$node = array('type' => 'page');
$form_state['values']['uid'] = 1;
$form_state['values']['name'] = 'admin';

$form_state['values']['title'] = 'Programatic Page';
$form_state['values']['language'] = 'en';

$form_state['values']['body']['en'][0]['value'] = 'My own value';
$form_state['values']['body']['en'][0]['summary'] = 'My own summary';
$form_state['values']['body']['en'][0]['format'] = 'filtered_html';

$form_state['values']['menu']['enabled'] = 1;
$form_state['values']['menu']['link_title'] = 'Auto-page';
$form_state['values']['menu']['description'] = 'Own Programatic Page';
$form_state['values']['menu']['parent'] = 'main-menu:0';
$form_state['values']['menu']['weight'] = 5;

$form_state['values']['path']['alias'] = 'auto-page';
$form_state['values']['comment'] = 1;

$form_state['values']['status'] = 1;
$form_state['values']['promote'] = 0;
$form_state['values']['revision'] = 0;

$form_state['values']['op'] = t('Save');

drupal_form_submit('page_node_form', $form_state, $node);

```

Is there anything wrong?

---

Using Firebug (Mozilla Firefox plugin), I figured out the name of the elements and then fill it with the proper values.
Creating a 'page' node programmatically, in Drupal 7, is done using the following code:

```
global $user;

$customNode = new stdClass();

$customNode->type = 'page';
node_object_prepare($customNode);
$customNode->uid = $user->uid;
$customNode->name = $user->name;

$customNode->title = 'Your page title';
$customNode->language = 'en';
$customNode->body[$customNode->language][0]['value'] = 'Your value';
$customNode->body[$customNode->language][0]['summary'] = 'Your summary';
$customNode->body[$customNode->language][0]['format'] = 'filtered_html';

$customNode->menu['enabled'] = 1;       // 1 to enable providing a link in main menu
$customNode->menu['link_title'] = 'Your page link title';
$customNode->menu['description'] = 'Your page description';
$customNode->menu['parent'] = 'main-menu:0';
$customNode->menu['weight'] = 2;

$customNode->path['alias'] = 'Your Alias';
$customNode->comment = 1;

$customNode->status = 1;        // 1 means published
$customNode->promote = 0;
$customNode->revision = 0;

$customNode->changed = $_SERVER['REQUEST_TIME'];
$customNode->created = $_SERVER['REQUEST_TIME'];

node_submit($customNode);
node_save($customNode);

```

This not completely functioning.
The page is being created successfully with all the values, but the link is not shown in the main menu navigation (I mean in the main menu tabs near the Home tab).
I checked it out in the created content and it's there, accessed it via "edit" button, pressed "save" (without editing anything), and it appears in the main menu.

I want it to automatically show when it is created. Do you have any idea?

# Answer
The Devel project includes a module called Devel Generate for generating dummy content. You could use it as an example. I think the parts you'd need are in the devel\_generate.inc file.
> 5 votes

# Answer
An example of how to do this is here- just tried it and it works real nice:
How to programmatically create nodes, comments and taxonomies in Drupal 7

(This was actually found by codeinthehole for this answer, so thanks to him)
> 1 votes

---
Tags: 7, nodes
---


title: Passing user id argument to filter

text:
# Question
Title: Passing user id argument to filter
I have a view that lists the (ubercart) orders of a user. I created a view for that with a filter applied: "User: current". This works perfectly this way, I use this view in my profile page template like this:

```
$view = views_get_view('user_orders_custom');
$result = $view->execute_display('default', array($account->uid));

```

My problem is that when admin is inspecting the profile page of a user, this lists the orders of the admin, not the user being watched. Of course the passed $account-\>uid is not used by the applied views filter `User:current`.

I don't know how to make my view filter on the **passed uid**. I tried creating a relationship, arguments but the filter thing is not clear to me.

# Answer
The solution is: removing filter `User:current` and adding argument `(Order user) Ubercart order: User ID`.
> 0 votes

# Answer
May be what you need is contextual filters, the user can go to `view-name/%` where *%* is a contextual filter for the *uid*
> 1 votes

---
Tags: views
---


# Question
Title: How to prevent a node from listing programmatically?
How can I prevent a node from listing, programmatically? I want to select node by nid. Beacause of some reasons, I don't want to use `hook_node_grants()` and `hook_node_access_records()`

I tried to change the `_node_access_where_sql()` function in the core which creates where clause for use in fetching node listings but *$node* or *$nid* is not passed to the function so I can't select node by *nid*

# Answer
Have you tried simply unpublishing the node with Rules? Rules will allow you to programmatically unpublish content based on a variety of factors. Once unpublished, Drupal will not list the node in content with the exception of Views that are not set to only display published content.

What are you using to determine which nodes should be processed by your code?
> 1 votes

---
Tags: 6, users
---


title: Contextual filters help

text:
# Question
Title: Contextual filters help
I have a page and a view. I have placed the view as a block on the page and there is a contextual filter defined as shown in the image

Basically when i print the arg(1) in header and see i get like 42 which is like the node id on which the view is placed. Can you please tell me what its is trying to do when its placed in the contextual filters as it was was done earlier by another person. I mean to ask how does it filter out the data based on the node id ?

# Answer
> 1 votes
I am not certain if I understand what you are asking here, but this question is bound to come up on searches for anyone trying to figure out contextual filters. The information you present leads to several questions and comments:

It is unclear what your contextual filter will due without knowing more about the view fields, setting and path definition you have given it. Also, is this the contextual filter screen for the page or block?

To define the location for the argument in the path for a **page** view you place a % character at the location in the path definition for the view. eg. in `Example.com/content/%/items`, any URL value matching the path pattern will generate a view with the value of the % passed on to the contextual filter. IN this way you have a view definition performing generalized filters as defined in the first column of the view definition form page and additional filtering as defined in the third column under the '**Advanced**' option. For a page view you complete the requirements for the contextual filter under the heading "When the filter value IS available or a default is provided"

For a block you must complete the section "**When the filter value is NOT available**" and select "**Provide default value**". IN the drop down list you can tell the filter whether it is intercepting a content, taxonomy or user id node number or you can tell it to select a raw value from the URL and which position in the string it is. In the example I gave above the context value we are looking for (the % sign) is in the second position.

However the value is passed, the context filter will further filter the view as defined on the view form for that page or block.

---
Tags: 7, views
---


# Question
Title: Block in Utility menu top only shows on home page
heres my site coonvalleytel.com/drupal

I made a block with 3 pictures that are links to youtube, twiter and facebook. But they will only show when you are on the home page. Do you guys have any ideas for getting it to show for every page?

# Answer
> 0 votes
Please tell us about the view you have defined. What is the path, the filters, etc that have been included. The pages your view shows on are dependent upon the address or block settings you have defined for the view.

---
Tags: blocks
---


# Question
Title: Node referencing: How do you display a node with all its references?
Ingredients:

* Drupal7 + References + Views module installed
* 2 content types: magazine issue + magazine articles (for each issue)
* Article c-type has a reference field: issue\_no which displays the issue it belongs
* I made a Views to display me a plain list of issues only.

Requirements

1. When I click on the issue in the issue list I want to see all its references nodes(=articles) attached
2. I need to highlight the latest issue in the list by creating a separate page VIEW on the frontpage that contains articles of the latest view.

I would appreciate any help.

Here is a prinscreen on my content type \> manage display

# Answer
There several ways (at least) to do it. The solution we've discussed here is relevant only for one node reference. I found no way to display multiple node references

* A. Using taxonomy. Create taxonomy terms: issue1, issue2 and display an articles under one of this
* B. Duplicate BackLinks View ( a preset of Views )
* C. In issue custom type create a field for each article. The type of the field must pe node reference. (autosuggestions).After
adding articles , the editor will create a new issue and type the
article to be displayed in those article fields.
* D.Create A view and add a footer. In the footer add a new view (the
articles).
> 0 votes

# Answer
Install views and have it manage your home page, then add a content type filter so that it only shows issues on your home page. This will stop your home page being a mix of articles and issues.

Then, go to each content type and go to "manage display", in there you can specify the format, by default this is set to title (link). You also have an option for "full rendered node" which will display the whole referenced content inline.

Alternatively you could use views and create a block with the nid as a argument so it displays references content in a way you can choose fields to display etc
> 0 votes

---
Tags: views, nodes
---


# Question
Title: What is the meaning of the field:delta content type offered in contextual filters in views?
When creating a new contextual filter for a view the list of types includes options such as content:spec (field\_spec:delta) where spec is the name of a field I have attached to the content type accepted for the view. It appears on some, but not all of the fields offered in the list. I cannot find a reference on this field. What is this (field\_name:delta)?

# Answer
It appears only for multi-value fields. It refers to the order of the values. A delta of 0 is usually the first item, 1 is the second, etc. This can be used to restrict results to ones that have values for a specific delta.
> 31 votes

# Answer
In Drupal, delta variable name inherits the Drupal 6 terminology and is an index for fields, blocks etc of the same type.

In module developement $delta allows one module to return many blocks. It may also be easier to understand if you keep in mind that the $delta need not be numeric. It's simply an identifier.

In your case is a local identifier of that field. It is similar to #id in CSS.
> 6 votes

---
Tags: views, 7
---


# Question
Title: How to display the comment form of a node in a popup?
How can I display the comment form in a popup. I want the functionality when I click on the link "add new comment" on a node, the comment form should appear in a popup window.

Any one who have some idea?

# Answer
There is Dialog API for Drupal 6, and Drupal 7 (although only the development snapshot for Drupal 7 is visible in the project page). This module contains sub-module Dialog Comment.

For Drupal 7, as I can see, there are some problems with modules for popup dialogues.
> 1 votes

# Answer
Well, for it I can propose you a 'sexy' solution.

```
$(function(){
  var comments = elem = $('#comments'); // I get the element comments
  if(comments.size() > 0) { // I check if is exist
    // Here I remplace the form with a link
    var link = elem.replaceWith('<a href="#comments">'+ Drupal.t("Comment my node") +'</a>');
    // For the new link I give him a OnClick event.
    link.clik(function(){
      // Here I just hide the submit button, you can hide other buttons as well
      $('input[type=submit]', comments).css('display', 'none');
      // Here the dialog from jQuery UI you can change is as well
      comments.dialog({
        buttons: {
          "Comment": function() {
              $('form', comments).submit();
          },
          "Cancel": function() {
              $(this).dialog('close');
          }
        },
        modal: true,
        height: 245,
        width: 475,
        title: title,
        open: function() {
        },
        close: function() {
            $(this).dialog('destroy');
        },
        resizable: false,
      });
    });
  }
});

```

You've to include this code in the header or footer of your theme (better if you can check before if you're on one page with comments or not. And be sure that jQuery UI Dialog is also loaded with drupal\_add\_library.

P.S. I didn't try the code, so maybe you'll find some bugs, but the main idea is there.
> 1 votes

# Answer
Ctools has a nice modal functionality that is easy to use, and doesn't need you to manually add any depended JavaScript code.
> 1 votes

# Answer
If you want to do it in a fancy non-technical way use Beauty Tips module.

if you need help here is a good video on this topic.

http://gotdrupal.com/videos/drupal-views-enhanced-with-beauty-tips-module
> 0 votes

---
Tags: comments, javascript
---


# Question
Title: How to timestamp last block access to profile cck field
I need to log when a user last accessed particular areas of my site (a content type and some views pages), to do this I have added a block using PHP filter with the below code. This block is only visible on the required pages so I was hoping it would mean when a user accesses these pages it updates the users profile with the timestamp.

```
global $user;
$uid = $user->uid;
$node = content_profile_load(profile,$uid);
$pid = $node->nid;
$node = node_load($pid);
$changeLastAccess = mktime();
$node->field_changes_last_access[0]['value'] = $changeLastAccess;
node_save($node);

```

The problem is this date always shows the **CURRENT** time, not the time when a user was last on one of the pages on which the block is active. I am totally stumped...

**EDIT: This was working all along, i had created the wrong CCK field type of "Date" rather than "Datestamp", changed this over and it works fine.**

# Answer
The above works fine, however the cck field type needs to be a "Datestamp"
> 2 votes

---
Tags: entities, blocks, users
---


title: Setting up a mobile site

text:
# Question
Title: Setting up a mobile site
I understand that there is already I want to get a Mobile version of my drupal site working about setting up a mobile website, but I'm still having such a hard time figuring out what to do. I'm a newbie in web development in general. I was hoping that I'd get some more handholding here.

Basically I have a Drupal site up and running, e.g. http://example.com/fullsite/, and I want to set up a mobile site on http://m.example.com/fullsite.

I'm a Lunarpages customer, which uses LPCP (instead of CPanel). I've created the m.example.com subdomain for the mobile site, but I haven't created any redirection. Some CPanels apparently let me setup the redirection through it, but not LPCP.

Following the instructions on some random blog I found, I set up new folders in my Drupal's "sites" folder. My "sites" folder currently looks like the following:

* public\_html

+ fullsite

    - sites

        * default (and all its contents)
            * all (and all its contents)
            * mydomain.com.fullsite

            + settings.php (copied from default)
            * m.mydomain.com.fullsite

            + settings.php // copied from default, but with the theme\_default line modified

```
    $conf = array(
      'site_name' => 'My Drupal site',
      'theme_default' => 'zen',
      'anonymous' => 'Visitor',
    );

```

I've also:

1. installed Drupal's Mobile Tools,
2. set the mobile url to **http://m.mydomain.com/fullsite**
3. set the desktop url to **http://mydomain.com/fullsite**
4. enabled "automatic redirection of the mobile user" under "redirection options"
5. chosen a different node as frontpage for my mobile visitors under "additional settings"
6. Under "Theme Switching", chosen "Switch theme based on the URL"

But accessing my site from my mobile device, here's what I'm seeing:

* Going to m.mydomain.com/mysite = "Not found. The reqeuested URL /mysite/ was not found in the server"
* m.mydomain.com/mysite/node/somenode = "Not found. The reqeuested URL /mysite/ was not found in the server"
* mydomain.com/mysite = "Cannot open the page because too many redirects occurred".

Am I even on the right track here? Do I have to do a new Drupal install on my *m.mydomain.com/mysite* for this? I was under the impression that I could just get *m.mydomain.com/mysite* to get its data from the main drupal site, and display the contents with a mobile theme. Is this true?

I'm pulling my hair out over this (Well, not literally. I'm actually bald)! Any pointers will be greatly appreciated.

# Answer
I think you are on the right track, but I think doing this as a true multi-site is overkill, and potentially the wrong idea.

Ideally, you want your desktop site and mobile site to share the same content. If you are not going to go down the route of just using mobile stylesheets, then I suggest using Domain Access to create the mobile site.

You can use this module to set up your mobile domain, and then create your content accessibility rules for what is visible where. When used in combination with Panels, you have great flexibility.

Mobile Tools let you choose your theme for a user and also shows up in panel selection rules, and domain tools lets you show/hide content for a particular user.

Note the issue log for Mobile Tools, though. I found a bug with how the ctools selection rules work, and have a patch on the issue that hasbn't been committed or commented on.
> 1 votes

# Answer
Try to set a redirection towards the main domain (the site one) in your lunar panel. The mobile tools module will detect the agent and will switch the theme according to the agent detected.

You can install the Firefox Agent Switch module to simulate the agent detection.

I hope this help.
> 0 votes

# Answer
Great question as I'm trying to get this up and running also. I'm not sure if the Mobile tools take care of this but I am under the impression you need to setup your sites.php file.

something like this maybe.

```
$sites = array(
  'mydomain.com.fullsite' => 'mydomain.com.fullsite',
  'm.mydomain.com.fullsite' => 'm.mydomain.com.fullsite',
);

```

Again I'm not sure if mobile tools is doing this for you, but might be worth a check.

I'll be watching this closely as if you get success I will follow the steps you've laid out.
> 0 votes

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


title: add three triptych side by side

text:
# Question
Title: add three triptych side by side
i have made a custom theme "Custom\_stark" and made changes into .info file and added the triptychs

```
regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

```

in Custom\_stark.info.

But when I see with block " Demonstrate block regions (Custom\_stark) "

i can see only in this default format.

And how can i get the triptych in desired format mention in below image

And below is the code for page.tpl.php

```
<?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>
    <div id="triptych-wrapper"><div id="triptych" class="clearfix">
      <?php print render($page['triptych_first']); ?>
  <?php print render($page['triptych_middle']); ?>
  <?php print render($page['triptych_last']); ?>
</div></div> <!-- /#triptych, /#triptych-wrapper -->

```

# Answer
Try this

```
 <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>
   <div id="triptych-wrapper">
      <div id="triptych" class="clearfix">
         <div style="float: left; width: 25%;">
            <?php print render($page['triptych_first']); ?>
         </div>
         <div style="float: left; width: 50%;">
            <?php print render($page['triptych_middle']); ?>
         </div>
         <div style="float: right; width: 25%;">
            <?php print render($page['triptych_last']); ?>
         </div>
         <div style="clear: both;"></div>
      </div>
   </div>

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to set a rule that sets a term reference field value and text area value in a commerce order entity
This relates to a post I made here How do I copy a "purchase limit" field from a product to a product line item

Situation: We are building a commerce website using Drupal 7 and Drupal Commerce for a government agency that distributes free publications

They have a limit on the number of free items that can be ordered at once, (unless the person ordering has a good reason.)

We have a field called copy limit on our product entities.

If the user enters a quantity on the” add to cart “for that exceeds the copy limit, we want the order to go into a holding area after the order is completed for further review.

Our plan is to use a taxonomy term to do this. We have a vocabulary called "Is this a bulk order?" It has two terms, yes and no.

We want to have it so if the quantity in one of the line items in a customer's order exceeds the copy limit, the term reference field for the "Is this a bulk order" vocabulary is set to yes.

Also (I'm not sure if this belongs here but....)

In a related question, we are trying to get the user fill out a field if the copy limit is exceeded explaining why they need to exceed the limit. We have a field on the order called "Bulk Order Explanation"

Right now, I have rule that after saving a new line item, and the quantity exceeds the copy limit, the user is brought to a add content page for a content type I called "Bulk Order Explanation"

What we want to happen is that after they save the "Bulk Order Explanation" node, the body of the content type is used to populate the bulk order explanation field.

I am not even sure if I am headed in the right direction on either of these things. Thanks for any insight you can provide!

# Answer
> 1 votes
Here's a strategy that I think will work:

* Create a field on the product like field\_bulk\_order\_limit
* Create a field on the order called "field\_held\_bulk\_order" or something. This can be a boolean or some similar thing.
* Create a rule that looks at the product's field\_bulk\_order limit whenever a line item is created or updated and its product has that field. It could output to the screen (system: site message) at the user if the number is above the bulk order limit.
* Create a checkout rule (a rule triggered by "when completing the checkout process") that loops through the line items and checks their products' field\_bulk\_order\_limit. If it finds line items with a quantity higher than the field\_bulk\_order\_limit, set the order's field\_held\_bulk\_order to TRUE. Optionally also show them another message.
* Fiddle with your administrative order views to have a view that explicitly shows held orders,etc.
* Nice to have: create a custom pane that lets them enter the reason that they need so many. This requires a tiny module. It could imitate the commerce\_order.module's pane (see commerce\_order.checkout\_pane.inc and commerce\_order\_commerce\_checkout\_pane\_info()

---
Tags: taxonomy-terms, rules, commerce
---


# Question
Title: Fatal error: Call to undefined function ctools_include()  While implementing Drupal 6 Multistep Form Using Chaos Tools
I would like to implement a multi-step user registration form. After a long time googling, I found Intro to Drupal 6 Multistep Form Domination Using Chaos Tools. While I was trying to implement the suggested code, I got the following error:

> Fatal error: Call to undefined function ctools\_include() in var/www/WC/drupal\_website/sites/all/modules/wombat/wombat/wombat.module on line 26

How do I solve it?

# Answer
> 4 votes
As the Chaos tools suite module defines `ctools_include()` in ctools.module, the only reason I can think of what would explain the error is that you didn't install the module. The other reason could be that you are trying to access the function when the module is still not loaded; for example, if you call the function inside `hook_boot()`, then you would get that error.

---
Tags: 6, chaos-tool-suite, forms
---


# Question
Title: How can I remove some content types of the admin menu?
I have drupal 6.x and I have installed the module "Admin menu". I want to know how can I remove some content types of the menu? I have looked that this menu loads all options of the website and I only require to remove the some content types of the menu.

Thanks for your help.

# Answer
I do not know if this way is useful for you: In `admin_menu.module` I have included a php `if` in `admin_menu_tree_output` to detect and remove items according links of content types to hide:

for example, I have several content types with the address http://yourdomain.com/admin/content/node-type/testcontenttypeXX. *(**XX** is numbers)*

then I have added `if(preg_match('/(testcontenttype)/',$serializeData) == false)` to `admin_menu_tree_output` function, seeking in `$serializeData = serialize($data['link']);` the respective address:

```
function admin_menu_tree_output($tree) {
  $output = '';

  foreach ($tree as $data) {
    $extra_class = isset($data['link']['localized_options']['extra class']) ? $data['link']['localized_options']['extra class'] : NULL;
    $link = admin_menu_item_link($data['link']);
    $serializeData = serialize($data['link']);

    if ($data['below']) {
            if(preg_match('/(testcontenttype)/',$serializeData) == false){
                $output .= theme_admin_menu_item($link, $data['link']['has_children'], admin_menu_tree_output($data['below']), $data['link']['in_active_trail'], $extra_class);
            }
        }
    else {
        if(preg_match('/(testcontenttype)/',$serializeData) == false){
            $output .= theme_admin_menu_item($link, $data['link']['has_children'], '', $data['link']['in_active_trail'], $extra_class);
        }
    }
  }
  return $output ? "\n<ul>". $output .'</ul>' : '';
}

```

I hope information be useful.
> 1 votes

# Answer
While you can add/remove items from the admin menu from this menu /admin/build/menu-customize/admin you really shouldn't, that would be customizing what that module does and anytime they release a new version you would have to make your customization again.

The purpose of that module to to simplify, or make shortcuts to, all of the aspects of administering a Drupal site. If there are certain portions of the admin you don't want users to see, use roles to control which of the links are viewable.

Hope this helps!
> 3 votes

---
Tags: 6
---


# Question
Title: Prevent embedded video appearing above image overlay
http://www.fareham.ac.uk/news/2011/10/17/skins-star-inspires-students

The above page includes an image gallery, powered by the Brilliant Gallery module.

The problem: when a thumbnail from the Gallery is clicked, the embedded YouTube video beneath the Gallery section appears above the image overlay (powered by the Lightbox2 module).

How can I prevent this from happening?

# Answer
It is a matter of wmode
> 1 votes

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


# Question
Title: How can I automatically rotate a picture?
apparently Drupal 7's built in image handling doesn't automatically rotate images based. Is there an option to do that? If not, how can I make it easy for a user to rotate an image left or right?

# Answer
ImageCache Actions seems to provide an "autorotate" feature. If server has Exif PHP extension enabled, and user's camera saved orientation in EXIF data, it automatically rotates image correct side up.
> 5 votes

# Answer
In Drupal 7 the rotation feature is in `Configuration > Media > Image Styles`. Then in configuration of your image field, you can chose the style related.

to see image rotated, you must asign the style in the `Manage Display` tab of fields of your Content Type.

I hope information be useful.
> 3 votes

---
Tags: 7, media
---


title: Erase custom translation

text:
# Question
Title: Erase custom translation
I need to erase a custom translation I made for the Addresses Module. The problem is I changed

> Mexico

to

> México

(with accent) and now, logically, the module does not work correctly since it is looking for the previous value so it can autoselect the states.

Is there a way I can erase the translation? I have tried to search for it but so far, I have not found the right entry.

I am able to use PHPMyAdmin, in case this is feasable thru SQL.

Thanx.

# Answer
I used a module called Localization Client which provides a user GUI for translations, enable it and go to the page with the translation you should be able to find it in the list then and alter it.
> 1 votes

---
Tags: 6, i18n-l10n
---


title: Add node with no title

text:
# Question
Title: Add node with no title
I would like to let users create elements with no title.

In this particulary case, I would like them to enter a registration number, as you can imagine there's no need for a title right here.

How can I remove it from the creation page (node/add/node-type), so I can only see the fields I want (not the title)?

# Answer
> 9 votes
The Automatic Node Titles module does that.

# Answer
> 2 votes
You can't submit a node without a title. You can use the Auto Nodetitles module which doesn't completely remove the title field, Instead hides the title field and fills it with a given pattern.

Another way is to rename the title field to *Registration Number*, if you are using a text field for registration numbers,

---
Tags: 7, nodes
---


title: Add a login form to my module

text:
# Question
Title: Add a login form to my module
I want to add the login form to a custom page I've created using a custom module, but I dont know how?

Shouldn't there be a form to use like get\_drupal\_form?

Using Drupal 7.

# Answer
> 1 votes
I figured it out. I used:

```
$html = drupal_render(drupal_get_form('user_login'))
return $html;

```

# Answer
> 3 votes
Drupal comes with a login block you can put in any of your theme regions to have show up on that page.

Or you can use `drupal_get_form('user_login')` if you want it to show up in your content somewhere.

---
Tags: forms, users
---


# Question
Title: How to hide view's results before applying exposed filter?
In a view I have some exposed filters.I would like the view to show no results before applying the exposed filter(s),but only after I have applied the exposed filter.By default,the view shows all the results.How can I achieve that? Thanks

# Answer
you could link to the view and pass a filter argument in the URL that doesn't have any results.

Or you could hide the exposed filters in a block. Also, create a "block" display for your view results.

Add the filter block to a page. Add the "results" block to the page but only show it for pages with "pagename?\*". That will hide your results block until filter values are passed through the URL.
> 4 votes

---
Tags: views
---


# Question
Title: How to conditionally load JavaScript with template.php
I have a content type that has involves some js magic for every node. How can I code it into template.php so that it is loaded only on display of the content type? I don't want the js to load uselessly on every page. My php skills are pretty shallow.

# Answer
> 0 votes
js\_injector module lets you control which pages you want to include your code.

CSS\_injector does the same for css.

---
Tags: theming
---


# Question
Title: How can I output debug info from hook_node_presave()?
I'm learning about module design for Drupal 7 and I want to see what hook\_node\_presave is being passed (and working with), how can I output debug info so that I can learn how to manipulate it?

Is there a similar hook that I can use to print out debug info?

# Answer
install the devel module and dump your variables with dpm($input, $name = NULL) to the screen.

This article shows additional debugging options.
> 2 votes

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


title: Get related node by taxonomy term?

text:
# Question
Title: Get related node by taxonomy term?
Let's say I have two content types: Page and News. Both of them have a field called Tags which is taxonomy term.

Let's say I tag a page and a news item with the term 'celebration'. When a user goes to the page on the front end website, the user should see related news items on the right side bar. A news item is related to a page if they both have at least one tag in common.

I tried to set up a news item block, but i don't know how to tell it to show only news items that share at least 1 tag in common with the page.

# Answer
I've used the 2.x version of Similar by Terms in the past, and it is very good, with nice views integration. A D7 version of the 2.x branch is in development at http://drupal.org/node/1270244.

The Apache Solr module can also supply a block of nodes that have similar taxonomy terms based on a Solr database: http://drupal.org/project/apachesolr. Very fast, but not trivial to set up.

Finally, here's a comparison of similar/relevant content block modules: http://drupal.org/node/323329.
> 2 votes

# Answer
I don't this is good form, but it achieved what I wanted. I created a block then pasted in the php code.

```
<?php

  if ((arg(0) == 'node') && is_numeric(arg(1))) {

        $sql = "
SELECT node.* FROM node
INNER JOIN field_data_field_tags ON field_data_field_tags.entity_id = node.nid
WHERE node.type = 'document'
AND field_data_field_tags.field_tags_tid IN

                (SELECT field_tags_tid FROM field_data_field_tags
                INNER JOIN node ON node.nid = field_data_field_tags.entity_id
                WHERE node.nid = ".intval(arg(1)).")
        ";

        $result = db_query($sql);
        while ($row = $result->fetchObject()) {
                echo '<a href="'.url('node/'.$row->nid).'">'.$row->title.'</a>';
        }
?>

```
> 1 votes

# Answer
If I understand your question, I think that this module can be useful http://drupal.org/project/similarterms

> Similarity is based on the taxonomy terms assigned to content. Blocks are available based on similarity within each of the defined vocabularies for a site as well as a block for similarity within all vocabularies.
> 0 votes

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