title: Path field gives wrong url

text:
# Question
Title: Path field gives wrong url
I made change in setting.php for base url

```
$base_url = 'http://www.example.com/drupal

```

Pattern for this content type paths are

```
[node:title]

```

pathauto works ok, in the database path is exactly as pattern.

Problem starts when I want to print Content:path in view I am getting

```
/drupal/[node:title]

```

I have a problem with path field because I want to rewrite result for logo field using

```
<a href="/company/[nid][path]">[field_company_logo]</a>

```

And link is `http://www.example.com/company/[nid]/drupal/[node:title]` instead of `http://www.example.com/drupal/company/[nid]/[node:title]`

# Answer
Changing the `$base_url` variable by no means makes drupal look through every bit of text in the system checking for href's. So, if you put in

```
 <a href="/company/.....

```

it is going to use it exactly as is because it has no idea to do anything else. It will, however, be more than glad to put it in front of a path if you use some of its built in functions, for example:

```
 <?php print l('Foo Bar Baz', 'company/foo/bar/baz'); ?>

```

will create a link to `/company/foo/bar/baz` if `$base_url` is not set, or if it is set to `drupal`, to `/drupal/company/foo/bar/baz`.

So, to your problem. Have you tried Views' `Output as a link` instead of creating the `<a> ... </a>` code yourself in `Rewrite the output of this field`? That *should* put that `$base_url` in there automagically if in the `Link path:` you enter `company/[nid][path]` (or whatever tokens you need as you use several different ones in your question).
> 1 votes

# Answer
I resolved this using `Global:php` field and in `output code` I wrote drupal function to find alias

```
<?php echo drupal_lookup_path('alias',"node/".$row->nid); ?>

```

Then as Jimajamma said in views I choose `Output as a link` and in `Link path:` i wrote `company/[nid]/[php]` and everything works.
> 1 votes

---
Tags: views, path-aliases
---


# Question
Title: Displaying non-empty fields in full node view
Using drupal 7 I have imported an excel spreadsheet into a database and mapped about 20 fields into a Custom Content Type. Not every field contains data in every record. I've created a couple of Views - one based on the Glossary that gives me a searchable form for the entries, and a separate Block view, which gives me the ability to hide empty fields and show random nodes.

However, when I click on a record to view the full node, the display shows all the fields, including the empty ones. If I edit the node, and then save it, when viewed the empty fields are hidden.

Is there a simple way to hide those empty fields all the time in full node view. Can I do it from within Views(3)? I'm not a programmer so not sure that I could edit a page template if that is what is required.

# Answer
If, when you edit the node, it displays correctly, this makes me think that the import *may* have added whitespace into the fields? Is that possible? I would recommend using Migrate for importing data. Even from files.

Either way, Views will not work for a node view ie, node/nid. You could use Views to create a landing/index page and hide empty fields pretty easily.

Rather than change the display, I would be more concerned with the quality of data in the fields (ie, whitespace) and would look at using something like VBO for cleaning the data. Are there many nodes? You could even just write a simple SQL update statement, something like;

```
UPDATE {field_data_field_blah} SET $value_col = NULL WHERE $value_col = '';

```

Note, pseudo query. :)
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How to change order of javascript files in Drupal 6?
I would like to change the order of my javascript files, and specifically move the jwplayer.js file so that it gets included after the jquery\_ui\*.js files. Does anyone know how to do this? I see how to do this in Drupal 7, using `hook_js_alter()`. But I do not see how to do this in Drupal 6.

UPDATE: Here is some more information on my setup, that might be relevant: \- I call drupal\_add\_js('jwplayer.js') from within a custom views template. The template adds jwplayer.js conditionally, depending on whether the views data includes any videos.

# Answer
If you look at `drupal_add_js()` and `drupal_get_js()`, you will see the details. Unfortunately, `module_invoke_all()` or it's cousins, don't get called, which means there are no hooks. Boo. A related issue is that when you aggregate, you loose the ability to do string manipulation (eg, explode, reorder, implode).

The best way to handle this is to alter the weight of the JW Player Module. One way to do this is to edit the `{system}` table and edit the `weight` column value. With the weights, lower numbers run earlier, higher numbers later, and where there is a tie, they run alphabetically. Make sure you clear cache when you do this. See Change module's weight - by module or manualy for some more details.

If this doesn't fix the problem, then the JS files aren't being added by the same hook. I am not sure what can be done it in this case w/o hacking the module.

A total sledgehammer approach would be to not include the your code, but to add it in the theme's .info file. This should add it after all modules.
> 5 votes

# Answer
I think you need to unset and attached it again in the order you prepared. See my post here which is a bit similar - How can I remove Javascript files?
> 1 votes

# Answer
JS Alter module for D6: http://drupal.org/project/jsalter

> This module adds a hook\_js\_alter() hook that other modules can use to modify the javascript that gets output to the page.
> 1 votes

---
Tags: 6, javascript
---


title: Linking content types

text:
# Question
Title: Linking content types
Can someone please tell me if this is possible? I have 2 content types, with the following fields.

* Asset

+ Title
    + Serial Number
    + Model
* Event

+ Title
    + Event Type (taxonomy)
    + Asset ID (a plain text field used to store links to Asset nodes)

Is there a way in views 3 to create a view that looks like *Asset Title : Asset Serial Number : Asset Model : Event Type*, basically a view linking both content types on one line. I've heard you need to use relationships, but I can't seem to get anything working.

# Answer
You need to create an event view with the asset ID as relationship. Then, add the field *Asset serial number* and select the right relationship, which should be below or above the Label setting.

I don't think this is the best option. It could be really performance consuming. First you need to create an event field view with event type and asset ID (the asset ID should be excluded from display). Go into the view folder, open theme, copy the *views-view-unformatted.tpl.php* file and paste it into you theme folder with the other template files (sites/all/theme/YOURTHEME/template). In the third column, click on theme and look for the style output (views-view-unformatted.tpl.php). There will be many of this. Use the more specific for that view (usually the last one), something like views-view-unformatted--event--page\_1.tpl.php.
Rename the file you copied in your template. Create an asset field view with the serial number and the node ID as contextual filters.

This is how a views-view-unformatted.tpl.php file looks like.

```
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

You should modify it in this way

```
    <?php if (!empty($title)): ?>
      <h3><?php print $title; ?></h3>
    <?php endif; ?>
    <?php foreach ($rows as $id => $row): ?>
      <div class="<?php print $classes_array[$id]; ?>">

        <?php print $row;
print views_embed_view('ASSET_VIEW', 'page_', $view->result[$id]->YOUR_FIELD);
?>
      </div>
    <?php endforeach; ?>

```

Test it.

`print views_embed_view('ASSET_VIEW', 'page_', $view->result[$id]->YOUR_FIELD);` will print the asset view. `$view->result[$id]->YOUR_FIELD` will print the asset ID from the event view.
> 0 votes

# Answer
A better way to do it is replacing the asset ID field with an entity reference field which refers to the other content type (Asset) and use view relations to get the relation. In short, create a relation between the content types, and you will be able to use view relations.

For advanced uses, you can take a look to the Relation module, which I don't recommend, in your case.
> 1 votes

---
Tags: 7, views, nodes
---


# Question
Title: In Activity Stream, how is the 'active group' determined when a node has multiple organic groups assigned to it?
I created new blog node in Drupal commons and assigned it to two organic groups. While it appears under both groups' Blog tab (view group\_tab\_blogs), it only appears under one group's Home tab but not the other.

>

On exploring the `activity_log_stream` view which is essentially the query for this tab, I noticed that it filters on the stream owner and does not search any other table.

>

Would I have to duplicate the row in this table or is there a way to have "multiple stream owners"?

>

**Update:** After a bit more digging, I started playing with the rules area. Here I see that this rule fires after the creation of a Node. But, again, how is the 'active group' determined when a node has multiple organic groups assigned to it?

>

**Update 2:** On Drupal.org, a bit more asking and digging lead to this bug report http://drupal.org/node/1294794 and even http://drupal.org/node/1256754.

**Update 3** The above patch failed.

>

# Answer
I believe the active group is just the group context which is present when content is created (i.e. if you're 'in' group B and post a node into groups A and B, it'll only go into the stream of group B). So it's not great for cross-posting.

You shouldn't use the patch in that issue because it was never finished, it's out of date, and has bugs and bad code that would most likely break your site.

If you plan to keep using Commons 6.x, best to post a feature request in the Activity log queue requesting default rules that would work to create multiple log messages when content is cross-posted across groups. Otherwise, wait for Commons 7.x where it's not planned to use activity log.
> 1 votes

---
Tags: 7, views, rules, organic-groups
---


# Question
Title: Is it possible to create an installation pack in Drush make?
I already have a Drupal 7 running. Is it possible to create an installation package using Make from my current setup. My goal is I have a Drupal 6 version which I need to convert to D7. For the sake of automated deployment I want to replace my D6 core once finished running the scripts to disable modules, features, and custom theme with my Drupal 7 setup before running update.php.

# Answer
> 1 votes
I have code to generate an installation profile from an existing site; it is still a work-in-progress in the issue queue here: http://drupal.org/node/1368242. Presently it works with D7, but does not yet generate the necessary installation scripts for D6. It still does a lot of useful work for you, though, and is a good place to start.

However, if your goal is to upgrade your D6 site to D7, what you are really looking for is Drush Site Upgrade.

---
Tags: 6, drush, migrations, deployment
---


title: Is there a page listing all fields?

text:
# Question
Title: Is there a page listing all fields?
I am wondering whether somebody has compiled a list of fields which are available for creating content types in Drupal. There are many lists of the most popular modules, but it would be great to have one focusing on existing fields, whether in core, or from third-party modules. I have looked around a bit, but always end up with lists of modules.

# Answer
There is a page at **admin/reports/fields** that lists the field name (the machine name), the field type and which module it came from, along with all of the bundles (content types, in the case of nodes) that use that field.
> 31 votes

# Answer
For Drupal 7, if you have `drush`, you can ask it for a list of "field types" (which includes their widgets), or "fields" (which includes the field name and its associated 'bundle').

The sample output (clean Drupal 7) for `drush field-info fields` gives for me:

```
 Field name    Field type               Bundles
 comment_body  text_long                comment_node_page,comment_node_article
 body          text_with_summary        page,article
 field_tags    taxonomy_term_reference  article
 field_image   image                    article

```

The output for `drush field-info types` gives:

```
 Field type             Default widget          Widgets
 file                   file_generic            file_generic
 image                  image_image             image_image
 list_integer           options_select          options_select, options_buttons
 list_float             options_select          options_select, options_buttons
 list_text              options_select          options_select, options_buttons
 list_boolean           options_buttons         options_buttons, options_onoff
 number_integer         number                  number
 number_decimal         number                  number
 number_float           number                  number
 taxonomy_term_referen  options_select          options_select,
 ce                                             options_buttons,
                                                taxonomy_autocomplete
 text                   text_textfield          text_textfield
 text_long              text_textarea           text_textarea
 text_with_summary      text_textarea_with_sum  text_textarea_with_summary
                        mary

```
> 23 votes

# Answer
You could also install the "Devel" module, and use the "Development" Block. There's a menu link (devel/field/info) that shows a comprehensive list of all fields, instances, and bundles.
> 4 votes

# Answer
In Drupal 6, just go to *admin/content/types/fields*.
> 3 votes

---
Tags: entities
---


title: Populate a file field on edit form

text:
# Question
Title: Populate a file field on edit form
I need to populate the file field with a value from the database (when editing a database row).

This is the code for the file field.

```
$form['file'] = array(
'#type' => 'file',
'#title' => t('Image'),
'#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);

```

The variable `$icon` contains the value (e.g. icon.png).

In Drupal 7 I made this work with:

```
  '#type'         => 'managed_file',
  '#description'  => t('Icon file may be a jpg, bmp, gif or png format.'),
  '#default_value' => $default_icon,

```

How can I do this in Drupal 6?

# Answer
> 0 votes
I ended up using this

```
if ($form_state['storage']['file'] != '0') {
  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_is_image' => array(),
  ));

  // If the file passed validation:
  if (isset($file->filename)) {
    // Move the file, into the Drupal file system
    if (file_move($file, $file->filename)) {
      // Update the new file location in the database.
      drupal_write_record('files', $file, 'fid');
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }

  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  file_set_status($file, FILE_STATUS_PERMANENT);
}

$fid = $file->fid;
$icon = $file->filename;

if (!isset($fid)) {
  $fid = $form['fid']['#value'];
}

if (!isset($icon)) {
  $icon = $form['icon']['#value'];
}

$id = $form['id']['#value'];
$url = $form['url']['#value'];
$title = $form['title']['#value'];

```

---
Tags: 6, forms
---


title: Is Google causing problems?

text:
# Question
Title: Is Google causing problems?
I have been getting the following notice from Google's IP address:

> Unable to generate the derived image located at public://styles/large/public/field/image/imagefield\_b9xgKB.jpg

Why does it happens? It started a week ago, and now it happens few times in a day. Sometimes the filename varies.

# Answer
> 1 votes
This is an error saying you have a link to an non-existing resource.

You should use Webmaster Tools to dig deeper, if I remember correctly, it should provide the URL for the page with the bad link.

---
Tags: media
---


title: Danland theme license

text:
# Question
Title: Danland theme license
I have chosen the Danland theme for my drupal site. The theme is licensed as GPL (from the license attached to theme). At the bottom of the theme on my website, there's "Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer", and I'd like to ask you if I can remove it (I won't derive and publish the theme).

I think I can, but I'm not sure.

# Answer
> 1 votes
Any module/theme hosted on Drupal.org is licensed under the GPL License v2+, which allows you to edit them, as long as you respect the license itself.

You can edit out that string. Even if you were distributing your version, you should distribute the source code too, which is the theme itself, as PHP is not compiled. You should not remove the attributions left in the comments from the previous author, though.

---
Tags: theming
---


# Question
Title: Views: sort criteria -> Post date, not start from latest but latest-3
is there a possibility to sort articles by postdate, but exclude the latest 3 and start with number 4 (because the latest 3 are already displayed in another view).

Or even better: is there in general a possibility to exclude articles already displayed on the same page but in another view?

# Answer
Yes, in the `Use Pager` options, you can specify an offset, which by default is 0, but can be any number, which, amusingly, in the help section offers:

```
The number of items to skip. For example, if this field is 3, the first 3 items will be skipped and not displayed.

```
> 0 votes

---
Tags: views
---


title: Video on pageload

text:
# Question
Title: Video on pageload
Hey is there a possibility to make a video automatically load on pageload (website) on Drupal 7 ? I mantion that I have installed Drupal 7 video module and I posted a video on my website but I do not know how to make it start on site load (if there is a posibility). Thank you in advance .

# Answer
On the Video Module page, there is a link to documentation:

External Documentation

which when clicked leads you to some General Help:

General Help

which leads to this picture:

Have you tried checking the `Automatically start video on page load` option there?
> 1 votes

---
Tags: files
---


# Question
Title: Disqus include causing Bad Gateway errors
I've set up Disqus on my drupal site and it was previously working, but it's suddenly not working and I have no idea what changed.

This is one of my nodes with Disqus in the block at the bottom: http://liberalgeek.com/content/republican-todd-akin-and-legitimate-rape-doesnt-cause-pregnancy

I'm getting a 502 Bad Gateway message in my javascript console on Chrome:

```
GET http://mediacdn.disqus.com/1345491156/uploads/themes/dsq028ee724157b05d04e7bdcf237d12e60.css?1557 502 (Bad Gateway) client.js:6
DISQUS.requireStylesheet client.js:6
Backbone.View.extend.bootstrap client.js:84
Backbone.View.extend.initialize.b client.js:81
b.Events.trigger lib.js:108
(anonymous function) client.js:16

```

# Answer
> 0 votes
It looks like the API was undergoing maintenance which is why it was rejecting with a 5xx error. Here is the list of meanings to the HTTP response codes that Disqus uses:

http://disqus.com/api/docs/errors/

---
Tags: 7, comments
---


# Question
Title: page not found after migrating drupal 7 to dev version same server using drush archive-restore
I have tried twice over to migrate a production site to a development version using a different database and although the files are all there and the database is also there I just keep getting a 'Page not found' when browsing to the dev version. I have checked my settings.php file which is pointing to the correct database too.

Here is a list of the process I used: `drush archive-restore /home/username/drush-backups/archive-dump/20120821113939/hampstea_db.20120821_113946.tar.gz default --destination=./hamp-dev --db-url=mysql://username:password@localhost/db_name`

Any suggestions? Thanks in advance

# Answer
> 0 votes
This just struck me; don't know why I missed it before. Rather than using archive-restore, use the Drupal multisite feature to make both your dev and prod site use the same codebase. Make http://mysite.com and http://dev.mysite.com point to the same IP address. If your ISP will serve up the same document root from both of these names, then you can follow the instructions on the aforementioned page to serve content from a different database based on the domain requested. If you can't do this, you need better hosting! There's a lot of good and inexpensive plans out there.

As an aside, I like to use the Environment indicator module to keep track visually of which site I am looking at.

# Answer
> 0 votes
A couple of questions:

1. Are you creating that dev site as a root subfolder of the production site?
2. If yes, do you get a page not found on the production site OR on the server?

This might be an issue with .htaccess; if you just added dev site to the root of your production website, you might need to add a rule to exclude "/dev".

I think adding this before rewrite conditions for the production site would work:

```
RewriteRule ^(dev).* - [NC,L]

```

# Answer
> 0 votes
The dev site is installed in a subfolder and probably has clean urls enabled.

Just edit .htaccess of the *dev* site and set RewriteBase /dev

---
Tags: 7, drush
---


# Question
Title: How can I insert a comment form into my view?
In Drupal 7, I'm building a module that has a view page that lists all nodes of a certain type. I want users to be able to comment on each node in the view from this view page.

I tried using `hook_node_view` but it only seems to apply to the full node page view. What kind of hook do I need to get the comment form of a node in a view?

# Answer
> 2 votes
What I know? That you can use the view.tpl.php file and add:

```
<?php
print drupal_render(drupal_get_form("comment_node_**content_type_machine_name**_form", (object) array('nid' => **$node->nid**)));
?>

```

Change the bold according to your node object and the content type machine readable name.

I think this link can help you too. and I suggest to check `hook_views_pre_render` Here which can do it but I didn't try it before.

---
Tags: views, comments
---


title: D6 prohibit upload file extensions

text:
# Question
Title: D6 prohibit upload file extensions
I'm using filefield module, and it has permitted extension field. Is it possible to disallow certain extensions (e.g. exe, zip, rar) instead of adding permissions for ones that are ok?

# Answer
Not directly, but you could do that in your own custom form validation. For example:

```
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {

  switch ($form_id) {

    case 'YOUR_CONTENT_TYPE_node_form':

      $form['#validate'][]='YOURMODULE_valid_extensions';
      break;

    // any other forms here

  }

  // any other form alters here

}

function YOURMODULE_valid_extensions($form, &$form_state) {

  // $whitelist=array('txt', 'doc', 'pdf');
  $blacklist=array('xxx', 'exe', 'php');

  /* I am assuming that this is a single value field ([0] below) */
  $extension=pathinfo($form_state['values']['field_YOURFIELD'][0]['filename'], PATHINFO_EXTENSION);

  // if (in_array($extension, $whitelist)) {
  //   return;
  // }

  if (in_array($extension, $blacklist)) {
    form_set_error('field_YOURFIELD', t('Invalid file extension'));
  }

}

```

and if you leave the extensions field blank, filefield won't do any validation, but you will in the second function above. I've also put in `//'s` basically what filefield is doing if you wanted to incorporate both. If you do go this route, you will have to put some verbiage in your help section as the widget will most probably say all extensions are valid :)
> 0 votes

---
Tags: files
---


title: Symbolic Code for Delete

text:
# Question
Title: Symbolic Code for Delete
I know about using LANGUAGE\_NONE instead of 'und' for an undefined language. Is there also a symbolic variable for a 'Delete' operation? In my hook\_node\_validate, I look at the value of $node-\>op, which is the operation. I test it for the value of 'Delete', if the content is being deleted.

Should I be using something other than the string 'Delete'? I looked in bootstrap.inc, but didn't find anything there.

# Answer
There's no symbolic code/constant for 'Delete', no.

The button containing that text gets set in the main `node_form()` function though:

```
$form['actions']['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#weight' => 15,
  '#submit' => array('node_form_delete_submit'),
);

```

and making the assumption that no other module is changing the `#value` of that variable by way of a form alter, you'll be safe checking the clicked button text by wrapping the same string in `t()`:

```
if ($node->op == t('Delete')) {
  // ...
}

```
> 1 votes

---
Tags: hooks
---


title: Explicit/Implicit Relationships

text:
# Question
Title: Explicit/Implicit Relationships
In this presentation, slide 13 says (emphasis mine):

> The relationships between Entities- the ways entities can interact either each other - define our Drupal application
>
> nodes can have comments
> users create nodes
> taxonomy terms are attached to nodes
>
> **these relationships are implicit - perhaps they should be explicit?**

What does the last sentence mean? In Drupal, what makes entity relationships implicit rather than explicit?

# Answer
Only the original author knows what he meant by this, as the distinction between implicit and explicit does not have any special technical meaning within the context of Drupal that differs from the normal distinction made in plain English. Nonetheless, here are my thoughts.

The relationships are implicit because there is nothing in the database to *define* them and give them *meaning*.

For example, take nodes and users. The `{node}` table has a `uid` column. What does this *mean*?

It is *implied* in Drupal that this is the author. But, it could really be anything: author, owner, sponsor, etc.

In some database designs, tables will never have relationships (ie, foreign keys) to other data tables directly (I forget which normal form this is).

To do this in Drupal, you would alter the `{node}` and delete the `uid` column. Then make a `{node_x_users}` table that looked something like

```
CREATE TABLE  `node_x_users` (
  `xid` int(10) unsigned NOT NULL default '0',
  `nid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `rid` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`xid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`),
  KEY `rid` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

The actual relationships, via (foreign keys to other tables) would be stored in this table and not in `{node}` or `{users}`. You would also make a table like

```
CREATE TABLE  `relationship_labels` (
  `rid` int(10) unsigned NOT NULL default '0' COMMENT,
  `type` varchar(128) NOT NULL default '',
  PRIMARY KEY  (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

```

This would store a text version of what the *relation type* is so you could *explicitly* define them.

So, when you make a node, you insert the node into `{node}`, get the `$nid` (which is the PK of the table), then insert the relationship into the cross table, `{node_x_users}` along with the `$uid` and the key representing the type of relationship. When you render a node, you also JOIN on the `{relationship_labels}` to get the "Authored by", "Edited by", etc text.

In the code you end up with more JOINs (but they are all on simple, indexed types), but you also gain some other advantages, the biggest benefit is a very flexible data model.

Personally, I see this as one of the biggest problems with the current Drupal architecture.

An example of a system that does relationships like this is CollectiveAccess.
> 2 votes

# Answer
As it is now, the relationship between (for example) a node, and the user who created it is established from the `$node->uid` property. It is implicit because it is a relationship that is automatically created from Drupal through a custom property. For Drupal, every node has an author, and every node has zero, or more comments; every comment is associated to a node (and not other entities), and every comment has an author.

This is different from the case where the `$node` object had a property containing a list of related entities, such as `$node->relatedEntities`. The user object for the user who created the node would be contained (for example) in `$node->relatedEntities['author']`, and the comments for the node would be contained (for example) in `$node->relatedEntities['comments']`. In this case, there would be one or more database tables that contain all the values for those relationships, such as in the following table.

```
Relationship  | Main entity ID | Main Entity type | Related entity ID | Related entity type
author        | 1              | user             | 345               | node
author        | 1              | user             | 2                 | comment
author        | 1              | user             | 243               | node
comment       | 234            | comment          | 345               | node
author        | 1              | user             | 234               | comment

```

If this were the way the relationship between nodes and author were stored, the node table would not define the uid field containing the user ID for the node's author. In the same way, the comment table would not define the uid, and the nid fields.
> 0 votes

---
Tags: 7, entities
---


title: How do I add fields to a specific node?

text:
# Question
Title: How do I add fields to a specific node?
I want to create a Basic page that, in addition to its title and body, has a list of other nodes. The list of other nodes has to be entirely administered through the admin. However, I don't want to add the other node field onto all Basic pages, as it only applies to this one specific case. How do I do that?

To clarify, I'm asking about the backend portion of this. How do I get it so that, when I edit a certain node, only specific fields show up in the admin?

# Answer
There are two main ways of doing this: You can create a second content type which is the same as the Basic Page content type except with the additional fields that you require, or you can just add those fields to the Basic Page content type and only fill them out on the single node you want them to appear on.

As for how to show a list of nodes on another node, I would highly recommend the Entity Reference module. This allows you to add a field that is just stored as a reference to another node.

---

*Original answer (I am leaving this in because it is another way to accomplish a similar outcome):*

Using Views you can create the list of nodes that you would like to display on the page. The new version of views makes it super easy to do that. From there you have a couple options, depending your level of skill with theming and how much control you need to have over where the list of nodes displays:

* A Block - Create a block display for your view. Place the block in the same region as the main content block.
* node--NODEID.tpl.php - You could add a template suggestion to your theme to override the specific node that you want to add the list to. To do that you would need to:

+ Create a node--NODEID.tpl.php file, replacing the NODEID with the nid of the node you want your list of nodes to show up on.
    + Embed your view in the node template using the following code:

    `<?php print views_embed_view('MY_VIEW', 'MY_DISPLAY', $node->nid); ?>`

Where MY\_VIEW is the machine name of the view you created and MY\_DISPLAY is either "default" or the machine name of a specific display in your view.

Here is an example: http://api.drupal.org/api/views/views.module/function/views\_embed\_view/7#comment-32858
> 3 votes

# Answer
Create a unique content type, that mirrors the basic page content type, and then just use it the once (with your added fields) ?
> 0 votes

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


# Question
Title: Set default values for a field from a node
In Drupal, when you create a field, you can specify the default value for a field. For example, if you have a field called price, you can set the default value to be 400. When the user creates a new node, 400 is the default value, but s/he can change it to whatever s/he wants.

Is there a way to link this default value to a node field value.

For example, lets say on node/12 I have a field called "price default". If the user enters 500 on this field (on node/12), the default value of the price field (for all new nodes) will change from 400 to 500.

# Answer
Ahmed was close, but to take it all the way you need to fetch the field's value:

```
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID_HERE') {
    // Fetch node that has default value
    $node = node_load($nid);
    // Fetch the value from price field
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $field_val = $node_wrapper->field_price->value();
    // Set fetched value as default
    $form['field_price'][LANGUAGE_NONE][0]["value"]['#default_value'] = $field_val;
  }
}

```
* I am itching for a clean way to avoid having \['und'\]\[0\] in there, as these values can change with localisation, but this would still work.
> 5 votes

# Answer
You can use hook\_form\_alter to set default value of your field by select the last value of it

```
function MODULENAME_form_alter(&$form, $form_state, $form_id) {
    $form['account']['status']['#default_value'] = '0';
}

```
> 0 votes

# Answer
You actually can. Before setting the price field's default value, do a `node_load($nid)` (You must know the node's id), it should return the complete node object inclusive of the fields. You can find the value of price\_default from that and set the default value of price field accordingly.
> 0 votes

---
Tags: entities
---


# Question
Title: Ckeditor toolbar not entirely showing up
I have just moved my site from local machine to production, the wysiwyg editor based on ckeditor no longer show the complete toolbar. I have a minimal list of element. Can someone help, am trying everything, edit profile, check if all files are uploaded, i don't see any problem !

# Answer
Updated answer:

Go to "Home › Administer › Site configuration › CKEditor".

Then select an individual profile in the upper section (not the Global settings).

You'll be on the "Edit CKEditor profile" page, where there is an "Editor appearance" section. The 6th item down (just below the color picker) is the ***toolbar selector***.

There are 5 options, if none of the selections meet your needs, you can easily create a custom toolbar with exactly the buttons that you want to have available.

The module author included a note below the toolbar selector, you can open the "ckeditor.config.js" located in "sites/all/modules/ckeditor" and create your custom toolbar there. It will appear in the selector after you create it.

I've included all of the buttons available for the normal CKEditor, but the module author has added some that are specific to Drupal. You can take a look at them in the config.js file.

Here are the standard plugin buttons, you can pick and choose which ones you want:

```
[ 'Source','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ]
[ 'Link','Unlink' ]
[ 'Image','Table','HorizontalRule','SpecialChar','-','SpellChecker' ]
[ 'Source','About','InsertSnippet','BGColor','SimpleLink', 'Select', 'SelectToText', 'SelectorUpdateSelector','SimpleLink' ]
[ 'About','BGColor' ]
[ 'Format','Font','FontSize' ]
[ 'TextColor' ]
[ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ]
[ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ]

```

Be Well, Joe
> 3 votes

# Answer
Install the jQuery Update module; that will fix your problem.
> 2 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Redirect the anonymous users to the login page when they try to vote a node
I am using Vote Up/Down for voting on nodes. I would like that anonymous users could be see the voting widget, but they should be first redirected to the login page, before they vote. I tried setting the permissions as follows:

1. use vote up/down on nodes - checked for anonymous user
When I try to vote as an anonymous user I get the following error.

> An error occurred at /vote/node/1470/-1/vote/helpful/59a7d98542754cb9fd01758fbbe95a3a.
>
> Error Description: 403: Forbidden
2. use vote up/down on nodes - checked for anonymous user; view up/down count on nodes - checked for anonymous user
I still get the same error.

Does anyone know what to do to redirect anonymous user to the login page when they try to vote?

# Answer
> 1 votes
I have installed the module that you mentioned and got the same error. It seems that even though the Vote Up/Down module allows you to give anonymous users permission to vote, internally, it does not support it and throws the specific error. I suspect - I'm guessing here - that they are using the user id to "save" what the logged-in user voted and when the user id is 0 (which means anonymous) an error is thrown.

Anyway, the way I see it, there are 2 main paths that you can follow in order to get the functionality that you want:

**1)** Have someone (= a drupal developer) modify the module for you. This way, you will be able to add the functionality, and even submit the changes it to the module's repository.

Pros: you help the community, you get a clean solution (depending on the developer's skill)

Cons: costly (I suspect), takes time, you get bad code and patch the problem (depending on the developer's skill)

**2)** Get the functionality through theming. Instead of enabling the module for anonymous users, you can just disable it, and through the node-*nodetype*.tpl.php file you can just show the image of the voting arrows to the anonymous users (you will have to use an if conditional to check if the user is logged in or not) and make the image point to a link like this:

```
/user/login?destination=/node/$node->id

```

This way the user will be redirected to the login form and then back to the node, but he will have to press the vote button again.

Pros: easy to implement, theme based solution = minimal interaction with code

Cons: it's really a work-around, not a solution, the user is not actually voting but he thinks he is voting (not really honest :P)

# Answer
> 1 votes
If anyone is still wondering about a workaround for this (I sure was)...you have to edit the /ajax-responder.js file, found here: /sites/all/modules/ctools/js/ajax-responder.js. If you View Source on the page(s) that have the vud widget, you'll see it included in your header (included in $scripts).

Here's what I did:

* Make a duplicate copy of the file just incase.
* Do a Find for "An error occurred at", and you'll find the alert() line that's causing the obtrusive alert message. Comment it out.
* Add in a redirect. Exactly what F1234k mentioned (thanks!). The 'path' variable that gets passed into the function includes the node ID (yay!). To get the node id, you need to split up the url (it includes a long ajax call url) to grab the section with the node id (which is in the 3rd section of the url):

```
var path_split = path.split("/");

var path_node_id = path_split[3];

window.location = "http://www.site.com/user/login?destination=node/" + path_node_id;

```

Unfortunately this still runs an error on the page and it is just a workaround, but it gets rid of the nasty alert message without having to mess around with too much code!

Also, I did this in Drupal 6.

---
Tags: 7, rating
---


# Question
Title: Why is #field_parents empty in nested, multi-step form?
I'm using Webform, Fieldgroup and Multistep with D7.

Ultimately I'd like to create a hierarchically-grouped list of all the submitted values and display on the last step of the multi-step form, with the following format:

* Page 1
    + Question 1 Label
        - Question 1 Response
    + Question 2 Label
        - Question 2 Response
    + Question 3 Label
        - Question 3 Response
* Page 2
    + Question 4 Label
        - Question 4 Response
    + Question 5 Label
        - Question 5 Response
    + Question 6 Label
        - Question 6 Response

When I inspect the `$form` object, however, I see the fields each listed, but `$form['field_my_question']['und'][0]['#field_parents']` is an empty array.

How can I identify from the `$form` object which fields belong on which page of my multistep form?

# Answer
> 0 votes
I don't know what exactly `#field_parents` is for, but the information about field grouping is in `$form` (which, it turns out, is an array, not an object) several times over, in `$form['#groups']`, `$form['#fieldgroups']`, and `$form['#group-children']`.

---
Tags: webforms, forms
---


# Question
Title: When using &drupal_static to cache variables how do I store an empty return result of null or false?
I'm making an expensive soap call and would like to cache it even if it is empty through the duration of the script and page load. It's entirely possible that in the third party database the object is empty and null. I don't want to make five soap calls if the object is empty. I feel like using PHP empty() and isset() this way is hackish. It works but there is a lot of funky logic involved. Is there a better way?

I need the drupal\_static so if the $third\_party\_info\_object is change anywhere else all the caches can get cleaned.

```
function my_module_get_information($user) {

  third_party_soap_initialize();

  $third_party_info = &drupal_static(__FUNCTION__);

  if (!isset($third_party_info) && is_null($third_party_info)) {
    // work some magic here
    $account_object = new thirdPartyAccounObject();
    $account_object->setThirdParyAccountId($user->uid);

    $third_party_info_object = new ThirdPartyInfo();
    $response = $third_party_info_object->getByAccount($account_object, false);

    $returnCode = {get the $returnCode here}

    if ($returnCode == 200) {
      $third_party_info = $response->getThirdPartyInfo();
    }
  }

  if (!isset($third_party_info)) {
    $third_party_info = false;
  }

  return $third_party_info;
}

```

# Answer
> 1 votes
drupal\_static()'s default value is null. So instead of doing this

```
<?php
$third_party_info = &drupal_static(__FUNCTION__);
if (!isset($third_party_info) && is_null($third_party_info)) {
?>

```

Try this

```
<?php
$third_party_info = &drupal_static(__FUNCTION__);
if (is_null($third_party_info)) {
?>

```

---
Tags: caching, performance
---


# Question
Title: Simplenews automatically send out email notifications when new content is published
I'm trying to figure out a way to allow anonymous users to subscribe to my blog and receive email updates whenever I publish new content.

I've tried a couple of solutions, but none of them seem to work the way I would like them to. This page (http://drupal.org/node/983184) says that I should be able to use Simplenews to do it, but I can't figure out how.

That module seems to be based around creating a Newsletter content node and which gets sent to the subscribers. However, what I want to do is post a new Article and have the system automatically send an email to all my subscribers containing something like a Teaser.

At the least, I'd like to send a simple email with the Content Title and a link to the node.

How do I configure Simplenews to work like this?

# Answer
> 1 votes
Recommend to try the Newsletter module. This may also help you.
This may also be another solution for you.

---
Tags: 7, notifications
---


title: Modifying the core tracker module

text:
# Question
Title: Modifying the core tracker module
I would like to modify the styling of the tracker module and also move it's content from a separate user profile tab to the main tab. What is the best way to accomplish this? Modifying the core module would be a bad idea right? I may also want to edit the module to change functionality.

# Answer
> 2 votes
It's the best to clone the module, rename it to let's say "custom\_tracker" and there do the modifications you need.

As I did this few times with other modules, here are some tips:

1. Rename with "custom" prefix/suffix to avoid name clashes. Don't forget to rename all function and variable (I mean the stored ones) names as well as all the files (tracker.module =\> custom\_tracker.module)
2. Test the module in local before using it on the live site.
3. As the module isn't too big, I suggest reading all code and do the renaming manually. It's better than simple replace as it might remove/screw wrong parts and also you can better understand the module.
4. If you would like to be able to improve the module later on, **mark** the changes/additions you made so later on if the module gets updated you can merge/add those improvements to your module as well.

---
Tags: 7
---


# Question
Title: How to add my html code so as to design the page generated by a view using drupal 7?
I have created a view with a page and a block. Also i have created a new content type by creating a new node--news\_page.tpl.php file and a page--news.tpl.php file so as to display my block there. What am i trying to do is to edit the way news are displayed. To accomplish that i need to add my html code to the page the view created. How do i do that using drupal 7 and views3 module?

# Answer
In your view on the right-hand side there is an 'advanced' link.

When you click this it will display a number of advanced options.

The option you want is 'Theme : information".

Click on information and you will presented with a number of template suggestions to help you theme your view.

To determine what template to use you basically need to think what level you want to theme at.

**Example:** If you click the link 'Display output' and copy/paste the code into one of the suggested file names i.e. views-view--\[YOUR\_VIEW\].tpl.php, this is the top level you can theme at.

If you wanted to theme a particular field you will find that further down in the suggestions.
> 0 votes

---
Tags: 7, views
---


title: Services module and hook_node_view

text:
# Question
Title: Services module and hook_node_view
When I view a node via Services in json or xml format a field I am adding via hook\_node\_view is unavailable. How could I add the field so it is available also when the node is viewed via Services? I only seem to be able to access the node via hook\_node\_load

# Answer
`hook_node_view()` is only invoked when a node is prepared for display (normally either through `node_view()` or `node_view_multiple()`).

Since the node isn't prepared for display when you request it via a services call, your hook won't be called. If you think about it this makes perfect sense; you're requesting a json/xml representation of the node so there's absolutely no reason why the node should be prepared for display.

The only way round this would be to move your logic into `hook_node_load()`, which is called for all node loads. The same data that you attach in `hook_node_load()` is available to you on the node object in `hook_node_view()`, so you'll be able to move your logic without any problem at all.

I suppose the other, more complicated method, would be to write your own Services resource that loads the node view as well as the node, so the extra data you're adding would get picked up.

But semantically speaking, unless the actions you're taking relate specifically to the HTML that will be output for the node, `hook_node_view()` is not the right place to add your extra data.
> 2 votes

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


# Question
Title: Webform - Replace Form title with Node title
I'm working on a Job Portal where-in i created a **content-type** for job listing and a Job Application **Webform**. I need to provide a link on the job node which will be linked to the webform and upon submission,the title of job listing node will be sent as the webform title(Editable or uneditable). And in the **Webform listing**, the form should have the **title** as that of the Job node from which it is applied.

I like to know, what are the ways with which this can be achieved

# Answer
> 1 votes
In CCK there is a module called Field Reference. Enable that an you can create a field reference field, which you can link to a specific field in another node.

---
Tags: nodes, entities, webforms
---


# Question
Title: How can I tell boost cron run to delete a file
If I have a custom module that maybe adds some fields, or reorders some data which is to be shown in the frontend: How do I tell boost, that the cached files should be deleted on the next cron run after I've made some changes?

# Answer
> 2 votes
First you need to set a flag which indicates that new fields are added. Can be a `variable_set()` or something similar thats stores values in DB whenever new fields are added.

In your `hook_cron()` you should check if the flag is set or not. If set clear Boost cache using boost\_cache\_clear\_all(). Unset the flag once cache is cleared.

---
Tags: 7, cron, caching
---


title: Drupal shows mobile theme on desktop

text:
# Question
Title: Drupal shows mobile theme on desktop
I have drupal 6 with mobile-tools module and idrupal theme for iphones. sometimes my website starts displaying mobile theme (idrupal) for desktop, and the only way to return back to normal theme for desktop is to flush all caches. is there a permanent solution to disallow idrupal theme from being used for desktop?

# Answer
> 1 votes
If you are using varnish in front of the your server, then it will completly cache you request, Mobile tools will not be able to determine the useragent is mobile or desktop to redirect the theme.

One of the solution is to determine at varnish level and redirect to a m.domain which always has a mobile theme attached to it.

Refer the following links

1. http://fangel.github.com/mobile-detection-varnish-drupal/
2. http://mobiledrupal.com/content/mobile-device-detection-varnish-0

---
Tags: theming, mobile-tools
---


# Question
Title: Plesk servers and Drupal Apache module requirements
Recently I have leased a shared server where I manage everything via Plesk and do the nitty gritty configurations via ssh.

Plesk comes default with almost every Apache module enabled, and my processes are over 100 megs each, which is way too high. Here is a list of them:

```
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_alias_module modules/mod_authn_alias.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule info_module modules/mod_info.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule cache_module modules/mod_cache.so
LoadModule suexec_module modules/mod_suexec.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule version_module modules/mod_version.so

```

I have learned a lot by researching the community about what Drupal needs on sites like 2bits.

However my question is, can I just turn all these off and enable the bare minimum that Drupal needs to run as mod\_php? By turning any of these off, would I actually affect how Plesk operates (which we need it to work fine in house for those doing general administration for the domains this server handles).

If nothing here would affect how Plesk works, then I ll be happy to just turn them all off, except for the hand full of modules drupal needs. And, by the way, I of course have conflicting information about what drupal 'needs' to run leanly. Which of the modules in this list would you suggest I keep to run drupal?

thoughts?

thanks

# Answer
Off the top of my head, Drupal will need many of those.

In my experience, Plesk is **very** picky about server configuration and may not run properly once you start mucking with the Apache and/or PHP settings.

Personally, I would not run a Drupal site on a Plesk managed machine, but that's me. I start out with the barebones CentOS and go from there. With Apache, I don't need to turn on/off any additional standard modules, though I will usually also install the module that allows HTTP range requests for H.264.
> 1 votes

---
Tags: 7
---


# Question
Title: Configure CKEditor - WYSIWYG HTML editor
What is the way to configure CKEditor - WYSIWYG HTML editor for Drupal 7 sites?

# Answer
You can install the CKEditor module for Drupal for that: http://drupal.org/project/ckeditor

You will have to include CKEditor by yourself, which you can download from here

Install the Drupal module and put the ckeditor folder from the second link under sites/all/libraries and that should be it.
> 1 votes

---
Tags: 7, wysiwyg
---


# Question
Title: Drupal 7: entity field as single/multivalued based on content type
I have a 'gender' entity(taxonomy) field.

I want to use it as single valued for content type X and multi-valued for content type Z in Drupal 7?

Is there any other work around to achieve this functionality?

# Answer
> 2 votes
Shortly, no.

Take a look at project Field instance cardinality and an issue #1029298.

> This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.

Theoretically, you can create field as multi-valued and limit cardinality for *content type X* programmatically.

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


title: Date ISO Custom format

text:
# Question
Title: Date ISO Custom format
My Drupal offers only three types of rendering a Date ISO field (Display management in Content Type admin panel). What if I want to see my date in a different way? Is there any way to set my own formatter?

Second question. Is there any possibility to indicate while calling render(...) or field\_view\_value(...) (or anywhere else) what formatter to use? For example, I want for specific set of nodes to show not brief date variant but a full one. How can it be achieved?

# Answer
Solved that!

in admin/config/regional/date-time there is an ability to add "date type" (there are three default ones, brief, medium ad full format) as well as to add custom format pattern in PHP date()-style for any "date type". Sweet!
> 0 votes

# Answer
There are two thing to do for the date format:

First create a date format (admin/config/regional/date-time/formats/add): this where you define how the date will be display and a simple PHP string date format is all you need something like 'm/d/Y' will show the date as 08/20/2012.

Once the date format is added you can use it on any "Date Type" (admin/config/regional/date-time) or you can create your own date type and assign the date format to it.

To display different date formats depending on what view of node is you have multiple options:

1. Use panels, views, context or display suite and format the date to your date type or date format
2. Edit or create a template for your node type (node--CONTENT-TYPE.tpl.php if D7 or node-CONTENT-TYPE.tpl.php if D6) and use the format\_date function to format it.

if ($teaser) { format\_date($node-\>created, 'custom', 'Y-m-d H:i O')); } else { format\_date($node-\>created, 'custom', 'H:i O Y-m-d')); }

OR using your date type:

```
if ($teaser) {
format_date($node->created, 'DATE-TYPE'));
} else {
format_date($node->created, 'DATE-TYPE'));
}

```
> 1 votes

---
Tags: entities
---


# Question
Title: Can I use a custom CCK Link field as URL for Ubercart Product Image
I created a custom link field for my Product content type using Drupal 6 and Ubercart 2. Now instead of linking the Product image in the Product site to itself or show it as a slideshow I would like to create a link to the URL of the given field.

I found the function that displays the product image, which is called 'theme\_uc\_product\_image' and replaced

```
 $output .= '<a href="'. imagecache_create_url('product_full', $first['filepath']) .'" title="'. $first['data']['title'] .'"';

```

with

```
$destination_url = $node->field_direct_shop_link[0]['url'];
$output .= '<a href="'. $destination_url .'" title="'. $first['data']['title'] .'"';

```

but it didn't work out!

Any ideas on how to solve this?

Thanks a lot in advance. Best, Manuel

# Answer
Digging into Ubercart, this is the theme function you are talking about:

```
/**
 * Formats a product's images.
 *
 * @ingroup themeable
 */
function theme_uc_product_image($images, $teaser = 0, $page = 0) {
  static $rel_count = 0;

  // Get the current product image widget.
  $image_widget = uc_product_get_image_widget();

  $first = array_shift($images);

  $output = '<div class="product-image"><div class="main-product-image">';
  $output .= '<a href="'. imagecache_create_url('product_full', $first['filepath']) .'" title="'. $first['data']['title'] .'"';
  if ($image_widget) {
    $image_widget_func = $image_widget['callback'];
    $output .= $image_widget_func($rel_count);
  }
  $output .= '>';
  $output .= theme('imagecache', 'product', $first['filepath'], $first['data']['alt'], $first['data']['title']);
  $output .= '</a></div><div class="more-product-images">';
  foreach ($images as $thumbnail) {
    // Node preview adds extra values to $images that aren't files.
    if (!is_array($thumbnail) || empty($thumbnail['filepath'])) {
      continue;
    }
    $output .= '<a href="'. imagecache_create_url('product_full', $thumbnail['filepath']) .'" title="'. $thumbnail['data']['title'] .'"';
    if ($image_widget) {
      $output .= $image_widget_func($rel_count);
    }
    $output .= '>';
    $output .= theme('imagecache', 'uc_thumbnail', $thumbnail['filepath'], $thumbnail['data']['alt'], $thumbnail['data']['title']);
    $output .= '</a>';
  }
  $output .= '</div></div>';
  $rel_count++;

  return $output;
}

```

First off, I hope you didn't go in there and start hacking away, but rather copied the above to your theme's template.php file and renamed it `YOURTHEME_uc_product_image()` and made your modifications there :) But, either way, from the declarations of this theme function, the only data you have to work are in the `$images` argument plus anything uberfunky returned by ub's image\_widget. You might want to throw in some debug code to see if anything in there is what you are looking for like this:

```
drupal_set_message('<pre>' . print_r($images, TRUE) . '</pre>');

```

at the start of your copied function. Just remember to clear your caches/theme registry so drupal sees your function.
> 0 votes

---
Tags: entities, ubercart
---


title: Where to store data for module

text:
# Question
Title: Where to store data for module
I recently developed my first module. Part of its functionality is to store names, e-mails, and phone numbers of people on a newsletter. They sign up through the front-end and the admin can review and modify them on the backend.

In addition it also stores SMS messages and their details (date sent, number sent from, message, etc) that come in from a short code. This process is triggered by an HTTP request. Again, the admin can review and modify these in the admin of the website.

And finally, the same install will host 15-20 tables with ~20 columns and ~170 rows of health, education, and water quality statistics that can be queried from the website.

So that's everything: newsletter list, sms messages, data

I've never worked with a CMS and added so much to the default database. I also lack a lot of knowledge about databases. So my question is **Should I store all this extra information in a different database?** My current hosting allows for 20, and I'm only utilizing one.

Let me know if you need any extra information. Thanks in advance!

# Answer
I'm afraid you need a long answer for this.. But using a data\*base\* to store different values like this is not the best way I guess.

You can use multiple databases with Drupal and switch them without a problem. But real question would be, *why*.

However, you can store categories in different table,and refer the category ID from the main sms message table. It's much easier to JOIN queries and get the data you want,rather than having a table for each category. Also, I'd suggest using core functionality when you can. With new entity system in Drupal 7,you can make a new entity, an SMS, and attach fields like category it to.

If you are storing settings of the module, consider using system\_settings\_form to store settings. You can set/get them using variable\_set and variable\_get. But make sure that you don't store big text using this.

Good luck!
> 2 votes

---
Tags: database
---


# Question
Title: Is it possible to retrieve partial forms?
Is it possible to retrieve only parts of a form for display, that is, only certain form elements?

I am looking at the stack for building the node form, and so far the functions I've seen work with wholesale forms, in this case the `node_form`.

> drupal\_retrieve\_form(): /.../http/includes/form.inc at line 752
> drupal\_build\_form(): /.../http/includes/form.inc at line 331
> drupal\_get\_form(): /.../http/includes/form.inc at line 123

I am interested in only retrieving (rendering) the default body field via AJAX **only for a preview type of display**. So far I've been successfully build and render the whole node form just using the `#AJAX` FAPI property and other Drupal hooks - but I was wondering if something similar was possible for just one field. Answers that point to Drupal core APIs instead of contrib modules (who may be using their own jQuery magic) are a plus.

I'm just gathering thoughts to see how I write a D7 module for this question.

# Answer
> 1 votes
This is how I might end up doing it:

* When a JavaScript callback is triggered by a user editing the body field (this can be done via the #ajax property), clone current node found on form\_state.
* Create a render array for the whole node by using FAPI's `drupal_build_form($form_id, $form_state)`.
* Extract the body field from the render array.
* Render the body field.
* Return HTML to the front-end (JavaScript) so it can be placed on a preview DIV.

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


# Question
Title: "Find Content" missing even though user has permission "Access the content overview page"
The *Add content* menu item is available, but the *Find content* item is not visible, even though the account used to log in has the *Access the content overview page* permission and can access http://example.com/admin/content.

How can I make the *Find content* visible to that account?

# Answer
Problem: User's "Add Content" menu item is available, but "Find Content" is not.

Solution: Manually re-add the missing menu link.

**How to add an item to the admin short menu...**

Click Edit Shortcuts

Add a new shortcut

Enter a Title, A URL and then Save

You will now have the 'Find Content' shortcut in your admin shortcut bar as needed.

Side note:

If viewing admin/content you can also add the shortcut by simply clicking the + as noted in the graphic below:
> 4 votes

# Answer
Citricguy's answer is good, but it only adds a shortcut, when the op was actually asking about a menu item, which is what I wanted as well.

I've since realised that the default behaviour in Drupal 7 is for the admin (UID1) to get the "Management" menu as their black menu at the top, whereas all other users get the "Navigation" menu. You can however change this by granting users the permission "Use the administration pages and help". This is a valid solution because they will only see links to pages that they have permission to view/edit.

I personally think this should be the default behaviour (start off with everything, and then hide menu items that they don't have permissions for), but then I guess the current system allows you to manually hide certain menu items for non-admin users while keeping it for the admins. Certainly this area needs some thought as to the configuration options.

There's also the Administration Menu Source module, which allows you to "use a different menu as the Administration Menu. Configurable per role".
> 2 votes

---
Tags: 7, navigation
---


title: Where is $node->rendered being set?

text:
# Question
Title: Where is $node->rendered being set?
Given the following code:

```
function hook_search_execute($keys = NULL, $conditions = NULL) {
  // Build matching conditions
  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
  $query->join('node', 'n', 'n.nid = i.sid');
  $query
    ->condition('n.status', 1)
    ->addTag('node_access')
    ->searchExpression($keys, 'node');

  // Insert special keywords.
  $query->setOption('type', 'n.type');
  $query->setOption('language', 'n.language');
  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }
  // Only continue if the first pass query matches.
  if (!$query->executeFirstPass()) {
    return array();
  }

  // Add the ranking expressions.
  _node_rankings($query);

  // Load results.
  $find = $query
    ->limit(10)
    ->execute();
  $results = array();
  foreach ($find as $item) {
    // Build the node body.
    $node = node_load($item->sid);
    node_build_content($node, 'search_result');
    $node->body = drupal_render($node->content);

    // Fetch comments for snippet.
    $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);
    // Fetch terms for snippet.
    $node->rendered .= ' ' . module_invoke('taxonomy', 'node_update_index', $node);

    $extra = module_invoke_all('node_search_result', $node);

    $results[] = array(
      'link' => url('node/' . $item->sid, array('absolute' => TRUE)),
      'type' => check_plain(node_type_get_name($node)),
      'title' => $node->title,
      'user' => theme('username', array('account' => $node)),
      'date' => $node->changed,
      'node' => $node,
      'extra' => $extra,
      'score' => $item->calculated_score,
      'snippet' => search_excerpt($keys, $node->body),
    );
  }
  return $results;
}

```

Where does `$node->rendered` come from? Where is it defined and what does it contain?

# Answer
> 1 votes
`$node->rendered` is set in `node_search_execute()`:

```
$build = node_view($node, 'search_result');
unset($build['#theme']);
$node->rendered = drupal_render($build);

```

It contains the rendered node display for the search\_result view mode.

---
Tags: nodes
---


# Question
Title: Inserting Block with Custom Input Filter Module via Shortcode Causing http 500 error
I have a custom input filter module, and I am trying to figure out why it crashes when I attempt to insert a block into a post via a shortcode. The method works perfectly when I am inserting a string, but when I try to insert a block, it causes a http 500 error.

Any ideas? I am using Drupal 7.15. Also, I have tried the insert\_block module, and it generates a similar error...

**Here is the input filter process that works (with a string)**

```
function _related_links_filter_related_block_process($text, $filter, $format) {
   $shortcode_regexp  = "/\[block\]/";
   $output = "Text string inserted in via shortcode";

   return preg_replace($shortcode_regexp, $output,$text);
}

```

**Here is the input filter process that causes the error (with a block)**

```
function _related_links_filter_related_block_process($text, $filter, $format) {
   $shortcode_regexp  = "/\[block\]/";
   $block = block_load('block', 3);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

   return preg_replace($shortcode_regexp, $output,$text);
}

```

Any help is appreciated!

# Answer
A 500 error can be caused by lots of things. Your best bet is probably to use the Watchdog and/or Apache logs to narrow down the specific cause(s).
> 0 votes

# Answer
Figured out a way to do it without the 500 error, I tried loading a block in a different way and it worked. Don't know why module\_invoke() works over block\_load(), if someone can explain.

```
function _related_links_filter_related_block_process($text, $filter, $format) {
   $shortcode_regexp  = "/\[block\]/";
   $block = module_invoke('block', 'block_view', 3);
   $output = render($block['content']);

   return preg_replace($shortcode_regexp, $output,$text);
}

```
> 0 votes

---
Tags: 7, blocks, input-formats
---


# Question
Title: Adding jQuery to Drupal 7 site: drupal_add_js() adds but doesn't call?
I'm using jQuery accordion effects to display some information. I include the libraries:

```
    drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', file);
    drupal_add_js('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js', file);

```

Those seem to work fine, since after including them I can paste

```
jQuery(".accordion").accordion({collapsible:true,active:false});

```

into scratchpad and I get the functionality I want.

However, if I try to add it to my function like so:

```
drupal_add_js('jQuery(".accordion").accordion({collapsible:true,active:false});', inline);

```

...nothing happens. I've tried some variations, such as

```
drupal_add_js('jQuery(document).ready((".accordion").accordion({collapsible:true,active:false}));');

```

as well as moving the drupal\_add\_js() call further downstream in my code, so it appears after the elements it acts on are created and rendered.

How do I get this little snippet of code to run on my page?

# Answer
> 3 votes
You're most of the way there! You just need to convert what's in your ready() to a function:

```
drupal_add_js('jQuery(document).ready(function(){jQuery(".accordion").accordion({collapsible:true,active:false})});', 'inline');

```

Also, according to docs you should change your googleapi calls from file to 'external',

```
drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'external');

```

---
Tags: javascript, navigation
---


# Question
Title: How can I assign values to radio buttons with the forms api?
I made radio buttons with the forms api using this code:

```
"sex" => array(
    '#type' => 'radios',
        '#title' => t('Sex'),
        '#options' => array(t('M'), t('F')),
)

```

It works perfectly, but instead of storing an M or an F in the database, it stores a 0 or a 1. How can I decide what value is stored for each option?

# Answer
The keys of the array set as `#options` determine the values and the values determine the labels.

In other words: The example in my question uses a regular array `array(t('M'), t('F'))` which, behind the scenes, is an associative array using non-negative integers as keys (same as `array(0=>t('M'), 1=>t('F'))`. Since the radio buttons use these keys to know what to store in the database, the solution is simply to change them: `array('M'=>t('M'), 'F'=>t('F'))`.
> 1 votes

---
Tags: forms
---


# Question
Title: What can cause form API to ignore the weight of an element that is a collection of buttons?
I have two form elements on a node form I'm trying to order unsuccessfully. One is a standard collection of form buttons (submit, delete, etc) and another is a fieldset add by CCK. I am trying to order the submit button (one of the buttons in the collection) above the fieldset. I've set the #weight on the button collection (the parent form element of the submit) to a number lower than the #weight of the fieldset.

I've verified that after the #pre\_render calls in drupal\_render() the weight values I set earlier in my hook\_form\_alter persist. So nothing has changed them up to this point. I can confirm that changing the weight on the fieldset does it move it around, so I am having some impact on positioning.

Why does FAPI ignore the weights and still position the submit button at the bottom of the form? Or is there another point after drupal\_render() that allows other modules to change form element weights?

# Answer
I've discovered this is expected behavior. The solution is to copy the buttons into new form elements, position them where desired, and remove the default buttons. Here are step by step instructions on how to do this.
> 0 votes

---
Tags: 6, forms
---


# Question
Title: Failed opening required 'sites/all/modules/og/og.field.inc
I was trying to add the BoWoB Chat module to my site. It doesn't work and the error log file in its directory contain multiple lines like the following ones:

> Failed opening required 'sites/all/modules/og/og.field.inc' (include\_path='.:/usr/lib/php:/usr/local/lib/php') in /home/public\_html/mysite.com/sites/all/modules/og/og.module on line 16

Lines 15 and 16 are the following ones.

```
// Load all Field module hooks for Organic groups.
require(drupal_get_path('module', 'og') . '/og.field.inc');

```

The file og.field.inc is in the same directory as sites/all/modules/og/og.module and its permissions are 644, so it is readable.

This one has me stumped. Do you have any suggestion?

# Answer
> 1 votes
Your file at least needs to have 755.

With 644 it is readable, but is not executable so the file cannot be managed as a php file (executable).

# Answer
> 1 votes
You've probably checked, but is the owner/group of the file accessible for your webserver account? I.e. on Linux do a `ls -l` to see what the owner and group of the offending file is -- you can fix with, for example `chown www-data:[your group] og.field.inc`, depending on your setup.

Just be sure to match the other, working, files. Group/owner settings have bitten me before -- usually when doing stuff via root or sudo... Good luck!

# Answer
> 1 votes
I don't have an explanation for this, but have seen something similar before, not for OG though. For some reason I could not change permissions/open a file that I had uploaded via FTP. I ended up deleting the entire directory and putting a fresh tar up there.

# Answer
> 0 votes
Install registry\_rebuild in Drush, and then run `drush rr`.

> There are times in Drupal 7 when the registry gets hopelessly hosed and you need to rebuild the registry (a list of PHP classes and the files they go with). Sometimes, though, you can't do this regular cache-clear activity because some class is required when the system is trying to bootstrap.

# Answer
> 0 votes
Looks like php is looking in the wrong directory, `(include_path='.:/usr/lib/php:/usr/local/lib/php')` probably isn't where the file lives.

---
Tags: 7
---


# Question
Title: drush appears to not be respecting --no-backup
My server has a great backup system in place. I do not need additional backups dropped into my home directory.

Reading the drush docs gave me the impression that the `--no-backup` option, would instruct drush to not make a backup.

```
$ drush --version
drush version 4.5

```

When I update a module with the --no-backup option it seems to be ignored.

```
$ ls ~/
creds
$ drush dl drush --no-backup --yes
Would you like to back up your current drush version 4.5 to /home/username/drush-backups/unknown/20110823223228 and replace it with drush 4.5? (y/n): y
drush backed up to /home/username/drush-backups/unknown/20110823223228/drush  [ok]
Project drush (7.x-4.5) downloaded to                                [success]
/srv/www/_drupal_.example.org/drush.
Drush successfully updated to version 7.x-4.5.                       [success]
$ ls ~/
creds  drush-backups

```

Am I missing something obvious here? I have tried changing the order of the parameters, but that doesn't seem to make any difference.

# Answer
> 2 votes
This is a Drush bug, and would best be raised in the issue queue. By coincidence, someone recently posted this: http://drupal.org/node/1741108

---
Tags: drush
---


# Question
Title: Pulling Breadcrumb items from the Menu Link text instead of Title field (D7)
Some of my pages are pulling text for the last breadcrumb item from the menu link text. The rest of my pages are pulling text for the last breadcrumb item from the Title field. What I want is for all of the breadcrumbs to pull from the menu link text.

I'm using the Menu Breadcrumb module (applied to all of the pages in question) which allows the menu link text of a page to be added to the breadcrumbs, *but I do not have this option enabled*. My theme (a derivative of Omega) must be what's pulling the text into the breadcrumbs (I hear this is not done by default) because when I *do* enable the Menu Breadcrumb option I get either the menu link text *twice* or the menu link text *and* the Title text (depending on which page I look at).

Those pages pulling the breadcrumb item from the menu link text are of a specific content type which has a panel applied to it. The rest aren't using panels -- this is the main difference I can see which might explain this behavior.

I suppose I could alter the theme to not put the text item in, then enable the feature in Menu Breadcrumb (which behaves correctly), but obviously it is possible to do it the way I want without modifying the theme since it's happening with the panel'd type pages.

Any ideas?

Install Stats:

* D7
* Derivative of the Omega theme
* Context
* Panels
* Menu Breadcrumb (used on all pages; modified \- see post by pschnapp)
* Custom Breadcrumb (used only on two types, not the affected types)

# Answer
It's been a while since we came to a resolution on this issue, so I hope I get everything right.

It seems that I was a bit confused w.r.t. what fields data was being pulled from for these areas (menu item, title, & breadcrumb item). Here's what we found:

* Menu item text gets pulled from the "Menu link title" field in the "Menu settings" section of a page's editing interface.
* The text in the "Title" field of a type is used for the breadcrumb item text and will be used as the page's title as well (i.e. the title displayed in the browser window's/tab's chrome) if no other title is specified.
* The "Page title" field in the "Page title settings" section will override the "Title" field so far as the browser chrome title is concerned, but won't affect the breadcrumb.

IIRC, the "Page title" field was not active for the pages we were having trouble with, which was the cause of the confusion I was having.

It would be nice if instead of defaulting to "Title" for the name of this field, "Name" were used instead, as that's a bit more descriptive and would not lead to the confusion we had. The name of this field is changeable -- I'd recommend changing it to "Name".
> 0 votes

---
Tags: routes, panels, breadcrumbs
---


# Question
Title: Instantiating Fields: via UI, API or Drush?
Are there any benefits of using one method of instantiating over another?

From what I'm guessing, creating field instances via the API (programatically) has benefits over the UI since you get to version control the changes.

Drush commands can be put into a script as well and then version controlled.

Are there any other pros/cons to doing things programatically versus the UI?

# Answer
You can use Features to export your UI-created field configurations and version control the result. It's much faster to create and modify field instances in the UI unless you're extremely familiar with the Field API. I used to create fields programmatically but I feel like my time would have been better spent using the UI and occasionally exporting with Features for VCS/simpletesting.
> 2 votes

---
Tags: 7, entities
---


title: Digg like site in Drupal

text:
# Question
Title: Digg like site in Drupal
Is there a way to create a "Digg" like site in Drupal. Basically I want to create a site based in "social voting". The users should be able to vote on specific items and based on this "democratic" behaviour the popularity of that particular item would be determined. I did come across a module "drigg" but was not too impressed with it. Any other alternatives ?

# Answer
You should check on the voting api and maybe fivestar if you need a rating system. As MPD suggested, Flag could be helpful too for this. But for a digg like site,... I think your safest bet might be Vote Up/Down. Then of course, you'd need to create views to display the front page, or each different category based on how many votes your users submit.
> 2 votes

# Answer
An easy solution is to use the Flag module to create your votes. Then you can make a View, sorted by flags and potentially with other criteria (like date windows). You may also be able fold in criteria based on Radioactivity.
> 3 votes

# Answer
For historical reason I'd like to mention the Drigg module and the now defunct Drigg site aimed to build Digg in Drupal.
> 0 votes

---
Tags: 7
---


# Question
Title: how to change value of submit button of comment form?
I wanted to change the default value of submit button in comment form from "Save" to "Post". I wanted to do that using a module , not javascript. So I wrote the following code in my module.

```
 function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id){

     $form['actions']['submit'] = array(

      '#value' => t('Post Comments'),
     );
     }

```

But instead of changing the value of submit button, this module is making the submit button hidden. If I add `return $form` , then the submit button displays but with the same default text "Save". Any suggestions please. Thank you.

# Answer
> 4 votes
You're replacing the entire element at the moment (which is why it doesn't show). You can change a specific property in the array like so:

```
$form['actions']['submit']['#value'] = t('Post Comments');

```

That way you're just setting the `#value` property, and not removing the other properties that already exist for the element.

---
Tags: forms
---


# Question
Title: How do I properly print the $node array in a views row template?
I'm writing a custom views-view-row-rss--content-type.tpl.php file in Drupal 6.

How do I properly print the `$node` array?

I have tried `print_r($node)` and even used `node_load()`. I'm not sure where to go next.

# Answer
Install and enable the Devel module.

Next, wrap the variables you wish to debug in dpm() or dd()

dpm() will output to the browser if possible.

dd() will output to a file on your server. For example on my Ubuntu dev box it outputs by default to `/tmp/drupal-debug.txt`
> 0 votes

---
Tags: views, feeds
---


# Question
Title: Drupal Form API Callback For Displaying a Table on the Same Page
I'm at an absolute loss as to how display a table and a form on the same page.

My objective is to publish information comparing our user data with our billing gateways data. My first thought was to create a dummy form item that can have it's values replaced by the submit handler akin to this Table and Form in the same page but that didn't appear to work with my callback.

My next attempt was to create a embedded form that upon a successful submission callback replaced information in the original render array. The idea of the code is to publish the 'one' in all the values before the submit button is called and 'two' after it is called. Here is that code:

```
function test_lookup_page($email = NULL){
    $hinput = array('One Customer Information' => 'aci', 'Two Customer Information' => 'uci');

    $header = array(
        'Legend' => array(
          'data'  => t('Legend'),
          'id'    => 'head-legend',
          'class' => 'col-legend',
        ),
      );

    foreach ($hinput as $hkey => $hvalue){

         $ckey[$hkey] = array(
          'data' => $hkey,
          'id'    => 'head-' . $hvalue,
          'class' => 'col-' . $hvalue,
        );
    $header = array_merge($header, $ckey);
    }

      // Table rows
      $rows = array(
        array(
          // Column 1
            'customer' => array(
            'data'  => t('Customer Account'),
            'id'    => 'row1-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row1-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row1-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 2
          'billing' => array(
            'data'  => t('Billing'),
            'id'    => 'row2-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row2-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row2-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 3
          'shipping' => array(
            'data'  => t('Shipping'),
            'id'    => 'row3-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row3-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row3-uci',
            'class' => 'col-uci',
          ),
        ),
        array(
          // Column 1
          'subscription' => array(
            'data'  => t('Subscription(s)'),
            'id'    => 'row4-legend',
            'class' => 'col-legend',
          ),
          'One Customer Information' => array(
            'data' => 'first',
            'id' => 'row4-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'first',
            'id' => 'row4-uci',
            'class' => 'col-uci',
          ),
        ),

      );

        $build = array(
        'header_text' => array(
          '#type' => 'markup',
          '#markup' => '<p>' . t('To add additional content to a form page, you can use a page callback and return a render array like this.') . '</p>',
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
        ),

        'test_order_admin_form' => drupal_get_form('test_order_admin_settings', $email),

      );
      return $build;
    }

  function test_order_admin_settings($form, &$form_state, $email = NULL) {

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('test_order_lookup'),
);

return ($form);

```

}

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

     $hinput = array('One Customer Information' => 'aci', 'Two Customer Information' => 'uci');

     $header = array(
      'Legend' => array(
        'data'  => t('Legend'),
        'id'    => 'head-legend',
        'class' => 'col-legend',
      ),
    );

     foreach ($hinput as $hkey => $hvalue){

       $ckey[$hkey] = array(
        'data' => $hkey,
        'id'    => 'head-' . $hvalue,
        'class' => 'col-' . $hvalue,
      );
      $header = array_merge($header, $ckey);
   }

// Table rows
        $rows = array(
        array(
          // Column 1
            'customer' => array(
            'data'  => t('Customer Account'),
            'id'    => 'row1-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row1-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row1-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 2
          'billing' => array(
            'data'  => t('Billing'),
            'id'    => 'row2-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row2-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row2-uci',
            'class' => 'col-uci',
          ),
        ),
          array(
          // Column 3
          'shipping' => array(
            'data'  => t('Shipping'),
            'id'    => 'row3-legend',
            'class' => 'col-legend',
          ),
            'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row3-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row3-uci',
            'class' => 'col-uci',
          ),
        ),
         array(
          // Column 1
          'subscription' => array(
            'data'  => t('Subscription(s)'),
            'id'    => 'row4-legend',
            'class' => 'col-legend',
          ),
          'One Customer Information' => array(
            'data' => 'second',
            'id' => 'row4-aci',
            'class' => 'col-aci',
          ),
            'Two Customer Information' => array(
            'data' => 'second',
            'id' => 'row4-uci',
            'class' => 'col-uci',
          ),
        ),

      );

        $build = array(
        'header_text' => array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
        ),

      );

       return ($build);

       }

```

# Answer
> 6 votes
The submit handler isn't the right place to build a display, the core form builder functions don't actually assign the return value to anything so it's essentially ignored.

The normal process for this sort of thing is to set `$form_state['rebuild'] = TRUE` in your submit handler, generate the table and add it back on to the `$form_state`, and then let the form builder function decide what to display depending on the existence of that value.

This is a skeleton example which should help:

```
function MYMODULE_some_form($form, &$form_state) {
  if (isset($form_state['table'])) {
    $form['table'] = $form_state['table'];
  }
  else {
    // Otherwise build the form as normal
    $form['some_field'] = array(
      '#type' => 'textfield',
      // etc...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['table'] = function_to_generate_table($form_state);
  $form_state['rebuild'] = TRUE;
}

```

There are various different permutations of that (depending on where you want to build the table based on the form state values; it could be the submit handler, form function or a helper function), just put your code wherever you feel most comfortable with it.

---
Tags: 7, forms
---


# Question
Title: What is the best module for student registration form
What is the best module to use if i want to create a student registration form for my website.

Some of the fields in this form is referred to taxonomy and content types as entities.

Im a novice user of drupal 7 and cant find any mdoule that does this, I keep getting FORM API tutorial in my seaches but I when I checked it involves a lot of programming.. :(

Thanks

# Answer
Webform module is pretty popular among Drupalers for registration forms. It is quite well supported and documented. It also has many cool in-built features and a few other 3rd party modules that bring in even more sizzle to the mix.

Good-luck to you friend & welcome to drupal.stackexchange.
> 2 votes

---
Tags: 7, forms
---


title: Sass/Compass tutorial for Zen?

text:
# Question
Title: Sass/Compass tutorial for Zen?
I'm trying to understand sass and compass so that I can take advantage of them when subtheming Zen, but I'm having trouble finding a good tutorial.

All of the documentation I find seems to already expect me to understand what the heck they are talking about. :) I've got a full understanding of standard CSS, that's not the issue.

I'm trying to do just the simplest thing and I'm not sure what the next step is. For example, by default the max-width is 1200 in the sass/layouts/responsive-sidebars.scss. I would like to change it, but when I make changes to responsive-sidebars.scss nothing in my actual presentation changes (I'm assuming because the actual presentation is using the actual css files in css/layouts/responsive-sidebars.css).

What am I missing? Do I need to do something to actively translate the scss file into the css in the other directory?

# Answer
Nevermind, I finally found this documentation on how to get started and how to automatically convert the scss files into css files:

http://drupal.org/node/1548946
> 0 votes

---
Tags: 7, theming
---


title: Custom validation for profile type?

text:
# Question
Title: Custom validation for profile type?
I used `profile2 module` and create some profile types,in one of them I have a custom field require custom validation . I did use drupal validation with custom validation function . Lets suppose I have a field with name 'nationalcode' if it was form element just need this in my custom module hook\_form\_alter(&$form,&$form\_state)

```
$form['field_nationalcode']['#validation'][] = 'my_custom_validation_function';

```

And determine **my\_custom\_validation\_function** function with my custom validation

```
function my_custom_validation_function(&$form,&$form_state) {
  if(!mycustomvalidation)
     form_set_error('field_nationalcode','my custom message');
        // I am not sure mayebe this one
     form_set_error('nationalcode','my custom message');
 }

```

But really what I should do in profile type cusotm validation?

I set `#validation` but How can i set form\_set\_error with profile type? .I means what i should use in first parameter in `form_set_error` ?

# Answer
> 0 votes
I found The good solution for validate nested form elements according to drupal 7 form\_set\_error api need to use

```
form_set_error('myporifletypename][myfieldname', 'my error message');

```

As example

```
 form_set_error('user_info][field_nationalcode', 'Your National code not valid');

```

---
Tags: forms
---


title: Jquery in my custom zen theme

text:
# Question
Title: Jquery in my custom zen theme
the following is my js file mymodule.js

```
$(document).ready(function(){

    alert('test');
});

```

and i just add this file in my customtheme.info .

scripts\[\] = js/mymodule.js

However, the js code only be executed at some pages, not all pages.

What could the problem will be?

Does anyone have the same situation before?

Please help me fix this.

# Answer
> 0 votes
In Drupal 7 to avoid conflicts with another library you should wrap your code in:

```
(function ($) {
  // Original JavaScript code.
})(jQuery);

```

To learn more visit: http://drupal.org/update/modules/6/7#javascript\_compatibility

# Answer
> 0 votes
Try it by implementing hook\_init() into your .module file:

```
function YOURMODULE_init() {
    drupal_add_js(drupal_get_path('module', 'YOURMODULE')  ."/YOURSCRIPT.js",  array('every_page' => TRUE));
}

```

Also make sure your module is in its proper place: sites/all/modules/YOURMODULE or a subfolder of this.

---
Tags: javascript
---