# Question
Title: Dynamic menu with latest Article in drupal7
I'm a bit new to Drupal environment. I'm trying to develop a demo site for CMS application. Now I'm facing a difficulty to create a dynamic menu for showing taxonomy-wise latest Article. Can I do it with any existing module (Muchomenu, OM Menu etc.,)

Thanks....

# Answer
I am sure there is a module do to something like that, but you could also create your own.

You could use hook\_menu() to query for the items you want and return the correct menu structure. You would need to also make sure the menu cache is rebuilt on a node save.

hook\_menu should return an array of menu items, often these are pretty static however there is nothing wrong with these arrays being dynamically generated.

So you can query the node table to get a list of nodes you want, loop through these items and dynamically create an array which contains the correct menu items.

very roughly:

```
function example_menu() {
  $result = db_query('select * from node where ...'); // put in your own select items and where clause
  $menu = array();
  while ($row = db_fetch_object($result)) {
    $menu['my_path/' . $row->nid;] = array(
      // See hook menu docs for what to put here.
    );
  }
  return $menu;
}

```
> 0 votes

---
Tags: theming, routes
---


# Question
Title: Views 3 and HTML5 - how to override output for markup?
I have a view that I've created that selects blog posts based on a specific taxonomy term, creating a sort of "Featured Posts" view that I've embedded on the front page of my site. The issue I keep running into is trying to output the view so that each post is semantically marked up using some of the new HTML. I've tried the built-in "Rewrite this field's output", but it ignores the tags I use (ie, article, header, footer) and wraps everything in divs even when I deselect the placeholder tags.

Should I create a overriding views--view\_name.tpl.php to rewrite the output of each post as it appears in the view, or do I need to use preprocess hooks in the template.php to affect the output?

I should state that I have basic experience with writing PHP and preprocess hooks, but I can any resources I need to move me down the linke if I'm pointed in the right direction.

# Answer
You'll notice that in your view under the "Style Settings" block there is a link for Theme: Information. It will expose all the theme files that are called for your view. You can use generic to very detailed theme files that will only be use for your views display.

The first file name in Display output is views-view.tpl.php. That will apply to all views and displays. The next one in the list is views-view--\[view name\].tpl.php. It will only apply to your view. It keeps drilling down until it gets as specific as possible. views-view--\[view name\]--default.tpl.php is the last one in the list and only applies to the default display of the view. Clicking the Display output: link will expose the template code that views uses. Simply copy and create a new template file with one of the suggested in the list. It's usually best to be as specific as possible. The template file can go anywhere in your theme and views will pick it up as long as you rescan template files in the theming information and save the view. There are view templates, row templates, field templates and field specific templates.

Once you learn how to manipulate view template files it will really open up your design possibilities.
> 10 votes

# Answer
Fences looks like a great module (for Drupal 7) to control views output markup:

Project page:

http://drupal.org/project/fences

From the project page:

> "Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field."

I like this bit particularly (great for debugging output):

> "Best of all, Fences provides *leaner markup than Drupal 7 core*! And can get rid of the *extraneous classes* too!"

This is also nice - reducing repetition of work:

> "This kind of tool is needed in order to create semantic HTML5 output from Drupal. Without such a tool, you have to create custom field templates in your theme for every field. :("

They've considered the popular alternatives too:

> Similar projects include **Semantic fields**, **Field Wrappers** and a tool inside the **Display Suite** extras. But we think this approach is Morefasterbetter™.

Credit to Drupal user rhache for mentioning the Fences Drupal module in their comment on this question Is Semantic Views module obsoleted by Views 3?
> 2 votes

# Answer
You may try semantic views module.

As it says at this issue, it is useful for html5 output.
> 0 votes

---
Tags: 7, theming, views
---


title: Simple drupal admin for clients?

text:
# Question
Title: Simple drupal admin for clients?
Basically Drupal is bit complicated for normal clients. Drupal 7 is better but still its not that user friendly for clients especially when comes to admin content or taxonomy!

Is there any module or themes which designed the client in mind? I found tabtamer and quickbar very helpful :) Any other to simplify admin section?

# Answer
We typically leave Seven as the admin theme on Drupal 7 sites, and use Rootcandy as the admin theme on Drupal 6 sites. One of our large clients installs Rubik whenever we deliver them a site.

A good admin theme can help, but it is really just lipstick on the pig.

I will also agree, to an extent, that Workbench can be of use for content creators on sites that are adding lots of new content.

However, the administration problem for Drupal is solved by doing three things:

1. Only install the modules that you actually need. Once you have a site ready for deployment, disable and potentially uninstall anything that you don't actively need. This reduces the number of entries in the admin menu.
2. Set up a proper set of roles and configure the bare minimum permissions that each role needs. Even if a single person is running the site, set up a non-administration role for their user that they will need for daily tasks. Save the uid 1 account for occasional tasks. Again, this reduces the number of entries in the admin menu.
3. Set up as much contextual help as is feasible and train the client. It is especially helpful if you can match up features in your site to a good book, like The Definitive Guide to Drupal 7.
> 8 votes

# Answer
Although Workbench is good I use to build a custom admin with:

admin menu and admin menu source to build a custom admin menu per editor.

Also is good to have menu per role to choose what menus can edit editors.

With views and views bulk operations you can build a better administration interfaces.

With this you must built it, but I think you will get a better options that Workbench.

Also you can use dashboard to help user to see their options.
> 8 votes

# Answer
Workbench provides overall improvements for managing content that Drupal does not provide out of the box.
> 3 votes

# Answer
Workbench is probably a good idea for general administration/workflow improvement. But if you're looking to improve UI on a fine-grained level you could set a custom tpl page for adding/editing a node if you don't like the default add/edit view (I know I don't). Or, along the same lines, you could run hook\_form\_FORM\_ID\_alter(). I know you're asking for a module or a theme, but thought I'd mention this anyway.
> 3 votes

---
Tags: 7, users
---


# Question
Title: Pressflow Install - Redirect to database configuration without error
I am currently installing the database in the conguration distribution "Pressflow." I have already installed apc and varnish.

During installation, I put the access to the database and when I click OK, I am automatically redirected to the same page. This does not create the database

# Answer
> 1 votes
Make sure that in your `settings.php` all your configurations are properly set. (e.g `$db_url`, `$base_url` ..)

# Answer
> 0 votes
You need create the database manually first.

---
Tags: redirection, installation, 6
---


title: Drupal 6 - Grouping Modules together

text:
# Question
Title: Drupal 6 - Grouping Modules together
I have been creating a lot of code in the past few months for my Drupal 6 website and have since created about 20 modules of code that all pretty much go together.

I know we can group modules together in a folder, but am wondering what impact this will have if I do this on already deployed modules.

Is it possible for me to simply create a new folder in the sites/all/modules folder and move all my modules in this new folder? Will Drupal handle this properly?

# Answer
> 1 votes
Grouping modules is allowed in Drupal, when the modules are not already modules. Because, the modules are registered in System table by the location of the module. So, Changing the folder structure will result in fatal errors.

If you would like to change the folder structure then you need to disable the modules and uninstall them. After that, you can re-enable them after changing the folder structure by grouping them.

**Note:** Make sure you won't lose any data when you un-install the custom modules. Take a backup of database and source code before doing any changes for safe side.

---
Tags: 6
---


# Question
Title: Made a local copy of live-site: all paths generate error 404
Drupal version: 6

I've made a local copy of a site that is live, has loads of content and is configured to run in the Kurdish language.

Steps I did to accomplish this:
\- Made a tarball of the Drupal installation and extracted it on my localhost
\- Dumped the live-database and imported it locally
\- Modified settings.php to reflect local database settings

When browsing to the local installation, the front-page seems to work fine (except for a few pictures not showing up, as well as the facebook like box generating a 404 error). Except: when clicking on any url, of any node-type, a 404 error is generated.

I tried to fix it with this proposed solution: http://www.paulmarc.org/learn/drupal/rebuilding-site-urls, but to no avail. It seems to me I have to rebuild the site, however: even invoking that path does not work and generates a 404 and is thus inaccessible.

# Answer
> 1 votes
Fixed. It appeared that I installed the mod rewrite module, but didn't activate it in my default site profile (as per these instructions: http://www.seangw.com/wordpress/2012/01/how-to-enable-mod\_rewrite-in-apache2-ubuntu/). Did that and everything works fine now. Woops, feel kind of stupid now.

---
Tags: installation
---


# Question
Title: How to track users actions on a form in my website
I read some post about "how to track..." but i didn't find my answer. I don't want to track the user loggin or how many time a user click on a link but what i would like to accomplish is:

* Track my user (anonymous or authenticated) to know if they failed to fulfill a form (failed = quit before submitting the form)
* Have a rate about each form who tell me, for example : 30% of users who begun the register form, stopped before submiting
* And more, knowing which fields were fulfilled before he quit.

My purpose is to help me to:

* Understand which process, forms are misunderstood in my website
* Maybe, knowing exactly which fields in my form (which label) are misunderstood (thanks to the fact that i could know which fields were empty when he quit)

I'm not a pro of `Google analytic` but i don't think so he can do that. What is the better approach for me to do that?

Thanks,

# Answer
> 2 votes
PHP saves data once you click the submit button, so finding which fields they filled before quitting might not be that straight forward. But you can always see how many times form was loaded and number of submitted entries to find the ratio.

---
Tags: 7, forms
---


title: Does everything need a bundle?

text:
# Question
Title: Does everything need a bundle?
I'm learning about the Entity API. I have a simple extra table that I'd like to "drupalize" so that I can use it in Views, for example.

I've read quite a bit, watched a few videos, looked at quite a few examples. I'm stuck on the concept of **bundles**. I understand what bundles are (e.g. node types are bundles of the node entity).

But for my use there will only ever be one bundle. In the examples I've seen the bundle is stored in the database table; this is not necessary for me as it would be the same value stored against every record. So I was thinking I could somehow skip this, or have my entity always return a standard string for bundle.

Have I misunderstood? Do bundles always have to be implemented, and implemented at database table level?

# Answer
Yes a bundle is always, always necessary for entities.

If you don't define your own bundle(s), the entity system will assign a default one with the same name as the entity type for you, and that one will be used.

If you've only got one bundle, and only ever plan to have one bundle, then you don't need to have a specific field in your entity table for it. As you suggest in your question it would always be the same, so would be redundant and just add extra overhead (however tiny) to your db queries.

If you think you might need to distinguish between different sub-types of your entity at some point though, it would be worth building that in right from the start; it really depends on your use case.
> 9 votes

---
Tags: 7, entities
---


# Question
Title: How can I get all the taxonomy term objects from the database regardless of vocabulary?
I can see in the Drupal taxonomy api taxonomy\_get\_tree() which returns an array of term objects, however, the vocabulary ID is a required object. I thought also about taxonomy\_term\_load\_multiple, but an array of IDs is necessary to populate it.

How can I get all the objects regardless of vocabulary affiliation? More or less what I am looking for is taxonomy\_get\_tree('all').

Each term object contains the \[vid\] it's associated with. I need to be able to loop through each object and determine the vocabulary it's associated with rather than the other way around.

# Answer
You can use the `entity_load()` function. The second argument, `$ids`, is defined as such:

> An array of entity IDs, or FALSE to load all entities.

So you can get all taxonomy terms in the database with this simple call:

```
$all_terms = entity_load('taxonomy_term', FALSE);

```
> 3 votes

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


title: Print rendered entity reference value

text:
# Question
Title: Print rendered entity reference value
How can I print the rendered values of an entity reference field into node.tpl.php?

I have an entity reference field called Instructors which references users. Using Devel I can find the target\_id of entity reference items, but I can't for the life of me figure out how to render these ids.

# Answer
You can try something like this

```
// $node represents the node object
$wrapper = entity_metadata_wrapper('node', $node);
$instructors = $wrapper->field_instructor->value();

```

Now in instructors you will have each instructor user object and you can print what ever information you want to print from it.
> 1 votes

---
Tags: 7, theming, entities
---


title: How can I log page cache hit rate?

text:
# Question
Title: How can I log page cache hit rate?
I'm running D7 on a php-fpm/nginx stack.

I want to test out some different combinations of cache lifetime and crawler frequency and see how it affects my page cache hit rate. What is the easiest (and reasonably performant) way to create a log with `time | url | ip | hit/miss` for the built-in page cache.

# Answer
> 1 votes
I figured out how to make nginx do the logging in a rudimentary way. I just added the following after my fastcgi\_pass directive.

```
log_format cache '$time_local $remote_addr $request_uri $sent_http_x_drupal_cache';
access_log /var/log/nginx/cache.log cache;

```

I'm not going to mark this as answered, because there are some problems with this solution:

1. Doesn't exclude pages that don't have the X-Drupal-Cache header set (logged-in users)
2. Doesn't exclude IPs I don't want logged (mine, for example)

For now I'll just deal with those issues when I parse the log file to create my stats, but if someone has a way to exclude them from the log then that would be preferable.

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


# Question
Title: Is there a way to create a taxonomy path redirect?
I am trying to create a taxonomy redirect for specific taxonomy URL. Basically what Taxonomy Redirect did for Drupal 6 but for Drupal 7. I have searched the Drupal 7 API for hook\_term\_path but don't see it.

Finally, I need these links to be associated with particular profile2 profiles.

Is this possible?

# Answer
Instead of `hook_term_path` you can use `hook_entity_info_alter`.

A small example

```
function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'MYMODULE_term_uri';
}

```

and then you can implement you version of `MYMODULE_term_uri` function.

Hope it helps.

Also if you want the D7 version of the module you mentioned you should try http://drupal.org/project/entity\_path
> 3 votes

# Answer
drupal.org/projects/tvi seems the closest for drupal 7. It actually does what I need. I am just concerned that its not needed since what it does could be done with managing the fields of taxonomy and this doesn't point directly to specific nodes created by views for profile 2.
> 1 votes

---
Tags: 7, taxonomy-terms, navigation, redirection
---


# Question
Title: Is there an easy way to check for http resources when I am switching to https?
The company I work for is going to be switching to serving everything over https. This means that all referenced images/scripts/etc. need to also be server over https. Is there a way to see what links/references and such I will need to manually fix?

# Answer
Saint Mary's College in Notre Dame, IN has developed a script to look through the node\_revisions table and help you visualize the references. You will likely have to adapt what they have written to fit your situation, but you can check it out on github.
> 2 votes

---
Tags: 6, media
---


title: How to create footer links

text:
# Question
Title: How to create footer links
Does anyone know how to add link such as about us in the footer region. i am using the zen theme. Further, How do you redirect people to the login or register page from pages such as upload, thus if they are not logged in.

# Answer
> 6 votes
You place your menu through the admin/structure/blocks form. Relocate the menu block from the disabled category at the bottom of the form to wherever you wish (footers). To get rid of the name, select configure for the menu block and enter in the Title box.

# Answer
> 2 votes
You can edit your footer in the "Manage block" section ("admin/structure/block").

# Answer
> 0 votes
Footer Map block is a good way. Its just a block of text links associated with certain menus... Or you could create a field view of the type of nodes or entitys you need and just create text links for the titles.

---
Tags: 7, navigation
---


# Question
Title: Views: show only one node per select box value
I created a Block showing the latest 3 articles ("pets") as teaser (not using fields). The content type has a field `type` which can be **dog**, **cat** or **other**.

Now i want to show only one of each `type`: one dog, one cat and one other. I don't have any idea how i can do that... I have some filter criteria (content-type=pet, available=yes, public=yes) and sort criteria (content:date\_arrived desc) and limited to 3 items.

Thanks for any help / hint!

I'm using drupal 7 and the newest views-module.

# Answer
> 1 votes
I thing it's difficult to make just with the views UI (the aggregation will not work) If you don't want the solution of Anil Sagar, i have another solution with some theming.

* Go to `format => setting` : In **Grouping field Nr.1** select your field `type` (left)
* Now your result will by group by type (dog, cat and others) You can see an extrat of the output. (right)

* Go to `Advanced setting => Other => Theme information`

* Copy / Paste `views-view-list.tpl.php` in your new template and make some modification

```
 <?php print $wrapper_prefix; ?>
 <?php if (!empty($title)) : ?>
   <h3><?php print $title; ?></h3>
 <?php endif; ?>
 <?php print $list_type_prefix; ?>
 //Add this
 <?php $x = 0; ?>
 <?php foreach ($rows as $id => $row): ?>
    <?php if($x < 1): ?>
    <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
    <?php $x++; ?>
  <?php endif ?>
<?php endforeach; ?>
<?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

```

And you'll have what you wanted:

# Answer
> 0 votes
I think below solution should work.

* Create three block views.
* Each will have three different type filters -- 1st view block (Type: dog) -- 2nd view block (Type: cat), 3rd view bloc (Type: Other)
* Restrict number of nodes to 1 in pager settings.

Enable all three blocks one below other or use views attachment feature as explained here.

One more solution for this is using Aggregation feature in views. I haven't tried this but should work i think. Give it a try !

---
Tags: views
---


# Question
Title: Selecting correct entities and fields in Rules
I am using the Rules interface to set up some rules about a booking site I am building. (using AGReservations+Ubercart in Drupal 7)

I have a field called Duration which is part of an entity called Reservation, which is itself is part of Ubercart's Order entity. I am having trouble getting my conditions to fire on the value of Duration, because there are many different entities and I am not sure if fields bundled with Entities are entities themselves, or how to pull the values out so that I can run my conditions and have the desired action.

Is there any module or tutorial to simplify this process? Something that makes it easier to know what kinds of data you have rather than plain trial and error?

# Answer
> 0 votes
**Rules Module**

Rules has a built-in debugger that can be fairly useful to see what was passed to your rule. It can be found and enabled at admin/config/workflow/rules/settings

---

**Devel Module**

The Devel module is another tool that is very valuable when debugging Rules. If you are working with custom code there are two functions in particular that will save you tons of time.

dd() and dpm().

dd() will write debugging data to file. Generally to /tmp/drupal\_debug.txt on \*nix based systems.

dpm() will display debugging data to screen, but may be a little less useful when debugging rules as redirects at times can cause issues while viewing.

**Usage Examples**

```
dpm($form);
dd($form_state);

```

Rules is an incredible module, but debugging can be a pain for sure. I would be happy to clarify if the above doesn't answer your question.

---
Tags: 7, rules, ubercart, entities
---


# Question
Title: Add intro text before profile 2 form in the registration page
I have a site that use profile 2 to add some field in the user registration page (/user) and via LoginToBoggan I can ask email x 2 and password x 2.

Now I need to insert a little introductive text before profile2 fields, like a phrase that explain why I need to ask that fields to the user.

How can I create it?

# Answer
You can use the markup module to display text. It is available as a field element.
> 2 votes

---
Tags: 7, entities, users
---


# Question
Title: Show various nodes in different ways on home page in drupal7?
I want to show nodes in different ways. For example, i want to show featured nodes, recent nodes. My question is that how we can show nodes in different ways on my home page.

See this demo site, i want my home page in drupal as like it.the problem is that how to manage nodes different ways as posts in WordPress.

thanks for the help

# Answer
Welcome to Drupal StackExchange !

You can build various views of same content using Views module in Drupal. You can follow this link to know more about the views module and also Views Documentation in the project page.
> 1 votes

---
Tags: theming
---


# Question
Title: How do I build a user table with aggregated article data?
I'm new to Drupal, and I want to make an overview over aggregated user data related to the articles they have written.

I basically want to build a table like this:

```
------------------------------------------------------
| user | articles published | articles with comments |
------------------------------------------------------
| bob  |                 12 |                      3 |
------------------------------------------------------
| sue  |                 34 |                      0 |
------------------------------------------------------
| kim  |                  0 |                      0 |
------------------------------------------------------

```

What is the best way to make a table like this? Is this something I need to make my own module for?

Would it be possible to aggregate this with an existing module?

# Answer
Welcome to the Drupal StackExchange !

You can achieve this with some custom php code and couple of queries.

```
<?php

   $articles_publishers = db_query("SELECT DISTINCT u.uid FROM {node} n LEFT JOIN {users} u on n.uid = u.uid where n.type = 'article'");
   foreach ($articles_publishers as $articles_publisher) {
     $publisher = user_load($articles_publisher->uid);
     $username = theme('username', array('account' => $publisher));
     $articles_published = db_query("SELECT count(*) FROM {node} where uid = :uid and status = 1 and type='article'", array(':uid' => $articles_publisher->uid))->fetchField();
     $articles_published_with_comments = db_query("SELECT count(*) FROM {node} n INNER JOIN {comment} c ON n.nid = c.nid where n.uid = :uid and n.status = 1 and n.type='article'", array(':uid' => $articles_publisher->uid))->fetchField();

     // Theme the information with above results

     print "Username :" . $username;
     print "articles published :" . $articles_published;
     print "articles with comments :" .  $articles_published_with_comments;
   }

?>

```

use above code in a module custom block or Add Block with php option to display the information.

Hope it helps.
> 1 votes

---
Tags: 7, css-js-aggregation
---


# Question
Title: How to delete data from a field programmatically
I have a content type called companies In this cck I have an Image field and user can add more than one image

I want to make a form programmatically that will display all images in a grid and under each image a button to delete it

Is there is a way to delete it from the node (this specific image only or I should make node\_load to get all fields and then check for all images and node\_save the node again)

# Answer
I think it's already answered here. You just need to build an interface to display images in grid format using views and a delete button is just a link where you pass the node id and delta value of field value to delete.

Once you call the link which will be a custom menu path with callback which executes the code shown in above link to delete the delta field value.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to set files public directory programmatically?
I have standalone script for adding some files to Drupal nodes. It is in main Drupal directory. It is multisite enviromnent. I know how to choose database and I am sure that I am choosing proper database, but my files lands in `sites/default/files` but I want them in `sites/domain/files`. I am getting public files path by

```
drupal_realpath('public://')

```

It returns `sites/default/files`.

All other things are correct and file data lands in proper database.

I checked site (admin/config/media/file-system) that database I am using and this path is set to `site/domain/files`...

Is there any chance to set public path programmatically? So `file_copy` will use proper path.

**EDIT**

The reason that I am asking is that my hooks: `hook_file_presave` doesn't invoke and I am thinking that is because public path problem. (All required module are enabled)

In single site env script works ok.

Probably the only solution is to create module, but it strange it isn't works. I wanted to stay away from creating modules for long running task because it's take longer and Batch API is slower that good old CLI. All my previous scripts worked with multisites.

# Answer
> 2 votes
You can set that variable like so:

```
variable_set('file_public_path', 'sites/domain/files');

```

Hopefully someone else will be able to tell you why this problem is happening, I have no such issue in any of my multisite installations.

---
Tags: 7, files, multi-sites
---


# Question
Title: Selling art with Drupal Commerce - how to approach?
I have a fair amount of experience with Drupal 7 but I'm confronted with some requirements that I simply don't know how to think about in terms of Drupal modules, etc. I'm not looking for a step-by-step tutorial; I'd just like to know how I can implement this roughly so I know which direction to head in.

I'm making a personal site for a friend who is an artist. We defined a custom content type, *work of art*, that allows her to add each piece she has created.

* She wants to sell some *works of art* and simply list others (never sell).
* Of the *works of art* for sale, for some the originals will be for sale, while for others only reproductions will be for sale.
* For reproductions, users need to be able to choose from among different sizes.
* Even after a *work of art* is sold, she would like to keep the node published so visitors can see it, though it should no longer be available for sale.

I've already built a gallery of the *works of art* in Views. Ideally, I would be able to add the option to purchase each work directly on its node page rather than building a separate store.

Is this going to be relatively straightforward to do in Drupal Commerce? What is the general approach I should take to this, given the requirements above?

# Answer
> 3 votes
Products you sell are not nodes in Drupal commerce, but are their own entity where you can define product related stuff, like SKU, price etc.

You probably will need two product types, one for originals and one for reproductions.

You will need to create a product reference field on a node or something else in order to display the add to cart form along with product details, this can be done on your work of art content type.

In order to select size, the easiest solution will be to create on product per size, then reference all of them and commerce will do the rest.

---
Tags: 7, commerce
---


title: Disable form redirect

text:
# Question
Title: Disable form redirect
I want to disable the form redirect.

```
$form['#redirect'] = FALSE;
$form_state['#redirect'] = FALSE;

```

Neither of those works.

How can I turn off form redirect? I want to see the output of `$form_values`.

# Answer
> 3 votes
If you just want see the $form\_values array, I suggest you to install Devel and use the function dsm or even you can use the drupal\_set\_message with print\_r.

# Answer
> 0 votes
for Drupal 7 a redirect wont occur if any of these variables are set and returns false when checked with empty() $form\_state\['programmed'\] , $form\_state\['rebuild'\] or $form\_state\['no\_redirect'\]

you can try by setting in hook\_form\_alter,

```
$form_state['no_redirect'] = TRUE

```

---
Tags: 6, forms
---


# Question
Title: How can I generate a link from a text field and a URL in a View?
I have an entity type consisting of 2 fields, a description field and a URL field, and I want to create a view with a single column which consisting of the description outputted as a link to the URL, ie `<a href="url">Description</a>`.

I don't know whether I am doing it the right way. I tried to use the tokens and rewrite results to create URL in the form `<a href="url">Description</a>` but it winds up pointing to the Drupal node. Is there some way of creating some kind of calculated field pointing to the URLs?

# Answer
> 2 votes
In Views you have a couple of ways to do this:

**Method 1:**

1. Add the url field to the view, but "exclude" it from the display
2. Add the description field to the view, but re-write its out put to a link and add the URL token replacement as the URL or path.

**Method 2:**

1. Add the url field to the view, but "exclude" it from the display
2. Add the description field to the view, but "exclude" it from the display
3. Add a global field for custom text and inside of it add field-description where field-url and field-description are the replacement token from the fields added to the view.

**Note:** In views it is important the order of the fields, so if using method 1 the url field has to be placed before the description field.

---
Tags: entities, uri
---


# Question
Title: How to link one given Image field to a specific view?
I would like to link an **Image** field to a specific view (created with Views) in a given *view mode*, under *"Manage fields"* tab, making this opportunity available **only within a given content type and only one specific field**.

I could also "hack" it into a given `theme_image_...` function, but I think it would be nicer to make it easily modifiable via the admin interface like this:

Maybe this could easily be done with a given or a custom module, but I don't know what would be a nice solution to this.

# Answer
Here is an idea:

1. On the content type hide the image from the display as you will show it with as an EVA field.
2. Using Views EVA attach the image to the content type so that the image is visible again, don't forget to check the views arguments to that the right images is shown in the node.
3. Re-write the image to be display as a link and there you can put the path to the view. Here you can also play with the image formatter as well.
> 1 votes

---
Tags: 7, navigation, media
---


# Question
Title: form auto complete how to restrict results by previous drop down
Hi I have a select field on a form which contains countries. The next field is a text box which is driven by an autocomplete function. The autocomplete function returns cities from a database table.

I want to restrict the cities that the autocomplete will return based on the country value selected in the dropdown. How do I do this?

if it helps here is my form

```
 $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            '#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
    );
$form['officename'] = array(
    '#type'=>'textfield',
    '#title'=> t('Location'),
    '#default_value'=>$form_state['officename'],
    '#size'=>20,
    '#maxlength' => 50,
    '#description' => t('Select the country where you want to pick up the car'),
    '#attributes' => null,
    '#required' => TRUE,
            '#autocomplete_path'=>'location-autocomplete'
);

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
);

```

and here is my autocomplete function. I want to restrict the sql with a where country = {country selected in Drop Down List}

```
function location_autocomplete($string){
$matches = array();
$result = db_query("select officename from {holidayautos_country_list} where officename like :keyword limit 0, 10", array(':keyword'=>"%" . db_like($string) . "%"));
 foreach($result as $row) {
    $matches[$row->officename] = check_plain($row->officename);
  }
drupal_json_output($matches);
}

```

Many Thanks Simon

# Answer
> 1 votes
Using the links suggested from Anil Sagar, I put together this solution using Ajax.

```
function HolidayAutosXML_carsearch_form($node, &$form_state) {
  $country_list = _get_country_list();
  $form['country'] = array(
    '#type' => 'select',
    '#title' => 'Select Country',
    '#description' => 'Select the country where you want to collect the car',
    '#options' => $country_list,
    '#ajax' => array(
      'callback' => 'update_officename_autocomplete',
      'wrapper' => 'haofficename',
    ),
  );

  $form['officename'] = array(
'#type' => 'textfield',
'#title' => t('Location'),
'#default_value' => $form_state['office name'],
'#size' => 20,
'#maxlength' => 50,
'#description' => t('Select the location where you want to pick up the car'),
'#attributes' => NULL,
'#required' => TRUE,
    '#autocomplete_path' => 'location-autocomplete',
    '#prefix' => '<div id="haofficename">',
    '#suffix' => '</div>',
  );

  if (!empty($form_state['values']['country'])) {
    $form['officename']['#autocomplete_path'] = "location-autocomplete/{$form_state['values']['country']}";
  }

  $form['submit'] = array(
    '#type'=>'submit',
    '#value'=>'Search Now',
    '#submit'=>array('HolidayAutosXML_carsearch_form_submit'),
  );

  return $form;
}

```
1. I added an Ajax element to the country drop down, telling it to look for a `<div>` with an ID equal to "haofficename" and calling a function named `update_officename_autocomplete()`.
2. I used a prefix and suffix element in the office name element to wrap it in a `<div>` element with the ID haofficename, which Ajax is going to look for.
3. `update_officename_autocomplete()` simply returns the altered office name element of the form. if you look inside the if statement you will see that it is adding to the `#autocomplete_path` property. So I had to add a second parameter to my autocomplete function. This function now takes `$country` and `$officename`.

function location\_autocomplete($country,$string){ $matches = array(); $result = db\_query("select officename from {holidayautos\_country\_list} where officename like :keyword and country = :country limit 0, 10", array(':keyword'=\>"%" . db\_like($string) . "%",':country'=\>$country)); foreach($result as $row) { $matches\[$row-\>officename\] = check\_plain($row-\>officename); } drupal\_json\_output($matches); }

It works like a charm.

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


# Question
Title: What is wrong with this schema definition and db query?
Hello and thank you for your time to help me in this weird case. I have a schema API function that returns few database table information, and everything seem to work fine... except the most simple table.

```
$schema['quotes_key'] = array(
  'description' => 'Auth keys for quotes',
  'fields' => array(
      'qid' => array(
        'description' => 'The {quotes} this key belongs to.',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'key' => array(
        'description' => 'Key of the qid to be accessed anonymously.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
    ),
    'primary key' => array('qid'),
    'indexes' => array(
      'qid'        => array('qid'),
    ),
  );

```

Then, I use drupal\_write\_record to write a new object to the database.

```
$key = new stdClass();
$key->qid = 789;
$key->key = md5(uniqid());
drupal_write_record('quotes_key', $key);

```

Whenever I run this code, I'm getting a mysql error:

```
user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES (789, '02ab38a849e02744f532cdf3137df146')' at line 1 query: INSERT INTO quotes_key (qid, key) VALUES (1, '02ab38a849e02744f532cdf3137df146') in .../includes/common.inc on line 3576.

```

Can anyone kindly help me to figure out the problem ? I tried db\_query to do the same database INSERT but getting same error. So I guess the problem is with my schema. the qid is stored in a {quote} table.

I tried reinstalling schema by drupal\_uninstall\_schema() and drupal\_install\_schema()

Thank you.

# Answer
I believe `key` is a reserved word. I'd stray away from using the key instead of trying to get MySQL to accept it. But here's some examples on how to get around it (which might not be possible via Drupal's db api).

https://stackoverflow.com/questions/2889871/how-do-i-escape-reserved-words-used-as-column-names-mysql-create-table
> 3 votes

---
Tags: 6, database
---


# Question
Title: Filter a view basing on a user attribute
I'm building a Drupal 7 site with a content type for events, and a view that displays a calendar of upcoming events. Events can be at one of two locations, and each user is also associated with one of the two locations. I'd like to set the calendar up so that the user only sees events for their location.

I tried doing this by creating a custom field on user profiles for location. However, I can't figure out how to use that field to filter the events on the calendar. It doesn't show up as an available value for contextual filters. Is there a way to do this?

Another option would be to make user location into a role, and then use role permissions to show the user one of two location-specific calendars. But this doesn't seem like what roles were really intended for.

Could I get some advice on an efficient way to do this? Events and user accounts are created by an administrator, and users don't need to be able to edit their location.

# Answer
> 1 votes
Finally I found an answer, described in detail on \[SOLVED\] Views - Filtering nodes by current user profile field, in the comment by Itangalo.

> * Create a user view.
> * Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will give you exactly one user object in your view -- the logged in user.)
> * Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the "interest" term for the logged in user.
> * Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes marked with the interest term for the logged in user.
> * Either set the view to display node teasers, or select a number of fields to display.
> * Add a display as usual. Done!

Confusingly, it starts with creating a view to display users. You can then create a relationship to bring in information about the custom user field, and a second relationship to find nodes that share that field value. I tried this and it worked for me!

A more straightforward method is described a few comments earlier, but I haven't tried that one.

---
Tags: 7, views
---


# Question
Title: How to make nodes to be aware that they were added to menu programatically
I'm adding nodes to menu programatically by custom PHP snippet in Rules. The problem is that nodes aren't aware of this - so the option "Provide a menu link" is unchecked in them, even if their menu-item exists. I cannot find anything relevant in $node object. How to fix this?

My code is:

```
$node_path = "node/" . $node->nid;
$node_alias = drupal_get_path_alias($node_path);
$menu = menu_load_links('main-menu');

foreach($menu as $key=>$value) {
    if($node_alias == $menu[$key]['link_path'] || $node_path == $menu[$key]['link_path']) {
        return;
    }
    if($menu[$key]['link_title'] == $node->field_rok['und'][0]['value'] && $menu[$key]['link_path'] == "<nolink>") {
        $menu_year = $menu[$key]['mlid'];
    }
    if($menu[$key]['link_path'] == "archiwum") {
        $archiwum_plid = $menu[$key]['mlid'];
    }
}

if(!isset($archiwum_plid)) {
    return;
}

if(!isset($menu_year)) {
    $item = array(
        'link_path' => '<nolink>',
        'link_title' => $node->field_rok['und'][0]['value'],
        'menu_name' => 'main-menu',
        'plid' => $archiwum_plid,
        'hidden' => 0,
    );
    // menu_edit_item_validate(array(), $item); Drupal doesn't recognize this function in this place (Rules), don't know why... :/
    $menu_year = menu_link_save($item);
}

$item = array(
    'link_path' => $node_alias,
    'link_title' => $node->field_numer_w_roku['und'][0]['value'] . '/' . $node->field_rok['und'][0]['value'] .' (' . $node->field_numer['und'][0]['value'] . ')',
    'menu_name' => 'main-menu',
    'plid' => $menu_year,
    'hidden' => 0,
);

// menu_edit_item_validate(array(), $item);
menu_link_save($item);

menu_rebuild();

```

# Answer
> 1 votes
Got it - I had to use drupal\_get\_normal\_path($node\_alias) on path added to menu. I hope that will be helpful for someone.

---
Tags: 7, routes, rules
---


# Question
Title: Fetch user id on behalf of the non-drupal php
I want simply to provide user id to php application that resides under my files/ folder. It is php that one flash app uses to create xml. This script, in my drupal root folder, works:

```
<?php
define('DRUPAL_ROOT', getcwd());
require_once '/var/www/drupal/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$user_uid= $user->uid;
echo $user_uid;
?>

```

but when i try to include whole script in that php app in my files folder, it fails, with many include type errors.

I am searching for simple solution to provide that app with user id!

Thanks!

# Answer
If you copy that code/file to another directory, DRUPAL\_ROOT will be set to that directory, not that of drupal's... so I'd change up that first define to point to where drupal is and you *should* be all set.
> 1 votes

# Answer
To those interested, i could not in any way accomplish what i wanted, i ended up by setting the cookie. In page.tpl.php:

```
setcookie("uid", $user->uid,  time()+(60*60*24*30));

```

In php app out of the drupal bootstrap:

```
if (isset($_COOKIE['uid'])) {
$user_uid=$_COOKIE['uid'];
}

```
> 0 votes

---
Tags: users
---


title: Completely empty page

text:
# Question
Title: Completely empty page
I need to create a page which is completely empty (no HTML returned at all). I need this for a POST callback (when using jEditable). I would like to still have access to the global variables (such as `$user`) and the modules that I have installed as I have a module installed which lets me access my REST service.

However, even though there should be not HTML returned per default, I should be able to return a string.

Does anyone know of a way to do this?

# Answer
You can do that through a custom module - create a path and instead of returning the output, just print it.

Here's an example:

```
/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items = array();
  $items['custom-url'] = array(
    'page callback' => 'YOURMODULE_blank_page_callback',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Display the content for your blank page.
 */
function YOURMODULE_blank_page_callback() {
  print 'Your string.';
}

```
> 12 votes

---
Tags: 7
---


title: Context - no reaction

text:
# Question
Title: Context - no reaction
I just installed context 3 on my drupal 6 site. I updated ctools to latest version (1.9) as suggested. Everything looks fine and I can enter conditions and reactions. The problem is that nothing happens. I see no reaction at all on the behavior of my site. Any hits to where I should start looking for the source of the problem?

# Answer
Start with a sanity check - make sure your rules "make sense" and that you set them up correctly. Try to apply the same context rules on a clean install.

If it works there and not in your existing site (with content, other modules and customized configuration), clone that site and try disabling modules one by one to see where the conflict is. It's hardly possible to say where the problem is without knowing any details about your existing installation.
> 0 votes

---
Tags: 7
---


# Question
Title: Content type permissions are not working
I'm trying to give users permission to edit certain content types, but it's not working. I'm having trouble tracking down which module could be the culprit. (I've used a couple of beta modules)

How should I go about tracking down this problem?

# Answer
make sure you have proper permissions assigned.Try rebuilding the site permissions.

If it still does not work try disabling individual permission based modules and rebuild site permission each time you do so and check.

You can also try using the devel node access module which gives a block which is placed below each content.
> 1 votes

---
Tags: 7
---


# Question
Title: Long time to load the edit page for any node?
I have a rare issue in a site. Every works fine but if I hit the edit link for any node it takes a very long time (about 1 minute), then the page is loaded correctly.

This only happens when editing a node.

How can I spot the problem?

# Answer
Install Devel module, enable it, go to: `admin/config/development/devel`, check "Display query log", "Display page timer" and "Display memory usage" and analyze the results displayed at the bottom of the page.
> 3 votes

---
Tags: nodes
---


# Question
Title: How to get a value from block configuration's form control?
I'm new to drupal stackexchange and drupal too.

I have made an example module that creates a block called "example". I added a textfield form control to the "example" block's configuration page using the `hook_block_configuration` hook function. Now I'm trying to get the value from the block configuration's form control in my `hook_block_view` hook function.

Here is what I have so far:

```
function example_block_info() {

    $blocks = array();

    $blocks['example'] = array(
        'info' => t('example'),
    );

    return $blocks;

}// end function

function example_block_configuration($delta = '') {

    $form = array();

    switch($delta) {

        case 'example' :

        $form['text'] = array(
          '#type' => 'textfield',
          '#title' => t('Text'),
          '#default_value' => '',
          '#size' => 50,
          '#maxlength' => 100,
          '#required' => true,
        );

    }// end function

    return $form;

}// end function

function example_block_view($delta) {

    $block = array();

    switch($delta) {

        case 'example' :
            $block['content'] = get_block_content(),
            break;

    }// end switch

    return $block;

}// end function

function get_block_content() {

    return /* textfield form control value */

}// end function

```

I figured I have to use the `hook_block_save` hook function to get the value from the '$edit' argument and store it somehow, but I'm not show how, or if that's the correct way to go about it.

```
function example_block_save($delta = '', $edit = array()) {

    switch($delta) {

        case 'example' :

            $edit['text'];

            break;

    }// end switch

}// end function

```

# Answer
What you need is completely covered in example module: block\_example.module

Have a look at following hooks:

1. block\_example\_block\_configure
2. block\_example\_block\_save
3. block\_example\_block\_view
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: Thumbnail: i need to have a fixed width and variable height (in proportion)
I need to fix the width of the thumbnail at 200px, while the height has to be resized proportionally; i've seen that i can fix the width x height for thumbnails, but need to set only one dimension....how can i do it?

# Answer
From the image styles settings for the "Scale" action:

> Scaling will maintain the aspect-ratio of the original image. If only a single dimension is specified, the other dimension will be calculated.

So if you specify just the width to 200px, the height will be calculated while maintaining the aspect ratio of the original image.
> 5 votes

---
Tags: 7, media
---


title: How to disable caching of a block?

text:
# Question
Title: How to disable caching of a block?
Although in Performance, the Block caching is disabled but I've a block created by Clock module(http://drupal.org/project/clock) when accessed as anonymous user it does not update the clock on every page reload.

I've even tried clearning browser cache but it works fine when logged in. For registered users it seems block caching is disabled.

The Clock block is there in this site: http://bit.ly/PKI2M8 \- please scroll to bottom-most right block titled 'Rail Time'.

How can I disable caching of this block?

# Answer
As MPD pointed out, page caching is your problem. Even with block caching disabled, the whole rendered page will be cached with page caching on, which includes any blocks no matter whether block caching is disabled or not.

As far as I know that leaves you with at least the following options:

1. Take the easy route, and just disable page caching.
2. Use JavasSript to set or update the time client side, you would still need an initial time source though, perhaps as outlined here.
3. As a much larger project you could see how authcache works for serving it's blocks of user specific non-cached content while the majority of the page is cached, and implement it for anonymous users for just the time block.
4. Use an iframe and get the contents from somewhere it isn't cached.
5. There are probably more ways...
> 1 votes

---
Tags: 6, caching
---


title: Drupal Errors after Installation

text:
# Question
Title: Drupal Errors after Installation
I'm new to drupal, and just trying to get it up and running smoothly.

I installed it manually on my *Go Daddy* account, but I'm getting these errors when I click on the customization links at the top of the screen:

I can still do things (add content, etc.) but since I'm new, I have no idea if there is anything not being shown to me because of these errors. I just did a fresh install and I'm still having the same problems. Any ideas?

# Answer
From the screenshots I could see that you are using acquia marina theme, and these errors are related to that theme.

Please make sure that, you installed/configured the theme properly.

Related issue in acquia marina theme issue queue - http://drupal.org/node/1057002
> 1 votes

---
Tags: 7, installation
---


title: Passing contexual filters

text:
# Question
Title: Passing contexual filters
I am creating a view in drupal 7 here is attached screenshot

Here

And preview of this Screen Shot is or output of this view is

Which is working fine .

Now when i try to pass contextual filter see

Named Edmonton it shows following result

And Result is not correct

It must show only filter with edmonton name

Any Body has idea what is the problem? Thanks in Advance.

# Answer
> 0 votes
I think the implementation has some issues. The first contextual filter that you have added is date, right and when you are passing an argument, it's not a date. Is that a username? If so then you need to use proper contextual filer. You have a filter as "Add Property View" and also the same in Contextual Filer.

---
Tags: 7, views
---


# Question
Title: using drush php-eval db_query() are there differences with db_query() from code?
I think the answer should be easy but I can't find it.

maybe I've been put in the wrong direction finding sites telling how to clear my flood table like so:

```
drush php-eval 'db_query("DELETE FROM `flood`");'

```

But I think is should be like this so it also works for prefixed tables:

```
drush php-eval 'db_query("DELETE FROM `{flood}`");'

```

Or does db\_query() works different in drush php-eval? As far as I know it just executes php but does it has the drupal 'library' available or not?

Now I could just try and see what happens but I think it's good to really know if there's a difference or not in running db\_query() from drush or from code.

# Answer
I don't know this for definite but conceptually speaking, if Drush *didn't* use a standard Drupal bootstrap to perform these tasks it would have to re-implement all of that functionality itself.

Drush uses your site's settings.php file for the database connection, which leads me to believe it will also have access to things like `$db_prefix`.

I think it's safe to say exactly the same thing is happening when you run `db_query()` from Drush as if you run it from any other bootstrapped instance of Drupal.
> 1 votes

---
Tags: 7, drush, database
---


title: Adding CCK field to solr index

text:
# Question
Title: Adding CCK field to solr index
We have a cck field called "keywords". We need to add this field to the solr index so we can search on it from outside of drupal. How are CCK fields managed in the solr index?

UPDATE:

I created a module "apachesolr\_search\_additions" and the following function:

```
<?php
function apachesolr_search_additions_apachesolr_update_index(&$document, $node)
{
  if (isset($node->field_keywords_raw) && !empty($node->field_keywords_raw))
  {
    $document->addField('sm_keywords', $node->field_keywords_raw[0]['value'], '2.0');
  }
}

```

I then ran cron and went to: admin/reports/apachesolr

it does NOT show the field name in the search index. How can I verify it is in the index?

# Answer
Adding Custom Fields to Apache Solr Search Results appears to have the instructions.

> To do this, we will use the two hooks used in the last example: hook\_apachesolr\_update\_index() and hook\_apachesolr\_modify\_query(). To start, we need to add the data to the Solr index.

Modified the code to work with a field\_keywords\_field (note: field\_keywords\_field\[0\]\['value'\] is what I'm using, you may need to debug this if your keyword field is multi-value or something)

```
/**
* Implementation of hook_apachesolr_update_index()
*/
function mymodule_apachesolr_update_index(&$document, $node) {
  // Index field_keywords_field as a separate field
  if (isset($node->field_keywords_field) && !empty($node->field_keywords_field)) {
    // addField($key, $value, $boost), change $boost to give this field a higher score
    $document->addField('sm_field_keywords_field', $node->field_keywords_field[0]['value'], '2.0');
  }
}

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',sm_field_keywords_field';
}

```
> 0 votes

# Answer
As an answer to your update: You can use the luke request handler most likely present in your solr configuration.

For a solr setup running on the built-in Jetty container, the default address for a single-core solution is `http://localhost:8983/solr/admin/luke` but that varies according to whether your solr actually is on the localhost and whether you have a multi-core setup. Adjust accordingly.

That output will show you all the fields, their statistics and more. By default, the output is xml.
> 0 votes

---
Tags: 6, search
---


title: Override views_exposed_form

text:
# Question
Title: Override views_exposed_form
I have a content type called Events. I would like to override the tpl file of exposed form in events listing.

I tried events\_preprocess\_views\_exposed\_form to add a template suggestion, I tried to add MYTHEME\_preprocess\_views\_exposed\_form to do the same thing, I tried simply to add views-exposed-form.tpl.php in my templates directory from MYTHEME directory but with no success.

# Answer
From your question, I could understand that you're using views to show your events list with exposed filters and now you want to override the template of that exposed form.

To override the exposed form template for a particular view, you need to create a template in the following name pattern,

**views-exposed-form--view\_name.tpl.php**

For example if your view name is event\_list, then the overridden template will be views-exposed-form--event\_list.tpl.php.

Once you added the template clear the cache, now view will use the overridden template for exposed form.

Take the views default exposed form template as base to theme your overridden template - Exposed form template

Note : To just override the template, you do not need any preprocess functions.
> 4 votes

---
Tags: 7, views
---


title: Creating posts linked to map

text:
# Question
Title: Creating posts linked to map
I want to create a map where on clicking on a certain location ,a user can find all the content/nodes/posts related to that location. ( Something like http://42floors.com/ )

Is it possible to build it using drupal? Can you suggest some modules that will be useful for this purpose? Thanks. :)

# Answer
location

gmap

views

With these three drupal modules you can easily create a map which will display all nodes with location details.
> 1 votes

---
Tags: 7, google-maps, javascript, location
---


title: Removal of Node Reference, Drupal 6

text:
# Question
Title: Removal of Node Reference, Drupal 6
Ok, trying to process a script, both PHP and JavaScript, where I am moving a particular content type NODE from one reference to another. This is the structure:

I have a PROJECT Inside each PROJECT are PAGES Inside each PAGE are CALLOUTS and Inside each CALLOUT are PRODUCTS.

What I want to do is take a PRODUCT from one CALLOUT to another CALLOUT. I am able to merge these, but now what I want to do is delete the first instance. An example:

I have PRODUCT AAG-794200 that is on PAGE 6 CALLOUT A. I am merging that PRODUCT with PAGE 6 CALLOUT B.

I can get the product to merge, but now I need to remove it from CALLOUT A. Here is my code:

```
$merge = explode(',', $merge); //Merge SKUs
$mpages = explode(',', $mpages); //Merge Pages
$mcallouts = explode(',', $mcallouts); //Merge Callouts
$mcallout_nid = explode(',', $mcallout_nid);  //Merge Current callout

$length = count($merge);
$e = 0;
while ($e < $length) {
    //Where is the SKU going to?
    $to_callout_letter = strtoupper($mcallouts[$e]);
    $to_page_num = $mpages[$e];
    $sku = $merge[$e];
    $from_callout = $mcallout_nid[$e];

    //Where is the SKU coming from?
    $other_callout = node_load($from_callout);

    //Need page ID of current callout for project purposes
    $page_nid = $other_callout->field_page[0]['nid'];
    $page = node_load($page_nid);
    //Need the project NID
    $project_nid = $page->field_project[0]['nid'];

    //We need to get the NID of the page we are going to
    $page_nid = db_query('SELECT * FROM content_type_page WHERE field_page_order_value = "%d" and field_project_nid = "%d" ORDER BY vid DESC LIMIT 1', $to_page_num, $project_nid);

    $page_nid_res = db_fetch_array($page_nid);
    $to_page_nid = $page_nid_res['nid'];

    //We need to get the NID of the callout here
    $co_nid = db_query('SELECT * FROM content_type_callout WHERE field_identifier_value = "%s" and field_page_nid = "%d"', $to_callout_letter, $to_page_nid);
    $co_nid_res = db_fetch_array($co_nid);
    $to_callout_letter_nid = $co_nid_res['nid'];

    $callout = node_load($to_callout_letter_nid);
    $long = count($other_callout->field_skus);
    $deletecallout = array();
    foreach($other_callout->field_skus as $skus) {
        $s = 0;
        while ($s < $long) {
            if($skus['nid'] == $sku) {
                $callout->field_skus[] = $skus;
                $s++;
            }
            else {
                $deletecallout[] = $skus;
                $s++;
            }
        }
    }

    foreach($other_callout->field_images as $old_image) {
        $callout->field_images[] = $old_image;
    }
    foreach($other_callout->field_line_art as $old_image) {
        $callout->field_line_art[] = $old_image;
    }
    foreach($other_callout->field_swatches as $old_image) {
        $callout->field_swatches[] = $old_image;
    }

    $callout->field_copy_text[0]['value'] .= $other_callout->field_copy_text[0]['value'];
    $callout->field_notes[0]['value'] .= $other_callout->field_notes[0]['value'];
    $callout->field_image_notes[0]['value'] .= $other_callout->field_image_notes[0]['value'];
    $callout->field_status[0]['value'] = 'In Process';
    node_save($callout);

```

This causes the PRODUCTS to MERGE, but not delete the original.

Thanks for any help. I know it's something simple, and it will be a palm-to-face moment.

# Answer
So the answer to this was easier than I thought. I loaded the $other\_callout node, and then unset the $key, utilizing the following code:

```
foreach($other_callout->field_skus as $key=>$value) {
if($value['nid'] == $sku) {
        $sku_rec = $value;
        $sku_rec_key = $key;
    continue;
    }
}

unset($other_callout->field_skus[$sku_rec_key]);

node_save($other_callout);

```

Thanks for the help guys, I appreciate it.

Drupal on.
> 0 votes

---
Tags: 6, entities
---


# Question
Title: Menu is not highlighted when viewing its corresponding page
I'm using D7. In it, one of the menu in left sidebar is not highlighted when viewing its corresponding page.

Case 1 : If I gave the path to the menu link as `node/15`, it is highlighted but the anonymous user can't see the menu at all.

Case 2: If the path will be www.sitename.com/blah/blahbla means its not highlighted and the anonymous user can see this menu.

Since that page is not to be accessible by anonymous user, hence this problem? Can any one help me to get rid of this?

# Answer
> 0 votes
I put a condition for that node and added the style for the menu in the page.tpl.I don't know is this is the right solution.But it worked for me.

---
Tags: 7, routes
---


title: Robots.txt and language exclusion

text:
# Question
Title: Robots.txt and language exclusion
I want to add a language on my drupal 6 site but I want that Google doesn't index every page in this language (fr).

Can I use robots.txt and and add something like this?

```
Disallow: /fr/*

```

# Answer
Drupal by default comes with robots.txt file. You can find the file in Drupal Root.

Yes, you can go ahead and change. Below code also should work.

```
Disallow: /fr/

```

But, if you use

```
Disallow: /fr/*

```

As per wikipedia

> Universal * match The Robot Exclusion Standard does not mention anything about the * character in the Disallow: statement. Some crawlers like Googlebot and Slurp recognize strings containing \*, while MSNbot and Teoma interpret it in different ways.
> 2 votes

---
Tags: 6
---


# Question
Title: Dont want horizontal scroll bar for views
I am using a view called "exhibit" with multiple fields. I am getting a horizontal scroll bar since the view have multiple fields. But I don't want the horizontal scroll bar.

How can I achieve this.

# Answer
> 0 votes
You can use css like this:

```
overflow-y: scroll;
overflow-x: hidden;

```

---
Tags: 7, views
---


# Question
Title: The username has not been activated or is blocked. using custom login form
In my module tpl file I'm calling

`<?php print drupal_render(drupal_get_form('mymodule_login_form')); ?>`

Then in my .module file I have this function:

```
function mymodule_login_form($form, &$form_state){
  $form = drupal_get_form('user_login');
  return $form;
}

```

So the user\_login form gets called and shows up but when I try to use it ( submit it ) I'm always getting the error message: `'The username has not been activated or is blocked.'`

When I change the tpl file to: `<?php print drupal_render(drupal_get_form('user_login')); ?>` it works and giving the correct error messages or logs the user in.

The problem with this is that I'm using it in a popup screen and want to display the error messages in the popup screen using ajax. So I need to alter the user\_login form. I know how to do that but I'm not getting past the error message `'The username has not been activated or is blocked.'`

# Answer
Is there other code going on in mymodule\_login\_form()? Could you post the full copy/paste of that function? You mentioned that you were altering the form...

Secondly, is there a reason why this alteration couldn't be done using hook\_form\_alter()? That would be the normal method of altering an existing form.

The error message you are getting will be coming from this function:

`user_login_name_validate`

Can you think of anything in your code that might be altering the form such that it falls into the if statement contained in that function?
> 1 votes

# Answer
If your requirement is displaying user login form in AJAX POPUP then you can consider Ajax Login/Register module.

* This module provides a block with 2 links (Login, Register) for the anonymous user.
* When the user clicks on Login or register the requested form appears in a nice ajax popup.
> 1 votes

---
Tags: forms, users, theming
---


# Question
Title: Best option to upgrade Drupal 6 Video field to Drupal 7
I'm trying to update a Drupal 6 site to Drupal 7.

I'm trying to move a video CCK field to Drupal 7. If I try to move to a video field, I get a message telling me there is not way to migrate.

How can I upgrade Video from 6.5.2 to Drupal 7.2.7?

# Answer
> 1 votes
For the video module there is no any direct migrate path even though it is CCK field, so what you have to do is use Migrate module. Just create a Views that output all the videos as XML in D6 site and use that XML input in D7 site to create new video nodes. This may need some additional effort but ultimately this will be really smooth approach.

---
Tags: 7, files
---


# Question
Title: Online streaming and on air/broadcast function for a Drupal website
I'm trying to figure out how to build a website for a tv using Drupal.

Going around the web I found different modules and Videola distribution.

About the Videola distribution, I have not find any tutorial or something close to it.

I've found Kaltura , Live Streaming and VideoWhisper

has anyone here got experience with these modules?

Thanks in advance.

# Answer
> 2 votes
Octopusvideo might suite for your requirement, this is in D7 and have lot of functionality.

---
Tags: media
---


# Question
Title: How to display Views exposed filters fields as a table?
I would like to display Views "Exposed filters" fields as a regular **table**, where the first column would be the field label, and the second column would be the field options/select lists.

So for example from this:

I would like to create this:

What is a possible solution for this?

# Answer
It's easier than I expected.

How-to steps:

1. Copy `views-exposed-form.tpl.php` (http://pastebin.com/V77CPxPG) from the Views module's `views/theme` directory to your own theme's `templates` directory (but some themes have their template files in their root directory! (or maybe even other directories like `theme` or sg. else)).
2. Copy ANOTHER instance of this file to the same directory, BUT now name it so that it also contains the particular view's machine name *after two dashes*:

```
views-exposed-form--page_test_ct.tpl.php

```

(like it's explained here; you should give a unique machine name to your view!)
So in my example, the machine name of the view is `page_test_ct`, like you can see it here:
3. Modify `views-exposed-form--page_test_ct.tpl.php` like this:
http://pastebin.com/1qfim7VX
4. Clear cache (theme registry).

---

# SCREENSHOTS

## BEFORE

## AFTER

## AFTER; having some exposed operators and descriptions too
> 2 votes

---
Tags: theming, views
---


# Question
Title: hook_theme, custom data, passing to custom TPL file
I am having trouble passing custom data through theme() to a custom callback and passing the data through to a tpl file. Here is my code:

hook\_theme:

```
function satb_schedule_theme() {
  return array(
    'satb_schedule_brackets' => array(
      'render element' => 'bracket',
      'variables' => array('bracket' => array()),
      'template' => 'satb_schedule_brackets',
      'path' => drupal_get_path('module', 'satb_schedule') . '/templates',
    )
  );
}

```

hook\_menu item:

```
$items['tournaments/%/%/schedule/winner-bracket'] = array(
    'title' => 'Winner Bracket',
    'description' => 'View the winner brackets for this tournament.',
    'page callback' => 'satb_schedule_generate_bracket',
    'page arguments' => array(1, 2, '0'),
    'weight' => -16,
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('view tournament brackets'),
  );

```

hook\_menu item callback (satb\_schedule\_generate\_bracket):

```
function satb_schedule_generate_bracket($nid, $product_id, $bracket_type) {
  $schedule = new SATBScheduleDisplay(array('nid' => $nid, 'product_id' => $product_id));
  return $schedule->getTournamentBracket($bracket_type);
}

```

This function generates an array of data. Inside of the method, data is gathered and returned through theme(), like so:

```
$output = theme('satb_schedule_brackets', array('bracket' => $brackets));
return $output;

```

In the template.php, I have this to modify and add variables for the template:

```
function satb_preprocess_satb_schedule_brackets($variables) {
  $brackets = $variables['bracket'];

  foreach($brackets as $key => $round) {
    switch ($key) {
      case 3:
        $classes = array('round', 'quarterfinal');
        $round_title = t('Quarter Finals');
        break;
      case 2:
        $classes = array('round', 'semifinal');
        $round_title = t('Semi-Finals');
        break;
      case 1:
        $classes = array('round', 'final');
        $round_title = t('Final');
        break;
      default:
        $classes = array('round');
        $round_title = t('Round @round_number', array('@round_number' => $key));
        break;
    }

    $variables['bracket'][$key]['data'] = array('classes' => implode(' ', $classes), 'round-title' => $round_title);
  }

  $vars['bracket'] = $variables['bracket'];
  $vars['tournament_title'] = 'Just a test';
  return $vars;
}

```

My custom tpl is loaded (I can see the static HTML in there as a test and print static vars) however, my modifications don't seem to get passed to the template.

For example, if I do print $tournament\_name;, its null. If I do print $bracket\['tournament\_title'\]- it appears, but I don't want to access variables like that because that's messy, and, it should respect the vars I am adding to the vars array.

What am I missing here? The classes and titles I am adding in the preprocess are also missing in the $bracket element in the TPL. The $vars has them, but the TPL does not.

# Answer
> 2 votes
Doh. $variables is passed by reference. I always forget this in template.php:

function satb\_preprocess\_satb\_schedule\_brackets(**&**$variables) {

---
Tags: 7, hooks, theming
---


# Question
Title: Why all dates columns in drupal are type=int and not type=date/timestamp/time?
I want to make this question short, so as title says "Why all dates in drupal are INT" ?

I've notice that in Schema API there was "datetime" but it was removed in D7. Also all tables that have time in it (cache\_\*,semaphore,node etc.) have INT instead of TIMESTAMP.

Before debating "INT vs TIMESTAMP" flame, I would like to remind you that:

* DATETIME is obvious what the value represents.
* INT is smaller
* TIMESTAMP has both advantages.

The thing is that I want to understand what's "philosophy of drupal" for this.

# Answer
I guess the main reason its that you cannot have two columns with TIMESTAMP and default NOW() value in MySQL according the documentation (see that answer). So seems to be the easier way to workaround it its to use int.
> 2 votes

---
Tags: database
---


title: Domain Access Database prefix

text:
# Question
Title: Domain Access Database prefix
I am on D7.x

I have not quite figured out how to solve the table prefix problem that was solved with domain access table prefix in the 6.x branch.

I know that I will need separate caching tables for instance, but I'm not quite sure how to allow the table prefixing when everything is based off the same settings.php file.

Thanks for your help.

# Answer
> 0 votes
I figured this out by making decisions in the settings.php file. I have a switch statement that gets the url and then sets a table prefix variable and then that determines the db name, the db password and the prefix. The default is to share everything if something is not found.

---
Tags: domain-access
---


# Question
Title: Filter the nodes by language output by the view
Before I have i18n module and some modules that does the translations but we decided to stop doing translation but still preserve the translated nodes.

After disabling translation modules my views which are using **content negotiation** says "Broken/Invalid handler" so I removed this filter.

Now all the views are using nodequeue which has a bunch of multilingual nodes.

My question is, how can I filter views to display nodes based on page language. I mean I want to display english articles only when I'm in English pages, korean articles when viewing Korean pages, japanese articles when viewing Japanese pages, etc.

Ex. nodes(eng) for English pages, nodes(korean) for Korean pages, nodes(japanese) for Japanese pages, and nodes(chinese) when in Chinese pages

# Answer
one work around is to re-enable the i18n module, to access the filter again, then use some hooks ( like hook\_form) to hide and set the default values for the i18n options in the node form if you want to remove those options from the user interface.
> 0 votes

---
Tags: views
---


# Question
Title: In a view, how can I display all sub categories of a given taxonomy term with content from each sub category?
For each article, I assign a 'sub-category' taxonomy vocabulary term. Then for each 'sub-category' taxonomy term, it links to a 'category' taxonomy vocabulary term.

I have set up a variant of the taxonomy-term template page that passes the category ID as an argument to a view. This view then uses a contextual filter to display all content within all sub-categories for the given category ID.

To illustrate, say you type in sitename.com/taxonomy/term/1922 which is, say, movies. The view will display all content marked with movies' sub categories. So it currently would show this:

```
/taxonomy/term/1922 (Movies)
Title         |      Sub-Category |
——————————————————————————————————-
Star Wars     |            Sci-Fi |
Star Trek II  |            Sci-Fi |
Home Alone    |            Comedy |
Office Space  |            Comedy |
Thin Red Line |               War |

```

What I want is to have, say, 5 pieces of content per sub-category titled by the sub-category. Something like this:

/taxonomy/term/1922 (Movies)

* Scifi:

1. Star Wars
    2. Star Trek II
    3. ...
    4. ...
    5. ...
* Comedy:

1. OFfice Space
    2. Home ALone
    3. ...
    4. ...
    5. ...

And so forth. So that it would title all sub-categories and show the top x number of nodes per sub-category.

# Answer
> 1 votes
This isn't a great answer, but after a couple days of trying to do this myself, the best I could figure out was to use Views Field View (I think that Views Grouping Row Limit would probably work too, but it's still in dev).

Create a basic node view that lists off your five movie node titles (along with any other teaser-like content you'd like), set your page to limit to five entries, and set the contextual filter to the movie's taxonomy term.

Then, make a view that shows taxonomies belonging to the vocabulary (movies). Set the contextual filter to "taxonomy term: parent term"), and output the tid (hidden) and term title. That'll make a list of your parent terms, so now add a views\_field\_view (set it to use your first view for input, and the tid for your argument).

Again, there's got to be a better way than this, as I'm sure it's going to create some real system overhead.

Pleeeease, someone come up with a better answer!

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


# Question
Title: Drupal 7 image styles ignored by theme preprocess function
I want to display images at the proper image style-defined size, but there's a problem being caused by a preprocess function written by the person who built this site before I came onto the project.

```
function abc_field__field_video_thumbnail($variables) {
    $output = '';

    // Render the items
    foreach ($variables['items'] as $item) {
        $output .= "<div class=\"field-item\">\r";
        $output .= '<a href="' . $movieurl . '" target="popup" data-popup-width="' . $variables['element']['#object']->field_video_width['und'][0]['value'] . '" data-popup-height="' . $variables['element']['#object']->field_video_height['und'][0]['value'] . '">';
        $output .= '<img src="' . file_create_url($item['#item']['uri']) . '" alt="" width="' . $item['#item']['width'] . '" height="' . $item['#item']['height'] . '" class="' . $item['#image_style'] . '">' . "\r";
        $output .= '<img src="/' . drupal_get_path('theme', 'nwe').'/images/button_play.png' . '" alt="Play Video" width="110" height="110" class="play-icon">' . "\r";
        $output .= "</a>\r\r";
        $output .= "</div>\r\r";
}

    // Render the top-level div
    $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

    return $output;
}

```

This seems to assume the image style processing would occur before this function happened, but unfortunately it doesn't, and I get a full-size image regardless of image style.

# Answer
By taking over the display of that field you're actually bypassing all the field system would usually do to apply the custom display settings; it basically passes off the responsibility of creating the field HTML to you, and provides you with the raw values you'll need to build it up.

So if you want to output a style based image, you'll need to do it manually using `theme_image_style()`:

```
$args = array('style_name' => 'thumbnail', 'path' => $item['#item']['uri'], 'alt' => 'Alt text');
$image = theme('image_style', $args);

// Append $image to your output...

```
> 2 votes

---
Tags: media
---


# Question
Title: How create form elements in form theme hook
I have a custom module with a from, form submit handler and for theme hook

In some case I need to create multiple form elements (textfields for example with name like "user\_input\_1"-"user\_input\_n")

What I did is change $form array in form theme hook and render new elements. But these elements are missing in the post and form submit processing form (even if shown on a page). I realize what it might be not appropriate way of creating new form elements in theme hook OR maybe there is something(function) what will allow me to properly prepare new form elements in theme hook on a fly.

Or maybe there is another way as I know how many elements do I need in submit processing function which rebuild the form and doing something like $form\_state\['storage'\]\['wizard\_step'\] = 'step3' (multi-step form). But I don't know drupal very well, just started..

Stuck and spend few hours trying to find appropriate way of solving this. Any help appreciated. Thanks

# Answer
> 0 votes
Answer is simple: form alter hook allows to manage form content on a fly

---
Tags: forms, theming
---


title: Entity reference no sorting by field

text:
# Question
Title: Entity reference no sorting by field
I have a problem that I have not been able to find the solution. I have an entity reference field for a node to display specific news I need them to be sort them by the date they were created by the latest. In the field settings there is an option to sort by created but it is not applying the sorting. Is there another way that I can sort them maybe using rules, or programatically. Any idea what I am doing wrong? I cannot use views for this particular problem because each node display different news, do it manually is not an option either because I am creating the content using web services.

NEWS ORDERED BY THE LATEST

September 12, 2012 lorem Ipsum is simply dummy text of the printing and typesetting industry.

June 12, 2012 lorem Ipsum is simply dummy text of the printing and typesetting industry.

May 12, 2012 lorem Ipsum is simply dummy text of the printing and typesetting industry.

# Answer
You can always use the `Views: Filter by an entity reference view` option from `Entity selection mode` and then create a view as per your sorting options and filters and select the view in the select box which shows up.
> 2 votes

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


title: Overriding Class Div Form-API

text:
# Question
Title: Overriding Class Div Form-API
Objective: To override the default classes and divs that are spit out from the Form-API from my custom addressfield implementation in a Drupal Commerce checkout pane. I need to make the classes/divs predictable based on the number of seperate address forms their are. I dynamically create (x) addressfields based on the number of gift subscriptions (x) so that I can combine address information for subscriptions.

Note: The addressfield form is a patch from the addressfield module which creates a form element type. This looks like this:

```
          $form['address'] = array(
          '#type' => 'addressfield',
          '#required' => TRUE,
          '#title' => t('Recipient\'s Address'),
          '#context' => array('countries' => array('AT', 'AS', 'BE', 'BG', 'CA', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'GU', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PR', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'GB', 'UM', 'US', 'VI'), ''),
          '#default_value' => array('country' => 'US'),
          '#description' => "Please enter the address you want to mail this gift to.",
          '#maxlength' => 60,
          );

```

However the problem arises when you load the page with the form. Drupal is dynamically creating numbers in the classes/divs that appears to be random. I would like to specify that number so that it conincedes with the number of subscriptions. So when i test i select (2) gift subscriptions and get and .

As opposed to the current way it does things (screenshot)

# Answer
> 1 votes
See line 398 of plugins/address.inc ? `$format['#wrapper_id'] = drupal_html_id('addressfield-wrapper');` That's the root of the seemingly arbitrary field identifier stuff. The code gets there from line 460 of addressfield.module `$element += addressfield_generate($address, $settings['format_handlers'], $context);`

Make a custom module, set the weight higher than that of addressfield so it runs after the addressfield module's hooks, and alter the form. There aren't hooks inviting you to alter those IDs unique to addressfield, and altering them in this case is no different than any other, so long as the module weight is adjusted.

# Answer
> 0 votes
If you are using 7, try hook\_page\_alter()

---
Tags: theming, forms
---


# Question
Title: DatabaseScheme Error when trying to install Jabber
PROBLEM: Got the following error when trying to install Jabber. This seems like a generic error. I have a feeling that the issue is similar to this post. I created a bug report so the maintainer can either help or include what ever fix comes from this.

> DatabaseSchemaObjectExistsException: Table jabber already exists. in DatabaseSchema-\>createTable() (line 657 of public\_html/d7/includes/database/schema.inc).

BACKGROUND: I have an OpenFire server running and was curious as to the integration with Drupal 7 and O.F. This post talks about the very same thing expect.. XMPP Framework Module is for D6. The alternative for D7 is Jabber.

I've tried both the DEV & BETA branches and both throw the same error on install. On uninstall of the module, there is another error but I've removed all entries into the DB for jabber myself.

If I try to goto the admin/settings/jabber page. It doesn't show up. Thus telling me it wasn't installed right.

How can I fix this error so the jabber module will install properly?

EDIT: After installing the DEV version. I just realized the Jabber settings page does show, although the previously mentioned error still pops. There are also additional errors but those are not relevant to this question.

# Answer
> 0 votes
Run database update then try reinstalling the module.

Also do keep backup of your database before running the update.

---
Tags: 7, database
---


# Question
Title: Drupal module save and retreive theme settings
I am creating a drupal module (my first) and I wish to simply store some variables.

I previousely did this by adding some form elements to the theme-settings.php file but now I want to have my own module.

I created my module and form and menu elements and that all seems to be fine. Problem is that nothing seems to be saving to the database. Or maybe is is saving but not retreiving.

This is what I have so far:

my\_module.module:

```
/**
 * @file
 * My Module Settings.
 */

/**
 * Implements hook_help().
 */
function mynewmodule_settings_help($path, $arg) {
  /* INFO:
   * The help hook is for displaying helpful messages at the top of pages indicated
   * by $section to further explain how they work. Adding certain "keywords" to the end of
   * a given path (like admin/modules#description) will cause this text to display elsewhere
   * in the page as well (in this case, in the description section for the given module).
   */
  switch ($path) {
    case 'admin/help#mynewmodule_settings':
      return t("TODO: Create admin help text for My Module.");
    case 'admin/config/system/mynewmodule':
      return t('My Module help text will go here.');
  }
}

/**
 * Implements hook_permission().
 */
function mynewmodule_settings_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer My Module Settings'),
    )
  );
}

/**
 * Implements hook_menu().
 */
function mynewmodule_settings_menu() {
  $items = array();
  $items['admin/config/system/mynewmodule'] = array(
    'title' => 'My Module Settings',
    'description' => 'Administer My Module Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mynewmodule_admin_settings'),
    'access arguments' => array('administer my module'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'mynewmodule_settings.admin.inc',
  );
  return $items;
}

```

And here is my form (mynewmodule\_settings.admin.inc):

```
// $Id$
/**
 * @file
 * My Module Settings
 *
 * @author Cybercampbell
 */

/**
 * Admin configuration form
 */
function mynewmodule_admin_settings() {

$form = array(
    '#type' => 'fieldset',
    '#title' => t('My Module Settings'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $form['breadcrumb'] = array(
    '#type' => 'fieldset',
    '#title' => t('Breadcrumb'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['breadcrumb']['breadcrumb_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show breadcrumb'),
    '#description'   => t('Use the checkbox to enable or disable Breadcrumb.'),
    '#default_value' => theme_get_setting('breadcrumb_display','mymodule'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

 /**
 * SOCIAL
 */

  $form['social'] = array(
    '#type' => 'fieldset',
    '#title' => t('Social Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  /**
 * FACEBOOK
 */
 $form['social']['facebook_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Facebook'),
    '#description'   => t('Use the checkbox to enable or disable the Facebook button.'),
    '#default_value' => theme_get_setting('facebook_display','mymodule'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['social']['facebook_id'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Facebook ID'),
    '#default_value' => theme_get_setting('facebook_id','mymodule'),
    '#size' => 32,
  );

/**
 * TWITTER
 */
   $form['social']['twitter_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('Twitter'),
    '#description'   => t('Use the checkbox to enable or disable the Twitter button.'),
    '#default_value' => theme_get_setting('twitter_display','mymodule'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['social']['twitter_id'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Twitter ID'),
    '#default_value' => theme_get_setting('twitter_id','mymodule'),
    '#size' => 32,
  );

  /**
 * RSS
 */
   $form['social']['rss_display'] = array(
    '#type' => 'checkbox',
    '#title' => t('RSS'),
    '#description'   => t('Use the checkbox to enable or disable the RSS button.'),
    '#default_value' => theme_get_setting('rss_display','mymodule'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  // Attach custom submit handler to the form
  $form['#submit'][] = 'mymodule_settings_submit';

  $print_footer_text = theme_get_setting('print_footer');
  $form['print_footer'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Footer Text'),
    '#rows'          => 5,
    '#resizable'    => FALSE,
    '#default_value' => !empty($print_footer_text['value']) ? $print_footer_text['value'] : '',
    '#format' => !empty($print_footer_text['format']) ? $print_footer_text['format'] : 'full_html',
  );

  return system_settings_form($form);
}

```

This code worked fine in the theme.settings.php file. Any ideas where i'm going wrong here?

# Answer
> 3 votes
The values entered in the form are saved, but not in the Drupal variable theme\_get\_setting() is looking for.

If you look at the code of the function, you will notice the following code:

```
// Get the saved global settings from the database.
$cache[$theme] = array_merge($cache[$theme], variable_get('theme_settings', array()));

if ($theme) {
  // Get the saved theme-specific settings from the database.
  $cache[$theme] = array_merge($cache[$theme], variable_get('theme_' . $theme . '_settings', array()));

  // If the theme does not support a particular feature, override the global
  // setting and set the value to NULL.
  if (!empty($theme_object->info['features'])) {
    foreach ($features as $feature) {
      if (!in_array($feature, $theme_object->info['features'])) {
        $cache[$theme]['toggle_' . $feature] = NULL;
      }
    }
  }

  // …

}

```

The Drupal variable used to save the theme settings is theme\_$theme\_settings (where `$theme` is the theme name). The form submission handler your code is using doesn't save the form values in that Drupal variable, and `theme_get_setting()` will not find them.

The other issue with your code is that it is not sharing any setting with the theme; for that to happen, the second parameter for `theme_get_setting()` should not get any argument. In fact, the second parameter is described as, "The name of a given theme; defaults to the current theme."

If you want to add settings that the currently enabled theme, or any module, would find with `theme_get_settings()`, you should implement hook\_form\_system\_theme\_settings\_alter(), which is an implementation of hook\_form\_FORM\_ID\_alter() for the form build from system\_theme\_settings(). The hook is particular because `system_theme_settings()` will look for the implementation of that hook done from the currently set theme, or the currently set theme engine.

If the settings are just for your module, and it doesn't need to be shared with other modules (or the current theme) via `theme_get_setting()`, then you can simply use `variable_get()`. In that case, you don't need to use a form submission handler that is different from the one set by system\_settings\_form().
See the code used from `system_theme_settings()`, which contains the following lines.

```
  $form = system_settings_form($form);
  // We don't want to call system_settings_form_submit(), so change #submit.
  array_pop($form['#submit']);
  $form['#submit'][] = 'system_theme_settings_submit';
  $form['#validate'][] = 'system_theme_settings_validate';
  return $form;

```

# Answer
> 2 votes
I think you should add the submit handler function for the `mynewmodule_admin_settings()` function and there override the theme settings with the values posted in the form.

Btw - it's not the best practice to control theme settings from a module. Do you have any specific reasons for moving this functionality to the module instead of leaving it in the theme?

---
Tags: 7, forms
---


# Question
Title: how to dynamically add new fields to a form using ajax?
I need to add the options array for a select field based on the first one like

```
<?php

function lists_form_alter(&$form,&$form_state,$form_id){
    $governments=array();
  if($form_id == 'place_node_form'){
      /*$vocabularies=  taxonomy_get_vocabularies();

      foreach($vocabularies as $vocab){
          if($vocab->machine_name =='listings'){
              //
              //$_SESSION['vid']=$vocab->vid;
              break;
          }
      }*/
            $options=array();
      $g=taxonomy_get_tree(23,0,1,FALSE);
      $x=count($g);
      for($i=0;$i<$x;$i++){
                $city[$i] = taxonomy_get_children($g[$i]->tid,23);
                      $options[$g[$i+1]->tid]=$g[$i]->name;
      }
      }
                  $options[0]='choose the government';

       $form['gov']=array('#title'=>'Gov','#name'=>'governorate','#type'=>'select','#options'=>$options,
           '#suffix'=>'<div id="replace"></div>'
           ,'#ajax'=>array('callback'=>'ajax_callback','event'=>'change','wrapper'=>'replace','method'=>'replace'));

isset($form_state['values']['governorate']) ? $op=taxonomy_get_children($form_state['values']['governorate'],23)
        : $op='';
$form['city']=array("#title"=>'City','#name'=>'city','#type'=>'select','#prefix' => '<div id="replace">',
        '#suffix' => '</div>',
           '#options'=> $op);

}

function ajax_callback($form_state,$form){
    $form_state['rebuild']=true;
    return $form['city'];
}

?>

```

what's wrong here?

# Answer
> 1 votes
You've got the parameters the wrong way round in your callback function; and you should probably take `$form_state` by reference if you need to change it:

```
function ajax_callback($form, &$form_state){
  $form_state['rebuild']=true;
  return $form['city'];
}

```

# Answer
> 0 votes
Thanks guys i found the solution by that answer

Is it possible to replace more than one form element (wrappers) triggered by only one #ajax trigger element?

the first answer using ajax\_command\_replace

and here is the final code

```
function lists_form_alter(&$form,&$form_state,$form_id){
 $governments=array();
  if($form_id == 'place_node_form'){

        $options=array();
  $g=taxonomy_get_tree(23,0,1,FALSE);
  $x=count($g);
  for($i=0;$i<$x;$i++){
            //$city[$i] = taxonomy_get_children($g[$i]->tid,23);
                  $options[$g[$i+1]->tid]=$g[$i]->name;
  }
  }
              $options[0]='choose the government';

      $form['gov']=array('#title'=>'Gov','#name'=>'governorate','#type'=>'select','#options'=>$options
       ,'#ajax'=>array('callback'=>'ajax_callback','event'=>'change','wrapper'=>'replace','method'=>'replace'));

```

$form\['city'\]=array("#title"=\>'City','#name'=\>'city','#type'=\>'select','#prefix' =\> '', '#suffix' =\> '','#options'=\>$op);

}

```
function ajax_callback($form_state,$form){
$form_state['values']['governorate'] != 0 ? $op=array(0=>'zero',1=>'one')
    : $op=array(2=>'two');

  $form['city']=array("#title"=>'City',
  '#name'=>'city','#type'=>'select',
    '#pref=> '<div id="replace">',
    '#suffix' => '</div>','#options'=>$op);

```

return array( '#type'=\>'ajax', '#commands'=\>array(ajax\_command\_replace ("#replace",render($form\['city'\]))) );

```
}

```

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