# Question
Title: Example of entity-within-entity subform processing
Suppose that, in Drupal 7, EntityA includes one or more instances of EntityB.

Is there an example of building the create/edit form for EntityA that includes one or more edit forms for EntityB, and that can ajax in a new create form for a new EntityB?

# Answer
> 3 votes
It's not really that hard. You would want to create form elements that use the `#tree` attribute, to make sure the data for instances of EntityB will be well structured.

In order to make add another functionality you need to:

* Keep track of the count in the `$form_state`.

```
if (empty($form_state['count'])) {
  $form_state['count'] = 2;
}

```
* Add a button somewhere to add another.

```
$form['entity_b']['add_another'] = array(
  '#type' => 'submit',
  '#value' => t('Add another'),
  '#limit_validation_errors' => array(),
  '#submit' => array('add_another_submit_handler'),
);

function add_another_submit_handler(&$form, &$form_state) {
  // Add one to our counter and rebuild the form
  $form_state['count'] += 1;
  $form_state['rebuild'] = TRUE;
}

```

The above will work with no JavaScript. If you want to Ajax-enable it, you need to do some work on the wrapper.

* Add a CSS ID that is used from the Ajax callback.

```
$form['entity_b'] = array(
  '#tree' => TRUE,
  '#attributes' => array('id' => array('add-another')),
  // ...
);

```
* Add the `#ajax` element.

```
 // ...
 '#ajax' =>  array(
  'callback' => 'add_another_ajax',
  'wrapper' => 'add-another',
  'effect' => 'fade',
 ),
 // ...

```
* Add the Ajax callback function.

```
function add_another_ajax($form, &$form_state) {
  return $form['entity_b'];
}

```

# Answer
> 1 votes
See my approach at rszrama's sandbox: Commerce Inline Product Form. I am planning to promote it to a full project this week. I am going to call it "Entity Inline Form" or "Inline Entity Form", since it can support any entity type.

Basically, you're either doing what that module does (having custom built forms for the embedded entity B), or using Subform to embed the original add / edit form of entity B. A third option would be to have a dialog in which the add / edit form is displayed (so that it's not embedded into the main form at all), and JS code that notes the final entity ids after the dialog is closed.

---
Tags: forms, entities
---


title: Filter taxonomy term on content type

text:
# Question
Title: Filter taxonomy term on content type
I'm currently running Drupal 7 and have got some taxonomies setup.

I also have different content types which live under the same taxonomy terms but want to be able to filter a term by content type.

What's the best way to do this in Drupal 7? I've looked into the Views module which looks like it's the right way to go.

I've also looked at this article: http://www.braahm.be/posts/tuning-taxonomy-pages-page-manager-panels-views-and-custom-build-modes-drupal-7 and Filter by content type and shared taxonomy terms but they seem a bit over the top for what I want to achieve.

Cheers,

James

# Answer
Views is the standard option for achieving your goal. Check out this video series to learn more
> 0 votes

---
Tags: views
---


title: Alternative to drupal_goto() function?

text:
# Question
Title: Alternative to drupal_goto() function?
I need to use an alternative function to replace `drupal_goto()`. The reason is that this function is causing me a problem to run cron.php. The code is:

```
    if(is_int($order_id)) {
$path = 'admin/commerce/orders/' . $order_id;
drupal_goto($path);
}
else {
  drupal_goto('admin/commerce/orders/');
}

```

# Answer
> 7 votes
The problem is not drupal\_goto() but your usage of it in a node. THere is a long standing issue in Drupal core to deal with this but I honestly think doing this is just wrong.

Instead of putting it in a node, you should create a custom module and put it in a page callback. See What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc? why it's a bad idea in general to use PHP in nodes, blocks and so on. You've seen one of those yourself, namely that it can be extremely hard to find out where the problematic code is actually coming from.

That said, the last comment in the linked issue points to a Field redirection module that is however currently limited to user/node references and links. And it's not dynamic as your code is. But again, for something like that you really should be creating a custom module.

# Answer
> 4 votes
I'm not sure why you're having problems with `drupal_goto()`, but if you need a no-frills alternative, some old school PHP would do it:

```
function my_goto($path) {
  header('Location: ' . $path, TRUE);
  exit;
}

```

This doesn't differ very much from the `drupal_goto()` function itself, except that it doesn't set a response code, and it pays no attention to any `destination` you have set in the query string (which `drupal_goto()` does).

---
Tags: cron
---


# Question
Title: Can I force cron to process all of my queued tasks?
My D7 module uses hook\_cron to mirror a big external datasource locally. For each new or updated row, $queue-\>createItem() schedules a task requiring several external API round trips to build the locally mirrored row.

I might queue 750 tasks but Drupal only runs 50 on a cron. How do I make all queued tasks run on each cron?

Please note:

* There are no errors reported in /var/log/apache2/error.log
* The latest message in admin/reports/dblog reports "Cron run completed." (looks successful)

# Answer
Basically PHP has memory and execution time limitations, so if you try to do a huge import of an external database you'll run out of runtime if not memory.

So the solution is to spread it out over many http requests, each doing a smaller chunk of the job.

For this, Drupal has the Batch API, which you can call from cron as needed.

Here's the Examples project's Batch example (with tests!) to guide the way. And a decent explanation with some code samples.
> 2 votes

# Answer
For completeness, two additional solutions:

* You can define a custom time limit for your queue in hook\_queue\_info(), that is however limited by PHP's total execution time.
* You can manually call cron as often as it takes. This is easy for task that you really only have to do once to work through the initial amount of tasks/items. If you have drush, you can execute something like following, which will execute cron over and over again until you manually stop it: `while [ 1 == 1 ]; do drush cron; done`. There might be nicer ways to do that but it works and it also prevents issues with time execution and memory limits.
> 1 votes

---
Tags: cron
---


# Question
Title: How do I create a View of different entity types?
I haven't used Views much before but it feels like I should be so I'm getting stuck in...

I think I'm missing something obvious here but how would I go about creating a view that 'mixes' several different entity types?

I have a custom field type attached to nodes, users, and also to user profiles provided by the Profile2 module. The field contains lat/long data (I know OpenLayers etc. provide this functionality, the field type was built as an exercise).

How can I create a view that contains all of the different entities that have this lat/long field associated with them? I'm basically after a simple table with 'Entity Title', 'Lat' and 'Long' as columns.

All of the different entity types are separated when I create a view (Content, Users & Profile) and I can't find a way to group them together so to speak.

Is this possible with Views or is not quite there yet with regard to entities?

# Answer
Views uses a term it calls `base table` translated into SQL it is the table used for the initial query

```
SELECT something FROM {base_table};

```

The thing is that what you want to do is a bit atypical, instead of doing

```
SELECT something, field_item FROM {entity} LEFT JOIN {field};

```

You want to do

```
SELECT something, field_item FROM {field} LEFT JOIN {entity};

```

In order to do this you need to use the field you are after as the base table. By default this is not possible, but it's not much work required in order to do it. What you need to do, is to use `hook_views_data` or `hook_views_data_alter` and add the data for the field table and make it selectable as base table displayed when you create a view.

There's a lot of doc on how to do this (the Views doc), and I have written this in one or more answers here. So I won't bother explaining how to do this.
> 5 votes

---
Tags: 7, views, entities
---


# Question
Title: When is the available 'language: English French...' link displayed under translatable content?
I am struggling with the i18n configuration of my site and the display of the available translated content 'languages' link displayed next/under the content.

Under which condition will this link be displayed for translated content?

1. The content type is translated-enabled
2. The language field must be displayed/visible in the content type configuration
3. There must be more than one language made available
4. The content must be translated
5. ...?

I guess all the above apply, but is there more?

The reason I am asking this is because I believe I have configured my site properly, but I still don't see that link to jump between translated content. I am looking for a check list to find my error(s) or misunderstanding. Thanks.

# Answer
I'm guessing this is your other question!

I'm not exactly sure but I just did this from scratch on my Drupal test site and found it to work.

1. **Modules** \- The only module I have enabled is **Multilingual content**
2. **Content Type** \- **Edit** \- **Publishing options** \- Enabled, with translation
3. **Content Type** \- **Edit** \- **Multilingual settings** \- Nothing selected except 'Normal'
4. **Regional and language** \- **Languages** \- Multiple languages enabled
5. **Regional and language** \- **Multilingual settings** \- **Node Options** \- Hide content translation links is not checked

i18n can definitely be uncooperative...
> 1 votes

---
Tags: 7, nodes, i18n-l10n
---


# Question
Title: What should I do to use a more recent jQuery version?
I am trying to use this jQuery Bubble script plugin with my Drupal 7 site. The plugin requires Jquery 1.6.2 (Drupal 7 only comes with 1.4.4).

There are some solutions on the net but none seem to work:

* jQuery Update: It only updates jQuery to 1.5. There is a sandbox version that will update it to jQuery 1.8, but its too complicated to use.
* jQuery Multi: I have installed 1.6.2 using this module; however, my site still loads the default jQuery 1.4.4. Version 1.6.2 does not seem to load.
* Using Newer Versions of jQuery: This is a technique for loading multiple jQuery in Drupal 6. Although it works in Drupal 7, my Bubble plugin wont run.

My site is only a simple 1 page webform, so I would be happy if I could supress the default 1.4.4 and then just link to 1.6.

# Answer
> 3 votes
Looks like there is a patch for the jQuery Update module to update it to jQuery 1.7.

# Answer
> 2 votes
The jQuery Multi module, which you mention in your question, uses jQuery's noConflict() mode. If you installed jQuery Multi and jQuery didn't load, it's likely that you didn't specify any files to load with the new version of jQuery. If you don't specify and files or libraries using the UI or provided hooks, jQuery won't be loaded by default. There is a setting in the configuration form to load jQuery even if no files are targeted to use it.

To use jQuery 1.6.2 with your script, you have to write code to target that file, or put it as a library in the sites/all/libraries folder and select it in the jQuery Multi UI.

If this still doesn't work, try posting an issue in the issue queue!

---
Tags: javascript
---


# Question
Title: Drupal 6 database has mixed InnoDB & MyISAM. Need to fix before migration
I have a Drupal 6 database with tables which are a mixture of InnoDB and MyISAM. I'm using the Acquia Dev Desktop stack. The core module and other tables created at installation are MyISAM, and the tables for modules I've since installed are InnoDB. I didn't think at this issue when I started this project, and need to move my Drupal site to a new dev. environment I created on WebEnabled. So I have a couple of questions:

1. Since my Acquia MySQL default settings are set to InnoDB, can I safely change this to MyISAM without causing problems within my site?
2. I tried using the DB Tuner module to change all my tables to MyISAM. It worked but then I checked the status report and it said that all those tables that were converted were now "mis-matches". I restored from a backup at that point. Am I going to have to uninstall all the contributed modules and re-install them as MyISAM to avoid getting mis-matched errors.

Thanks a lot.

Jason

# Answer
You could use the backup & migrate module to backup your DB. Then take this text file (UTF-8) and change all MyISAM strings to InnoDB. Save it and restore this backup. Done.
> 2 votes

# Answer
You may want mysql to write the script for you

Let's start with the base query

```
SELECT CONCAT('ALTER TABLE ',table_schema,'.',table_name,' ENGINE=MyISAM;') SQLCommand
FROM information_schema.tables WHERE engine = 'InnoDB';

```

Let's run it at the command line and save it to a SQL text file and display it like this:

```
mysql -uroot -AN -e"SELECT CONCAT('ALTER TABLE ',table_schema,'.',table_name,' ENGINE=MyISAM;') SQLCommand FROM information_schema.tables WHERE engine = 'InnoDB'" > /root/MassConvertInnoDBToMyISAM.sql
cat /root/MassConvertInnoDBToMyISAM.sql

```

Next, login to mysql. From the mysql prompt, run the script:

```
mysql> source /root/MassConvertInnoDBToMyISAM.sql

```

Give it a Try !!!
> 2 votes

---
Tags: database
---


# Question
Title: How to handle ajax wrapper id for list of similar ajax forms?
Consider a Drupal 7 page with a list of same-type entity forms: formA, formB, formC. The entity form uses ajax to replace part of itself.

Is there an established way to manage the wrapper id's so that an ajax call for formA knows to replace the wrapper div in formA? If I don't change the wrapper id's, I would have three divs on the page with the same ID.

# Answer
> 2 votes
You can use `drupal_html_id()` which:

> Prepares a string for use as a valid HTML ID and guarantees uniqueness.

e.g.

```
function my_form($form, &$form_state) {
  $id_string = 'my-element-id';
  $unique_id = drupal_html_id($id_string);

  $form['element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#ajax' => array(
      'wrapper' => $unique_id,
      // ...
    )
  );

  $form['output'] = array(
    '#prefix' => '<div id="' . $unique_id . '">',
    '#suffix' => '</div>',
    '#markup' => 'Some markup'
  );
}

```

That should guarantee that the AJAX will work no matter how many different instances of the same form you create.

---
Tags: forms, ajax
---


# Question
Title: How do I modify email headers when using Rules to send mail?
I'm using the Drupal 7 Rules module to trigger and send emails on specific events, but need to modify the email headers before the message is sent.

What would be the appropriate way to add 'reply-to' headers (as used in RFC 5322) to specific outgoing emails that are sent using the Drupal 7 Rules module?

The following works when using drupal\_mail() but I do not see how to apply this hook when using Rules.

```
function hook_mail($key, &$message, $params) {
    switch ($key) {
        case 'key_name_here':
            $message['Reply-to'] = $params['mail'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];
            $message['headers']['Reply-To'] = $params['mail'];
            break;
    }
}
// One note to the above script, lines 4 and 7 seem redundant and likely need work.

```

# Answer
> 2 votes
You can still use hook\_mail, you just need to identify the key for the rule or rules you want to override. The key is set in the rules\_action\_mail() function `$key = 'rules_action_mail_' . $name . '_' . $element->elementId();` where name is the rule name and element id is the numeric id for the rule. You need to make sure your custom module has a higher weight that the rules module in the system table of your database.

---
Tags: rules, emails
---


# Question
Title: Why should we avoid theming forms with template files?
The issue was raised in this question. Why not exploit the advantages that template files offer in the case of forms?

# Answer
I can see no good reason for not using a template file to theme a form. As I stated in that question, the simple #prefix and #suffix tricks might not be enough, say if you wanted the entire form to be a table rather than div based. I've used drupal\_render with a form element parameter in a template to draw the individual fields in the form, but make sure you call drupal\_render without an argument at the end of the template to populate the rest of the form, such as the form hash etc. as it won't validate.
> 2 votes

---
Tags: forms, theming
---


# Question
Title: How to remove a prefix with hook_form_alter?
Looking at the source of a module, it is doing this:

```
$form['buttons']['back'] = array(
  '#prefix' => t('or'),
);

```

Now I want to remove that prefix; I tried the following code, but it doesn't make any difference.

```
function mymodule_form_formid_alter(&$form, &$form_state) {
  $form['buttons']['back']['#prefix'] = '';
}

```

I tested the following code, but it doesn't seems to work; the prefix is now 'testingor'.

```
function mymodule_form_formid_alter(&$form, &$form_state) {
  $form['buttons']['back']['#prefix'] = 'testing';
}

```

I tried the following code, but it doesn't make any difference.

```
function mymodule_form_formid_alter(&$form, &$form_state) {
  unset($form['buttons']['back']['#prefix']) ;
}

```

What am I doing wrong?

The form ID for the form I am trying to change is "commerce\_checkout\_form\_checkout" which is used from the Drupal Commerce module.

# Answer
> 1 votes
In your hook\_form\_alter the following should do the job and has the benefit of leaving the element there if required.

```
$form['buttons']['back']['#access'] = false;

```

---
Tags: 7, forms, commerce
---


# Question
Title: How many times drupal calls hook_node_presave for a node?
During debugging my code I noticed that `hook_node_presave()` is called 3 times when I edit a node. Why?

I use the following code to count how many times the function is called:

```

function mymodule_node_presave($node) {
  static $counter = 0;

  // Some code...

  $counter++;
  watchdog('mymodule', "hook has been called $counter");
}

```

# Answer
Once.

If it's called multiple times then you your node is saved multiple times.

This might be because you have some rules or other code that e.g. resaves the node in a hook\_node\_insert()/update().

To find out what and where, enable devel.module if you haven't already and add a `ddebug_backtrace()` call to your hook. That will give you the backtrace on how your function was called and you can identify who is calling node\_save().
> 1 votes

---
Tags: hooks
---


# Question
Title: How to change the order of form elements in a modal user login form
I have a modal form for user login. I want to rearrange the links. I enabled captcha for user login form. Now i want to display 'Create New Account' and 'Forget Password' links to be displayed below the 'Login' submit button. I need help on how to do this. Thanks in advance.

# Answer
> 4 votes
@jags: Always make sure to mention what version of Drupal you are working on as the answers could be sightly different for different Drupal versions.

You essentially have to change the HTML that gets generated to render the form. Such 'theme override' can be done at multiple places. In your case a good place to do so is the theme layer. Assuming that you are on version 7, the below is what you will need to do -

1. In your theme's directory edit the file called 'template.php' to register a new theme function

```
/**
 * Implementation of HOOK_theme().
 */
function THEME_NAME_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  // Add your theme hooks like this:
  $hooks['FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT'] = array(
      'arguments' => array('form' => NULL),
    );
  return $hooks;
}

```
2. Now create the new theme function and make changes to the '#weight' property of the desired elements to change the order in which they appear in the form

```
function cio_st_FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT($form) {
  dsm($form); // This line will show you the content of $form and help you know which attribute you would like to edit. You will be able to use this function only if the devel module is turned on.

  // Make the changes in the '#weight' attribute of the desired elements to change the order in which they get rendered.

  return drupal_render($form);
}

```
3. The line `dsm($form)` is just for your help. Do not forget to remove/comment it once you are done with the changes.
4. **NOTE** You will be required to clear you sites theme registry cache to see the changes take affect.

Hope this helps :-)

---
Tags: users, javascript
---


title: Blogging platform using Drupal 7

text:
# Question
Title: Blogging platform using Drupal 7
I am planning to make blogging platform using Drupal 7. In which I am going to allow user to create his own site using my subdomain. Is this possible with Drupal 7?

Which modules I am going to need?

# Answer
> 0 votes
If I understand correctly, you're looking at either the core blog module (which isn't that great), or a combination of content types and Views.

Start here for blog building information!

With regards to the second part, are you looking to have the user create a site, and then start blogging on it? Wordpress.org style? For that you'll firstly need to get a solid theme in place, as well as a working blog. Secondly, look into Aegir which is a REALLY solid, powerful tool for creating Drupal sites off the back of another site (using a site as an installation profile almost...but not quite).

There are a couple of installation/demonstration videos here and here.

# Answer
> 0 votes
Blog as such is a standard content type comes with a core! What you might require though is to maintain different user profiles for which you may need Profile2 module.

---
Tags: 7
---


# Question
Title: Mandatory field (A or B) in a content type
I have a content type (external\_document) that has an entity relation to an "event" and an entity relation to a "project."

I would like to be able to have some validation rule saying: All the documents must be "linked" to either an event or a project.

I am unclear on the following:

* How to do it on D7?
* What is the proper name for that in Drupal so I can search it?
* Is it the "Drupal" way of doing the content type with 2 entity relations?

# Answer
> 2 votes
You could use the Field validation module to take out some of the legwork.

> This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

There's a validation rule built in for

> Require at least one of several fields

which is exactly what you're after.

# Answer
> 1 votes
**How to do it**

In a custom module, you can implement hook\_node\_validate and check whether your condition is met.

If you want to mark the fields as required you could add this with jquery:

```
var requiredHtml = '<span title="Required" class="form-required">*</span>';
$("label[for='edit-field-move-teil-aufenthaltsbewil-value']").append(requiredHtml);

```

jQuery let's you do even more sophisticated things like removing the required mark on the fly from the second entry, if the first one contains (valid?) data.

But remember while jQuery checks can improve usability, they never replace the checks on the server side. Client side checks can always be bypassed by clever users.

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


# Question
Title: How to parse out links and img src references from body copy?
I need to modify links and img references in the body of nodes and comments. MPD already gave me good advice regarding using a script.

Is there an easy way in Drupal or PHP to parse out all the links in the body copy?

# Answer
> 12 votes
It's never easy to do something like this because parsing HTML is a bit hit-and-miss, depending on how well formatted the input is.

I've always found the best way to do it is to load the HTML into a `DOMDocument` object, loop through and change whatever element attributes/values I need to, then use the `DOMDocument` to give me the new output.

This is a very rough example but hopefully it'll give you the idea:

```
$html = '
  <p>Blah blah blah</p>
  <p><a href="/some-path" title="A Title">Link Text</a>
  </p><p><img src="/some-path.jpg" alt="Some alt" /></p>';

$doc = new DOMDocument;

// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc->loadHTML($html);

// Get the links.
$links = $doc->getElementsByTagName('a');
foreach ($links as $link) {
  // Change the value of an attribute based on the current value.
  if ($link->getAttribute('href') == '/some-path') {
    $link->setAttribute('href', '/some-other-path');
  }
}

// Get the images.
$images = $doc->getElementsByTagName('img');
foreach ($images as $image) {
  // Change the value of an attribute based on the current value.
  if ($image->getAttribute('src') == '/some-path.jpg') {
    $image->setAttribute('src', '/some-other-path.jpg');
  }
}

// Get the new HTML
$new_html = $doc->saveHTML();

// Strip out the tags that loadHTML() introduces to get the clean HTML.
$patterns = array("/^\<\!DOCTYPE.*?<html><body>/si", "!</body></html>$!si");
$body_text = preg_replace($patterns, '', $new_html);

// Update the node body.
$node->body[$node->language][0]['value'] = $body_text;

```

**EDIT**

I knew I'd seen a good question about this on SO; have a look at How to parse and process HTML with PHP? for a good discussion on the subject in general.

# Answer
> 1 votes
As I answered in your other question, filters are the proper solution since they won't actually alter the data, but the output. This means that should you want to change it differently (or fix a conversion bug), data is still there.

Just check the documentation on hook\_filter\_info() and have a good time parsing HTML with PHP.

# Answer
> -1 votes
Maybe you are not looking at the good way.

Have you try to make a replace in the database?

```
update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, 'find this string', 'replace found string with this string');

update client_table set company_name = replace(company_name, 'Old Company', 'New Company')

```

I have use use them for some migrations. It's no easy—you must check and map all the replace—but it works.

---
Tags: 7, migrations
---


# Question
Title: Easiest way to hack Drupal 6.22 installation for security audit
I am doing a security audit for a client. Their installation is Drupal 6.22. I need to show them it's unsafe. What is the easiest way to hack it as an example?

I would need to directly show them the steps, so it must be quite detailed instructions. They have the following modules installed:

1. Administration menu
2. Color
3. Comment
4. Database logging
5. Help
6. PHP filter
7. Taxonomy
8. Update status
9. Masquerade
10. CKEditor
11. AES

Here are some common settings:

1. Server Apache/2.2.3
2. MySQL database 5.0.77
3. PHP 5.2.17
4. update.php Protected
5. File system Writable
6. register\_globals Disabled

# Answer
> 4 votes
The question you're asking is pretty impossible to answer. If you know Drupal and/or web security then you'll know the answer already. If you don't then the answer is too long to put into a Stack Exchange comment.

Here are some articles about how I have gained knowledge of web application security and how I perform a security audit of a Drupal site:

I agree with Ivan Alfaro that the security\_review module is a good start. Many of the elements that the security\_review module audits can be audited from outside a site, so you could look at what it does and see if you can do similar things.

# Answer
> 2 votes
Easiest way to identify potential vulnerabilities is to install the Security review module.

---
Tags: security
---


title: Drupal Commerce SKU generator

text:
# Question
Title: Drupal Commerce SKU generator
I am building a Drupal Commerce site and I had the weirdest request:

Upon creating a new product, the client want's to select the product's category from a select list or something similar. This should result in the first part of the product's SKU, say

"CAT007"

Then he want's to select another attribute for that specific product which produces the second part of the SKU, say

048

So the complete SKU of the product would be CAT007.048 thus resulting in a unique identifier. The reason for this is that he doesn't want to look within huge arrays in order to produce the correct SKU.

My problem is that I can't seem to find a decent solution with which I can give the client access and management over the arrays.

Can anyone come up with something?

EDIT something that came to mind was taxonomy terms that contain a field with their SKU prefix/suffix. The problem that arises from that is how can I pass the tid from the user's selection (javascript) to the php side in order to do a term\_load() and get the field's value.

# Answer
By using `taxonomy_vocabulary_machine_name_load()` and `taxonomy_get_tree()` I was able to extract the 2 taxonomies I needed for creating the prefix and suffix of the SKU.

I created tables of key, value pairs that contained the tids and the SKU codes.

By using `json_encode()` I was able to pass those tables into an inline js script I attached to commerce's product form using `$form['#attached']['js']`.

Now by having a JavaScript array mapping tids to SKU parts, it's easy using jQuery to fill in the SKU textfield accordingly. :)
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How to set a field's 'translatable' property
When I create a new field type in Drupal it seems to be automatically assigned a 'translatable' property and it's not always right. For example, I would expect a Long Text field type to be marked as translatable = TRUE, but for some reason it's coming in as FALSE sometimes. However, body is TRUE.

Is there a place where this property is exposed in the UI and changeable?

I have the i18n module installed and enabled.

# Answer
Entity translation exposes a checkbox which allows to set the translatable property.

It also provides a user interface to actually use field translation, there isn't much you can do with translatable fields without that module anyway.
> 2 votes

# Answer
Try the following code:

```
function mymodule_field_available_languages_alter(&$languages, $context) {
  $languages = array();
}

```

The hook is documented in Multilingual Field API, and hook\_field\_available\_languages\_alter().

*somehow i18n does not respect that ..*
> 0 votes

---
Tags: entities, i18n-l10n
---


title: URL function with i18n localization

text:
# Question
Title: URL function with i18n localization
I'm using the Rate module for voting. When an anonymous user clicks on the voting widget, the user is redirected to a url "user/login-to-rate". I'm also using i18n for localization. The issue with both of these together is that when I'm on a page with the URL "en/my-url" and I click on the voting widget, I'm redirected to "de/user/login-to-rate" where "de" is my default language. Ideally the user should be going to "en/user/login-to-rate" i.e. user selected language should be respected.

Going into details, I find that the rate module calls `url()` using the following code:

```
print url('user/login-to-rate', array('query' => $query, 'absolute' => TRUE));

```

There is no language paramater that is passed, which means the default site language gets selected.

Am I missing something here in the configuration? Has anyone faced a similar problem and can help?

# Answer
> 3 votes
url() uses the current language by default, you only need to pass the language to it if you want another language, e.g. when sending mails to a user with a different language.

If you're on en/something and the global language is not en, then something else might be problem, for example incorrectly configured language recognication.

# Answer
> 1 votes
Try passing it the language object then. Without looking at the module, something like:

```
global $language;
print url('user/login-to-rate', array('query' => $query, 'absolute' => TRUE, 'language'=>$language));

```

If this works, make sure you submit it as a patch to the module.

---
Tags: uri, i18n-l10n
---


# Question
Title: Module to allow multiple paths for a single node?
Is there a module that would allow me to define multiple paths for a single node? (Not just one node; I need to do this for multiples.) For example, I need to be able to access http://www.example.com/node/153 via both http://www.example.com/tracks/big-picture and http://www.example.com/big-picture.

I need to be able to define at least one of the paths manually, i.e. not using a pattern.

# Answer
> 3 votes
You can already do this using core's Path module in Drupal 6. If memory serves, it should be in admin/build/path/add. Simply create two aliases that both point to node/153.

I should caution, however, that this may raise red flags with search engines. They typically frown on duplicate content, and your SERP rankings will likely suffer as a result.

---
Tags: 6, path-aliases, uri
---


# Question
Title: Missing filter and sort criteria from views
I'm following along a NodeOne video where it describes how to use the Views module. It looks like I'm missing a whole lot of filter criteria. Such as, all the "User:... " criteria, and the "Field:..." criteria is missing from the sort criteria menu.

This is a more or less fresh install of Drupal 7, and the only module I've installed is the views module, plus its dependencies.

How do I get those criteria to appear in the filter and sort menus?

# Answer
> 1 votes
I was running through that tutorial the other day too...

You need to add a relationship to the user (in the "Advanced" fieldset of your View), then the `User:` filters will appear.

I think the `Field:...` criteria are now called `Content:...`.

I got the tutorial content working fine in quite a short space of time and if memory serves these are the only things that were different from what was stated in the video. The video uses a beta/RC version of views whereas it's now in full release, so there will be a few differences.

---
Tags: 7, views
---


# Question
Title: User Relationships view showing the right number of users, but showing my profile link, not theirs
I'm not very good with Views and Panes, but I've *almost* completely managed to get what I want working.

I have User Relationships configured to have non-reciprocal relationships (so like Twitter, where "A follows B" does not necessarily imply that "B follows A"). I have a Pane that displays users followed by $current\_user and I have cloned it to a new Pane displaying users following $current\_user.

The Panel is almost working perfectly, with one exception — it is showing me the right number of profile links, but they're all links to $current\_user's profile with $current\_user's avatar, rather than links to $following\_users' profiles with their avatars.

I changed the Fields section in the Pane definition to point to the requestee User profile picture and the requestee UID, but this doesn't seem to have fixed it. It's not the database query coming out wrong, I'm just displaying the wrong values for each relationship in *this* Pane.

I'm sure this is really very obvious, I just can't spot the setting I need to change from requeste*e* to requeste*r* in the Views Pane interface.

Anyone able to point me to where I'm missing the obvious bit of configuration?

---

**Edit:** I've taken a screenshot of the configuration interface (linked, rather than embedded, as you'll want to look at it in a bigger scale than embedding allows). The Custom text in the Fields reads `<a href="/user/[uid]">[field_user_image]</a>`. In the Contextual filters, I've set the Requester user filter to Exclude. The Argument input reads as follows:

**Edit 2:** Looking in the Custom text (`<a href="/user/[uid]">[field_user_image]</a>`), I have Replacement patterns available:

* `[field_user_image]` == User: My profile picture
* `[uid]` == User: Uid
* `[nothing]` == Global: Custom text
* `%1` == User relationships: Requester user title
* `!1` == User relationships: Requester user input
* `%2` == User relationships: Requestee user title
* `!2` == User relationships: Requestee user input

But I can't work out how to make use of `%1` or `!1` in order to get the requeste*r*'s `[uid]` or `[field_user_image]`, rather than that of the currently-logged-in user.

# Answer
> 1 votes
Fixed it. I was using the requeste*e* fields when I should have been using the requeste*r* fields. What was:

>

Should have been:

>

Problem solved.

---
Tags: 7, views, users
---


title: Drupal 7: user is following view

text:
# Question
Title: Drupal 7: user is following view
I need to create a view of people a user is following. the default settings for user relationships only shows people following a user. i know i need to use views but i have no clue how to set it up. Any suggestions will be greatly appreciated.

# Answer
I've just had a problem that took me forever on a View to do with User Relationships, on question #25294.

The screenshot of the View I was debugging and the information I put in my question should hopefully give you everything you need.

(Bear in mind that my View was getting the people following $currentuser, whereas you want the people $currentuser is following, so you'll want to reverse all the instances of `requester` and `requestee`.)

I hope this helps!
> 2 votes

---
Tags: 7, views, users
---


title: Subscription and Node action

text:
# Question
Title: Subscription and Node action
I am using Drupal 7. And i am quite new.

I want to develop a system in website where an Event is declared by the Administrator. (Event is a custom event type - or i can use any existing one if needed). The event has a field (variable number of) subscribers to it.

If a user want to subscribe to event he/she can fill in a web form. Alternatively Subscription can be done by having a button (if such a thing is possible on node).

The problem is, usually such triggers help send an email post this. However, i want that once such an event happens, i want to modify the target node and append the current user\_reference in the list of subscribers in the node.

So basically, when a user subscribes the page, the system modifies the node to append the name of such a user in the subscriber's list.

Is such a thing possible? If so, how?

# Answer
> 1 votes
Short answers -

Drupal 6: Use Signup

Drupal 7: Use Entity Registrations

Both of these modules do pretty much exactly what you want on both counts.

---
Tags: webforms, notifications, rules
---


# Question
Title: Problem with loading translation of JS file via ajax
I've got an ajax call that loads some info and a js file with something like Drupal.t('CLOSE HISTORY')

That string, although properly loaded in the database, does not get translated when loaded through ajax.

Are there any issues translating js files that are loaded through ajax?

Any ideas are appreciated!

# Answer
> 1 votes
Answer was simple - the js translation file that drupal generates was "stuck". Seems to have been a browser caching issue.

---
Tags: ajax, javascript, i18n-l10n
---


# Question
Title: Can a form triggering an ajax call reload itself on drupal 7?
I'm trying to built a page to ask questions with a stream on top, so I need ajax to avoid the reload. It is actually simple. On top is a node with the stream and I add to blocks beneath.

1. A table with the questions, number of votes for the questions and an "add vote" button
2. A form to add a new node "question with 0 votes"

I have two problems.

A)When I click on the submit button of the 2. Block I add a question, I can update the table with the new question, but the add question form is not being emptied.

B)When I add a vote on the table (currently an ajax call from a checkbox) I get the database to have an increased counter and as far as I could check the callback delivers the new table, but the old one is never replaced. I thought it was the cache, but I even managed to avoid using the cached one, still no replacement. I get a few headers allready sent notices, but I don't understand why. I just want the form to be replaced by the new one.

(don't mind me getting a view instead of just a database result, it's just to built the table)

```
function questions_list_voting_form($form, &$form_state){
global $user;
$form['#prefix'] = '<div id="questions-list-table">';
$form['#suffix'] = '</div>';
$form['table'] = array(
        '#tree' => TRUE,
        '#theme' => 'table',
        '#header' => array(t("Title"),t("Votes"),t("Add vote")),
        );
    $view = views_get_view('questions_view');
}
$view->is_cacheable = FALSE;
$view->execute('block');
foreach ($view->result as $row){
    //['rows']['row-'.$row->nid]
    $question = array('#markup'=>$row->node_title);
    $vote = array('#markup'=>$row->field_data_field_votes_field_votes_value);
    $addvote = array(
    '#type'=>'checkbox',
        '#return_value' => 'add_vote'.$row->nid,
    '#ajax' => array(
      'callback' => 'ajax_addvote_callback',
      'wrapper' => 'question-list-table',
        'effect' => 'slide',
    ));
    $tab_arr = array(
            'question' => &$question,
            'vote' => &$vote,
            'addvote'.$row->nid => &$addvote
    );
    $tab_rows = array(
            array('data' => &$question),
            array('data' => &$vote),
            array('data' => &$addvote),
    );
            $form['table'][] = $tab_arr;
    $form['table']['#rows'][] = $tab_rows;
    $form['redirect'] = FALSE;
    $form['#rebuild'] =TRUE;
    unset($question);
    unset($vote);
    unset($addvote);
       }
     return $form;
}
function questions_list_voting_form_submitx($form, $form_state){
   if(substr($form_state['triggering_element']['#value'],0,8) == 'add_vote'){
    $tmp_node = node_load(substr($form_state['triggering_element']['#value'],8,2)); //question node
    $tmp_node->field_votes['und'][0]['value']++;
    node_save($tmp_node);
   }
}
function ajax_addvote_callback($form, &$form_state){
questions_list_voting_form_submitx($form, $form_state);
$form_state['no_redirect'] = TRUE; // avoid redirect?? maybe not working
$form_state['input'] = array('test'=>'etch'); //something to avoid cache
$form = drupal_build_form('questions_list_voting_form', $form_state);
$form_html = drupal_render($form);
return $form_html;
}

```

# Answer
Your form id is 'questions-list-table' but you have 'wrapper' =\> 'question-list-table' (letter s is missing). You might also want to be explicit with 'method' =\> 'replace' since the ajax is causing problems.

You should add a '#submit' =\> 'submit\_function' and modify your $form\_state in that function instead of trying to modify it in the ajax callback.

Why do you rebuild and render the form in your ajax callback? I think you just want to return the part of the form to replace - in this case, $form itself.
> 1 votes

# Answer
Have a look here Remove tabledrag statuses on Ajax submit and display status message after Ajax submit I had a similar issue

Also as Joe Beuckman said you have a typo on your #ajax\['wrapper'\] value.
> 0 votes

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


# Question
Title: Give a specific user role the ability to edit, delete users other specific role
I'm working in Drupal 7.

I want to give to a specific user role named "test role" the ability to edit, and delete users whose role is *students*.
Users with that role should not modify the admin account, and any other account with other roles.

# Answer
> 1 votes
Sounds like a combination of the following:

http://drupal.org/project/role\_delegation \- Adds a permission to assign roles per role http://drupal.org/project/administerusersbyrole \- Allows controlling, based on roles, which users can admin which other users.

---
Tags: 7, users
---


# Question
Title: How can I pull the latest published revision for a referenced node using the CCK node reference field?
Right now if I reference a node in another node via a CCK node reference field, if I change the referenced node, which creates a new revision of that node, it shows the edits on the page that's referencing that node even though I haven't published the latest revision.

I'm looking for a way to patch the node reference field or CCK to join on the node\_revision table so it will pull only the latest PUBLISHED version instead of the latest edit.

I have looked through both nodereference.module and content.module under CCK to try to find where the body is pulled in so I can edit the query. I can't find that query.

Any help is GREATLY appreciated.

# Answer
> 1 votes
Which module are you using to get forward-revisions? Revisioning?

This just seems like a bug in node reference field in that it makes the assumption that the latest revision is always published (which is true in core).

http://drupal.org/node/738116 has a patch which seems like it fixes node titles on auto-complete widgets and in the list of nodes. But it falls short of completely fixing the issue.

---
Tags: 6, entities, nodes
---


# Question
Title: User anonymity while using user_external_login_register()?
I am using D7 and implementing my own 3rd party authentication against campus LDAP by hook\_form\_alter()ing a user\_login\_form to my use own custom user\_login\_authenticate\_validate() which eventually calls user\_login\_external\_register(). As general examples see these blog posts for this technique:

blog entry 1

blog entry 2

But using this method, or even the D7 LDAP module; I see Drupal eventually calls user\_login\_external\_register() with $username and $password.

I dont want to store ANY $username or $password in Drupal as this is considered private student campus data. So, can anyone suggest a mechanism provide dummy user $username and $password for thousands of users logging in? What can I stuff into $username or $password to be able to know that if a student logs in 2 weeks from now they have the same Drupal account they used 2 weeks ago.

All I can think of is generating thousands of custom PHP uniqid()'s and provisioning 1 per each user just prior to calling user\_login\_external\_register() by stuffing faux $username and $profile into the $edit or $account before Drupal creates the account and after the authenication by the 3rd party.

Any feedback and thoughts appreciated.

# Answer
> 4 votes
Would it be sufficient to hash the username and/or password through something like sha1()?

You then wouldn't be storing campus data locally, as the hash is one way. You'd still be able to check against it later as Drupal would store the hashes.

---
Tags: 7, users
---


title: Flexible gallery solution for Drupal 7

text:
# Question
Title: Flexible gallery solution for Drupal 7
I'm trying to build a site which should have gallery functionality. I think we should be able to solve this with Drupal 7. So my question is: **is there any module/feature etc. (or any combination of modules), which can solve the following?**

* The site is on Drupal 7.
* **(A)** We will have a gallery manager role. Every user with that role should be able to *upload and manage his/her own galleries*. We will have at least 10 person with this role.
* **(B)** A gallery should be able to contain/display/manage ~100 pictures, so *batch uploading and editing (for captions, ordering, etc.)* is necessary.
* Support for usual Drupal goodies like *image styles, Views* etc.
* Support for a *clearbox-like display*, preferably integration with the Colorbox module.
* Support for *YouTube videos* in galleries would be nice, but not a must have.

I've already checked a lot of suggestions in the topic. Alternatives that probably won't work in my case *(please correct me if I'm wrong)*:

* A Drupal 7 version of Node Gallery would solve almost all of this, but it's not likely that we will see anything like that soon. **edit**: Node Gallery is now completely and totally unsupported, meaning that we won't see a D7 port ever.
* Media Gallery is a somewhat incomplete module - I've tried to build the functionality above with that, but I can't see any way to support point **(A)**, not to mention a big bunch of bugs that would make it impossible to use it on a production site. Also it's not maintained well.
* Field Slideshow is just a nice formatter, I don't think it's possible to use anything like that in my use case. As far as I can understand, a formatter-based solution won't scale well enough for **(B)**, not to mention the missing management functionality. Gallery formatter is the same from my point of view.

I would appreciate any suggestions on solving this. I'm not afraid of building something from scratch (whether it means playing around in Views, coding or both), but at least I would like to know where to start to achieve all of this.

# Answer
> 1 votes
In D7, I do galleries with the image field and the plup module. Nothing fancy, but at the same time, probably because it is nothing fancy, you automatically get support for colorbox, permissions (standard core or from contrib like Field permissions module), image styles, image captions (using the image caption module) and any other (image-)field related functionality.

So far it has fully satisfied my needs

---
Tags: 7, media
---


# Question
Title: Setting link target through views programatically
I have a text field that turns its value into a link, provided it's an absolute link. For some reason, setting the target to blank is not working. Am I doing something wrong? I set the target inside the array.

```
elseif (valid_url($row->{$view->field['field_myDoc_link_value']->field_alias}, TRUE)) {
  $fields['title']->content = l(
    $fields['title']->content,
    $row->{$view->field['field_myDoc_link_value']->field_alias},
    array('target'=>'_blank', 'html' => TRUE)
  );
}

```

Or would I set it somewhere else? Thanks!

# Answer
> 2 votes
Your problem is that you need to define the target under attributes, so

```
array('target'=>'_blank', 'html' => TRUE)

```

should instead be:

```
array('attributes' => array('target' => '_blank'), 'html' => TRUE)

```

---
Tags: navigation, views
---


# Question
Title: How to feature-ize multiple vocabularies applied to multiple content types?
Each of my content types is being exported into its own feature. I now need to export several vocabularies that are associated with the content.

Some of the vocabularies are applied to multiple content types. What is my best option for exporting those? Can I export a stand-alone feature that contains all the vocabularies that apply to multiple content types? Or should I associate them all with the most common content type? Or do I have to include each vocabulary in each feature individually?

# Answer
An important thing to keep in mind is that things start getting messy when multiple features try to export the same thing. For example, have multiple features that export the same Taxonomy vocabulary. When this happens, best case scenario is that you have to update all the features every time you make a change to the vocabulary. Worst case is, well, worse than that. I've heard some horror stories, but never tried it personally; I do my best to keep proper separation.

In your case, I suggest separating the content types and vocabularies into separate Features. For the vocabularies, you can either put them all in one feature or split them up into separate features, whichever you prefer. I tend to keep all the vocabularies in a single feature, which I think makes sense for your situation as well. For the content type Features, you can now list as a dependency the Features module defining the vocabulary used by that content type.
> 3 votes

---
Tags: 7, taxonomy-terms, features, importing-exporting
---


# Question
Title: Drupal Coding - Menus - hook_menu is not generating menus
While working on the layout of a new custom menu, I discovered that the hook\_menu process is not working on my D7.12 local site. As a test I enabled the Menu\_example module and found that it will not generate menu items in the navigation menu, although it did a week or two ago. So far I have reinstalled all Drupal 7.12 files and confirmed that the module file hook\_menus are being read (using dsm). I am at a loss as to what else can be preventing the menu links from being installed.

Does anyone have any similar experiences or suggestions on how to track this problem down to its source?

EDIT: This code does not add a menu item in an empty menu called "Stuff":

```
function material_menu_menu (){
  $items['stuff/existing'] = array(
    'title' => '020000 Existing',
    'page callback' => 'material_view' ,
    'page arguments' => array ('sum' , '020000 '),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'Stuff',
    'access callback' => TRUE,
    'weight' => '2 ');
  return $items;
}

```

# Answer
> 2 votes
The place to start debugging is in `_menu_navigation_links_rebuild()` which builds up the menu links...it gets passed the menu router items built up from `menu_router_build()` (which is where hook\_menu() is called from). A bit of temporary debug code in that first function would be the best way to go I think.

To address your other question, I've just added a menu item to a module in exactly the way you've done and it's come up in the UI as expected. It sounds like you have something pretty unusual happening with your menus!

---
Tags: routes, hooks
---


# Question
Title: Webform css stylesheet overriding my css file
I am using drupal 6.25 with webforms 6.17 and conditional stylesheets 6.12 and am noticing that the webform style.css file is overriding my IE7style.css file even though the IE7style.css file appears after the webform stylesheet when I view the source in IE7.

It makes no difference if I have css caching turned on or off - the result is the same.

Here is the relevant line in IE7style.css

```
.webform-container-inline .form-item {
    display: block;
}

```

Here is the line in webform's sytel.css it should be overriding

```
.webform-container-inline DIV.form-item {
    display: block;
 }

```

How is this possible and more importantly how do I fix it???

# Answer
The 'div' in the webform's CSS makes it more specific than your CSS in IE7styles.css, thus overriding your styles. You should copy the CSS selector from the webform module's CSS **exactly** if you want to override it with a style in a file later in the cascade.

Here is a good article on general traits of CSS specificity and inheritance.
> 1 votes

---
Tags: theming
---


# Question
Title: How to get all linked nodes from all terms in a vocabulary
I have a content type "News entry", which has a term reference "News category", which is of course a taxonomy vocabulary.

I’m not sure if I get this whole taxonomy thing right, but I’m able to render and theme each category correctly (/news/category-a).

Now I want to theme the overview or home page, which displays all news entries of all categories. Easiest way for me would be selecting the right rows out of the database, but I reckon that’s not very much the Drupal way.

So I figured out how to get all terms of a vocabulary. In the preprocessing function theme\_preprocess\_node\_news\_overview() I tried taxonomy\_get\_tree(). Now I've got an object for each term with the following contents:

https://i.stack.imgur.com/cbT8c.png (can’t post images yet)

The news entries are preprocessed in theme\_preprocess\_node\_news\_post(), It’d be great if this function could be reused for the news overview.

And now I’m stuck. How do I get Drupal to behave like it’s displaying a category/tax. term, but instead of the nodes of one term get (and display) the nodes of all terms?

# Answer
As "all linked nodes from all terms" are in my case the same as "all nodes of a content type", I solved my problem this way:

```
<?php
function themename_preprocess_node_news_overview(&$vars) {
  $results = db_query("SELECT nid, type FROM {node} WHERE type = 'news_post';");
  $tmp = array();
  foreach ($results as $result) {
    $tmp[] = $result->nid;
  }
  $vars['content'] = node_view_multiple(node_load_multiple($tmp), 'teaser');
}
?>

```
> 0 votes

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


# Question
Title: Add a Button within the content type overlay window for the url link
There is any way to add a button into the content type for example Article as show in the below figure

there is any module for adding the button within the content type in drupal 7.

# Answer
The page in your screen shot is a 'node add' page for a particular content type in your drupal site. Therefore the best way to add more elements there is to utilize hook\_form\_alter()

```
<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mynodetype_node_form') {
    dsm($form); // This function is available via Devel module. Here, it shows you the contents of $form in a structured manner, so that you know where to make the change to add a button.
    // Add code here to add button in the form etc.
  }
}
?>

```

The above code snippet assumes your module name is `custom` and your content type name is `mynodetype`

To understand what code you need to write to add new form element (in your case a button), refer drupal form api - http://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7
> 1 votes

---
Tags: 7, nodes
---


title: Project Pages of Drupal

text:
# Question
Title: Project Pages of Drupal
I have seen project pages in drupal under http://drupal.org/project/xyz. I don't know how that works really.

Is this a specific 'Content Type' it is, but each node (aka project) has extremely consistent layout where as the whole thing look more like an basic article or a book page. Also, the elements within also has sections and further content; so it doesn't look like a pure single node. Or is this a different entity using a module like Project? But it is not available for D7.

Specifically, I want something exactly like this, but i don't quite know how to make specialized and consistent.

# Answer
> 7 votes
Drupal.org is using the Project module.

What you see as project page is a normal node to which the Project module adds extra fields. Keep in mind that the project page is also showing blocks shown just for those pages, and which are not part of the project page output.
The Project module automatically creates a path alias for every project node. That is the reason you see http://drupal.org/project/views, instead of http://drupal.org/node/38878; if you try the last link you will see you are accessing the Views project page.

The fact the project page is just a content type is proved from the fact project is shown in http://drupal.org/node/add, which lists the possible content types for which a user can create a node.

What you see in that page depends from the permissions you have on Drupal.org; as site maintainer, I see listed some content types a normal user doesn't see, such as the Story content type.

As alternatives to using the Project module there is the Storm module, which is more complex, in some way, and lack integration with CVS, or Git repositories (as far as I can see).

> Storm is a structured system for project management, including:
>
> * Organizations, Teams, People,
> * Projects, Tasks, Tickets, Timetrackings,
> * Notes, Invoices, and Expenses.
>
> Each part provides permissions to control the sharing of data with other Drupal users, and based on assignment of projects/tasks/tickets to particular users or teams.

The difference is that the Project module has been thought to be used on Drupal.org, even if it can be used on other sites, and the main features are the ones required from Drupal.org.

The Support Ticketing System module implements a ticketing system, and a help desk.

> The support module provides a basic ticketing system and helpdesk that is native to Drupal, offering complete email integration.
>
> The Support module offers the following features:
>
> * Ticketing activity is illustrated with colorful charts (depends on the Chart API module). -Tickets can be assigned to users (and users can view all tickets assigned to them).
> * Tickets support states (new, active, pending, closed, etc) and priorities (low, normal, high, critical, etc).
> * Configurable email notifications for new and updated tickets.
> * Email integration allows tickets to be created and updated via email, with support for attachments. New users can be automatically created. Ticket properties can be updated via email (using included support\_mailcmd module).
> * Highly configurable client and user ticket overviews, highlighting tickets that haven't been updated for a long time.
> * Fully integrated with Drupal's search functionality, users can only search for tickets they have access to.
> * Supports an unlimited number of clients, each with their own configuration and access permissions.
> * Tickets are nodes, ticket updates are comments.

---
Tags: nodes
---


title: Create a renderable array for checkbox

text:
# Question
Title: Create a renderable array for checkbox
I want to inject a checkbox within a preprocess function and I think it should be a renderable array.

What is the structure of a renderable array for a checkbox?

Update:

I use profile2 module and have created profile checkbox fields. While viewing profile currently the field are show as just text. I want to show it as disabled checkbox with state. So it is not within a form.

# Answer
Assuming that your render array is part of a form (outside of which a checkbox doesn't make a whole lot of sense), you would do it like this:

```
$form['checkbox'] = array(
  '#type' => 'checkbox',
  '#title' => 'Title',
  '#default_value' => 1, // Checked by default
);

```

Have a look at the checkbox type documentation for all of the available properties.

**EDIT**

Just to add that `render($form['checkbox']);` also works perfectly outside of the form context using the above code; the correct checkbox element is rendered, but without the "name" and "id" attributes.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to update the current page to show new content?
I am currently displaying a list of MySQL database table names, such as table1, table2, table3.

Each table name will be a link; if users click on it, it will display them the data contained in that table.

One way I know I can do this is to create a Drupal page that contains the content of "table1", so that when a user clicks on "table1", they are taken to this page and can see the data of "table1".

However, this soon becomes un-manageable if I have a large databases with many tables.

I'm not quite sure if Drupal can work in this way, but I would like it so that when a user clicks on a table link (either table1 or table2 and so on), the current or a generic page will then be updated with the content of the table chosen and be updated with its content.

# Answer
I am not sure what functionality you are trying to build and if adding PHP code inside a Drupal node is the right way to do it. But assuming that is what you would like to do, here are the steps to achieve what you want:

1. Create a Drupal node (say the nid of it is NID) and add the following PHP code inside it

```
$table_name = arg(2); // This grabs the 3rd argument of the page menu path (note: the 1st argument is indexed 0)
print $table_name; // Replace this with PHP code to fetch and print data in the table represented by $table_name

```
2. When you are making table1, table2 etc links make sure the URL that they point to is `node/NID/<table_name>` where `<table_name>` is table1, table2 respectively.
> 1 votes

# Answer
If you have a dynamic list of tables/columns, then you can build this using PHP, you just need a dynamic menu entry that accepts the table name as an argument and then you can re-act to that in PHP. There are many books and online documentation available about how to create modules, try here for example: http://drupal.org/node/361112

If you have a fixed list of tables, you could build this using Views. If these are custom tables, you first will integrate them with Views, however.
> 0 votes

---
Tags: navigation
---


# Question
Title: Discount based on a field in product display node in Drupal Commerce?
I want to create a pricing rule based on discount entered in a field in the product display node? Is it possible? I have been trying to do it but i can't see the discount field in the dataselector. I tried entity has field but there only line-item entity appears and no node entity?

# Answer
> 5 votes
You can do this, I have done so myself. It's been a lot easier to do this than when I needed to do this.

The thing is that in rules, in order to get the fields of an entity, to use it in Rules, you need to either add a condition that the field exists or add a condition that the entity is of type X.

I've attached the base setup that does this for the commerce kickstart install profile. You might be using a different product type, but it should be easy to change.

```
{ "rules_example_discount" : {
    "LABEL" : "Example discount",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_product_reference" ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:type" ],
          "value" : "product"
        }
      }
    ],
    "DO" : []
  }
}

```

Update:

Since you are saving the discount on the product display, you are making it more difficult for you. What you need to do, is from the line\_item/product context to be able to figure out which product display the product comes from. The easiest way to do that would be to add a node reference field on the line item and then populate that with the product display node when adding the product to the cart. This should be doable with a custom submit handler added to the add to cart form with `hook_form_alter`. Then you need to tweak the rule accordingly and use the field from the node referenced on the line item instead of the product reference on the line item.

# Answer
> 4 votes
As I said on IRC, a line item doesn't store the id of the product display in a way that Rules can understand. This is because product displays are not required for Commerce to work.

However, line items have a "commerce\_display\_path" field that stores the url from which the product was added, so in your case it would probably look like "node/1", or whatever the node id is.

What you need to do is: Write a custom Rules action that takes the line item, initializes the wrapper, gets the value of commerce\_display\_path, explodes the string, takes the nid, loads the node, returns it.

Example code:
$line\_item\_wrapper = entity\_metadata\_wrapper('commerce\_line\_item', $commerce\_line\_item);
$url = $line\_item\_wrapper-\>commerce\_display\_path-\>value();
$url\_parts = explode('/', $url);
$nid = $url\_parts\[1\];
return array('node\_fetched' =\> $node);

Place this in a custom rules action, and you're good to go.

You can then use your action in a component to get the product display whose fields you can then access.

---
Tags: commerce
---


title: Add View To page.tpl

text:
# Question
Title: Add View To page.tpl
I hope that you could help me out with this. After much time ive finally managed to work out how to takeover the space that my breadcrumb was taking up. With this bit of space i thought about adding a banner in there or a welcome message. I dont want my site to look 'tatty' so the banner idea was soon forgotten. A welcome message would be nice but it will be going through all my site and im sure that folks will get a bit sick of it.

I was hoping to add a View of random quotes in there. You can see the 'spot' i mean on my frontpage here- http://onlinebanter.com/

As i type this though i'm a wondering if i could make that spot a block region? Then i could have a welcome message on the frontpage and then use it as a region to add helpfull advice for differant sections of my site. also i could add a random quote view for within nodes etc.

Could anyone offer me advice on either adding a view to a page.tpl or creating a block region in the wee spot ive found?

All help appreciated.

thanks

# Answer
You can open your theme's .info file and add `regions[my_region] = My region`. Now open your page.tpl.php and do `print $my_region` (the name of the variable corresponds to the `regions` array index - see the first sentence) where the region should be rendered. After this make sure to clear your Drupal's cache so that it picks up the new region and the modified page.tpl.php.

Views can generate block displays. After you created the block display, you can use the Drupal's default blocks interface to put the Views block into the region you created, or better yet use a module like: Context which gives you more control over when to show which blocks in what region and when not to...
> 1 votes

# Answer
If you go for the view block directly in the template, you can use views\_embed\_view('yourview', 'yourblockdisplay') in your block's block--id-of-block.tpl.php (name depends on your drupal version).

If you want to create a region (which is probably overkill here), you have to add it to your theme.info in this form `regions[quotes_region] = Region name` and add the relevant variable in yourtheme\_preprocess\_block, then add the block to the region.
> -1 votes

---
Tags: views, theming
---


# Question
Title: Return inserted serial from drupal_write_record
I have a module which creates records in the db via drupal\_write\_record and this works perfectly. However I need to get the automatically assigned serial number for each record which is written into a variable.

Does anyone know how I can achieve this and get the index #?

I need the index variable to use in another table to create the reference...

Edit: Clives answer worked as below:

```
// Create object
$call = new stdClass;
$call->uid = $user->uid;
$call->call_type = $call_type;
$call->cli = $cli;
$call->start_nid = NULL;
$call->timestamp = $timestamp;

// Insert call row in db
drupal_write_record($table,$call);

// Test correct index
drupal_set_message($call->call_id);

```

# Answer
`drupal_write_record()` populates the serial field of an object you pass to it automatically. So assuming you have a serial field in your table called `id`, if you run code like the following:

```
$record = new stdClass;
$record->title = 'Title';
$record->some_other_field = 'Something';

drupal_write_record('table_name', $record);

```

the `$record` object will be auto-populated with a member representing the serial column when the function returns. In this example you can access it with `$record->id`.
> 5 votes

# Answer
Think I found the solution:

```
$last_id = db_last_insert_id($table, $field);

```

Edit: As per Clive's comments his solution above is most effective.
> 0 votes

---
Tags: 6, database
---


# Question
Title: Add a CONCAT field to hook_views_data in Drupal 6
I'm working with getting a GROUP\_CONCAT field into views for my module and I've been using this answer as a guide: https://drupal.stackexchange.com/a/12364/2735.

I'm almost there, having successfully added the groupby to a new field in \_view\_query\_alter. The problem I'm having is getting that field out into views, so that it's an option in the "Fields" area of the views UI. In the SQL, according to Views, I've correctly got the GROUP BY and the GROUP\_CONCAT, where the concat in the SELECT looks something like:

```
GROUP_CONCAT(month_id) AS months

```

However, when I try to get 'months' back out in \_views\_data, it either (a) adds the table name to 'months' as in:

```
SELECT mytable.field1,
mytable.months ...

```

or (b) does not recognize the field at all in the Views UI.

In \_views\_data, I try defining the field with:

```
$data['mytable']['months']

```

which produces (a), and with:

```
$data['']['months']

```

which produces (b). I know I'm missing something small here. Can anyone tell me what it is?

----UPDATED to show the code I have so far, added to my .module file -----

```
/*
----the table that my module uses: ----
CREATE TABLE IF NOT EXISTS `drupal_seasonality_chart` (
  `food_id` int(11) NOT NULL,
  `month_id` int(4) NOT NULL,
  `is_partial` tinyint(4) NOT NULL,
  `veg_or_fruit` text NOT NULL,
  PRIMARY KEY (`food_id`,`month_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--------
notes:
 - food_id relates to a term_id
 - each food_id can have many month_ids

*/

//this function is adapted from: http://drupalcontrib.org/api/drupal/contributions!views!docs!docs.php/function/hook_views_data/6
function seasonality_chart_views_data() {

    //group
    $data['seasonality_chart']['table']['group'] = t('Seasonality');

//base table
    $data['seasonality_chart']['table']['base'] = array(
    'field' => 'food_id',
    'title' => t('Seasonality table'),
    'help' => t("Seasonality content related to food tags."),
    'weight' => -10,
    );

    //join. The food_id in the module table relates to a term id (tid) in term_data
    $data['seasonality_chart']['table']['join'] = array(
         'term_data' => array(
         'left_table' => 'term_data',
         'left_field' => 'tid',
         'field' => 'food_id',
         ),
       );

    // Food ID field.
      $data['seasonality_chart']['food_id'] = array(
        'title' => t('Food id'),
        'help' => t('References a food tag'),
        'relationship' => array(
         'base' => 'term',
         'field' => 'tid',
         'handler' => 'views_handler_relationship',
         'label' => t('Example term'),
    ),
  );

  // Month ID field.
  $data['seasonality_chart']['month_id'] = array(
             'title' => t('Month id field'),
            'help' => t('Month number'),
        'field' => array(
          'handler' => 'views_handler_field_numeric',

          'click sortable' => TRUE,
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_numeric',
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
  );
    //---the concat field ---> here's where the trouble is <------
    // using $data['seasonality_chart']['months'] creates a non-existent field called seasonality_chart.months
    $data['']['months'] = array( //using no table does not return the field at all
    'title' => t('Months field'),
        'help' => t('Month number list'),
    'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => TRUE,
    ),
    );

  return $data;
}

//this function comes from here: https://drupal.stackexchange.com/questions/12359/add-a-group-by-in-views/12364#12364
function seasonality_chart_views_query_alter(&$view, &$query) {
  $query->add_groupby('tid');

  // hack to make the query constructor just ignore these fields (not adding them to the GROUP BY clause. It's needed to let it continue without problems
  $query->fields['seasonality_chart_month_id']['aggregate'] = TRUE;
  $query->fields['term_data_name']['aggregate'] = TRUE;
    $query->fields['term_data_vid']['aggregate'] = TRUE;
    $query->fields['months']['aggregate'] = TRUE;

    // ... do I need add_field() here instead? in addition?
    //$query->add_field('','GROUP_CONCAT(month_id) AS months');

  // Configure the fields that perform the aggregation (SUM, AVG, etc)
  $query->fields['months']['table'] = '';
  $query->fields['months']['field'] = "GROUP_CONCAT(month_id)";
  $query->fields['months']['alias'] = 'months';

}

```

# Answer
You have to implement a handler class for the field (most conveniently derived from views\_field\_handler). You also have to make the field handler known to Views; see the source code of hook\_views\_data() for an example.

Add the GROUP\_CONCAT and GROUP BY clauses to the query in the field handler's query() method.

A tutorial style explanation of how to implement hook\_views\_data() and what other aspects you need to consider (like implementing hook\_views\_handlers()) is included in the views module, but you need the Advanced help module to have convenient access to it.
> 2 votes

---
Tags: views
---


# Question
Title: User relationships. Override mysite.com/relationships page with views
Is there any chance to override mysite.com/relationships page with views? I guess the answer would be yes. But how? Can somebody explain to me in details. :)

P.S. I've tried to create my own page view, with path /relationships, but there's so much settings... messed up me :(

# Answer
I'm not sure if it's the best solution or the best practice. There is a low overhead, small module called Empty Page that strips the content from a page. Use that and then put blocks in regions. It's great for creating elaborate front pages too.
> 1 votes

# Answer
Yes, it's definitely possible (though somewhat fiddly) and we've done so on our site. I probably don't know Drupal well enough to pre-empt any howto questions, but I had a question about it (now resolved) that I posted a screenshot of the View configuration to, so you might find those helpful.

If you have any specific questions on our implementation, drop them in the comments and I'll update this answer with more detail.

I should disclaim that our site uses UR in a Twitter paradigm, so relationships are unidirectional but may be reciprocated: Alice can follow Bob but that neither implies that Bob follows Alice nor prevents Bob from doing so.
> 0 votes

---
Tags: views, users
---


# Question
Title: Drupal 7 field widget - allowed values list
I need to have a select widget but with custom allowed values per user. Since in D7 I cannot use php code, I was wondering if there is some kind of hook I could use to achieve that functionality.

Thanks

# Answer
> 1 votes
This would be hook\_field\_widget\_form(&$form, &$form\_state, $field, $instance, $langcode, $items, $delta = 0).

The example code for the hook, reported in the documentation is the following one.

```
function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return $element;
}

```

---
Tags: 7, entities
---


# Question
Title: Update a field based on value of another field in node edit form
In the node add/edit form, I have a node reference field. When users select a node, I want to update another field with value of a field of selected node.

What's the best and easiest way to do this?

I want to load the value in the edit form, using AJAX or AHAH, so that the users can see it, and edit if necessary, not just updating the field after form is created.

# Answer
Drupal 7:

Create a custom module. This module should implement `hook_node_insert` and `hook_node_update`. Both functions will have almost identical code, and it should go something like this:

```
/**
 * Implements hook_node_insert()
 */
function mymodule_node_insert($node) {
  if ($node->type == 'my_node_type') {
    // Set the $value variable with value you wish
    // to insert to the referenced node.
    $field = field_get_items('node', $node, 'field_whatever_it_is');
    $value = $field[0]['value'];

    // Grab the referenced node's nid.
    $field = field_get_items('node', $node, 'field_nodereference_field_name');
    $ref_nid = $field[0]['value'];

    // Load the referenced node into a variable. Avoid cached nodes.
    $ref_node = node_load($ref_nid, NULL, FALSE);

    // Update the referenced node with $value
    $ref_node->field_to_update[0]['value'] = $value;

    // Save the referenced node
    node_save($ref_node);
  }
}

```

If you just want to update the referenced node's node reference field with the current node's nid then you can also just use a module called Corresponding Node References
> 1 votes

# Answer
I think the Rules module can help you.

> The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

There is a good screencast about how to have nodes being updated in sync with the parent nodes they belong to.

Sync article promotions with articles
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: How do I build a relation of users having a specific role, automatically?
I have installed the Relation module. I need that users with the "test" role are related with all users having the "student" role, automatically.

How can I build this relation?

# Answer
> 2 votes
With the Rules module, you could take action on a "user created with role student" event.

---
Tags: entities
---


# Question
Title: AJAX callback inserts empty div with large amounts of data - Whats happening?
Drupal 7 - Created a module that lists out a bunch of tabular data from an external oracle database. The list has a number of select boxes to narrow down criteria. After setting up the menu file I have the following callbacks:

```
function listAll($form,&$form_state) {
    //Page callback for drupal_get_form

    $form['semesterSelect'] = array(
        '#type' => 'select',
        '#title' => 'Semester',
        '#options' => array('Fall','Winter','Spring','Summer'),
        '#default_value' => 'Fall',
        '#ajax' => array(
            'callback' => 'callbackSemesterSelect',
            'wrapper' => 'courseListDiv',
        ),
    );

    $form['courseList'] = array(
        '#type' => 'markup',
        '#prefix' => '<div id="courseListDiv">',
        '#suffix' => '</div>',
    );

    if (!empty($form_state['values']['semesterSelect'])) {
        $form['courseList']['#markup'] = getCourseTable();
    } else {
        $form['courseList']['#markup'] = 'Select a semester';
    }

    return $form;
}

function callbackSemesterSelect($form, $form_state) {
    return $form['courseList'];
}

function getCourseTable() {

/***
* This function uses ob_start() and ob_get_clean() to return an HTML formatted table
*/

}

```

What I have noticed is that if my table goes over 30 or so rows the output ends up being an empty div where courseListDiv was previously. When its under 30 rows it displays the courseList element with prefix/suffix as expected. Is the output buffering causing this? is there a limit on ajax data or something in drupal that might be causing this?

# Answer
> 0 votes
Turns out there was some UTF8 encoding in a field that was causing the output to not be rendered. Appears to be something in the output buffering that caused this and not drupal. Adding a utf8\_decode when the fields print has resolved the issue.

---
Tags: 7, ajax
---


# Question
Title: Is it possible to remove the contextual link for deleting a node?
In Drupal 7, can I somehow remove the "delete"-link from the contextual menu?

Some users don't realize that this actually deletes the node. They think it only removes it from the current page but still exists in the database.

# Answer
You can implement hook\_menu\_contextual\_links\_alter() to remove the "delete" link from the contextual links.

```
function YOURMODULE_menu_contextual_links_alter(&$links, $router_item, $root_path){
  unset($links['node-delete']);
}

```

However, if your users are irresponsible enough to believe that "deleting" a node does not actually delete it, you may be better off simply removing those users' permissions to delete nodes at all.
> 3 votes

# Answer
After looking into Custom Contextual Links module, I found a way to do this.

```
function MYMODULE_contextual_links_view_alter(&$element, $items) {
    // Check if we have a node link to process
    if (isset($element['#element']['#node']->nid)) {
        unset($element['#links']['node-delete']);
    }
}

```
> 2 votes

---
Tags: 7
---


title: A car dealer website with Drupal

text:
# Question
Title: A car dealer website with Drupal
Soon I will be starting to develop a car dealer website using Drupal. I want users to be able to select make, modal and other stuffs. The main thing is the search; I will be using the Views module, with exposed filters, and taxonomy terms.

Is there any module which can do this?

# Answer
> 2 votes
There is no specific module to do this but using as you mentioned Views, views exposed filters and taxonomy will give you what you want.

---
Tags: search
---


# Question
Title: How to import external database table into Drupal database table?
I imported an external database into my local Drupal database. The database table I am particularly interested in is the default "users" table in Drupal and the imported "USER" table from the imported database (My current Drupal database has both "users" and "USER" tables).

The external "USER" table contains columns that are not contained in my current Drupal "users" table.

I would like to perform either one of the following:

1. Merge the "users" and the "USER" table, so that all the rows from the "USER" table is now contained in the "users" table.
2. Allow Drupal to obtain login information from the externally imported "USER" table. By this, I mean if there is a user called "ABC" in the "USER" table, then Drupal should allow user ABC to log into the website.

Any help is appreciated. Thank you.

EDIT:

I have tried using the migrate module, but nothing shows up nor do any options show up for me to migrate my data. I have found a little tutorial that teaches how to import external data using drush and migrate - http://www.gizra.com/content/data-migration-part-1. Is this the correct way to use Migrate?

# Answer
You have at least 2 choices, none of which is easy in my opinion.

1. Import the non-drupal-users into drupal using a tool such as Migrate to actually map the new fields into drupal fields, you can use hook\_schema\_alter() and hook\_entity\_propery\_info\_alter() to tell Drupal about these new fields that Migrate is moving over.
2. If you dont merge these tables permenantly into 1 drupal "users" table you're kinda making more trouble for yourself. You could implement your own authentication method to do an SQL query against your (non-drupal) Users table and if the visitor is found there create a new Drupal user account for them. To do so you'd basically create your own login logic as loosely described here for an external source, Blog Tutorial
> 2 votes

---
Tags: users, importing-exporting, database
---


title: How to make in CCK a field like a grid

text:
# Question
Title: How to make in CCK a field like a grid
In my site I want user to add a new album of images he have to add 1. title
2. description
3. sub form that contain Image and title and set to default (radio button) and he can add more than one sub form

and only one image will be the default site that will appear in home page (Selected from radio button)

How can I make things like that

# Answer
Presuming CCK=\>Drupal 6, and without writing a custom module or custom compound CCK type, you could do something like this:

1. Create a cck content type, let's call it album\_image, and in it have the following fields:

a. Image field b. text field for title c. text area for description
2. Allow your users to create/edit these content types and fields via permissions
3. Create a view that returns all album\_images created by the logged in user
4. Add a node reference field to the user's profile (The Content Profile module is an easy way to do this) and restrict it to one result, and call it for discussion here default\_image.
5. Within CCK screens for the field above, use the view you created above to populate the "returned values" for the node reference instead of just selecting a content type.
6. Now, when your user edits his or her profile, they can select one album\_image as the one they want displayed.

Now within your user profiles you have a field called field\_default\_image that contains the nid of the album\_image your user wants to have displayed on his or her profile, so you can then load that up to get the image and use that wherever you need, eg, within whatever preprocess functions you use within your theme to paint the profile.
> 1 votes

---
Tags: entities
---


# Question
Title: How to copy field value into another field by its node ID?
I have a document that goes through 3 phases. Each phase is its own content type because each phase brings in new questions and structure built upon the previous phase.

I want the below to happen when a user is adding new content for phase 2 & 3:

1. User is asked for node ID of previous document in phase 1
2. Field values from that previous node is retrieved and imported automatically into the new content's fields.

Are there any existing modules that can do this? Maybe the Rules module?

# Answer
I could not find a solution to my problem, but I found a workaround. Instead of 3 phases with each their own content types, I instead was able to make one content type and use the vertical tabs to create 3 "sections". It is not ideal but it should work. I would still like to know if what I am asking is possible.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: Mod Rewrite for Subdomain to point to TLD
Is it possible to create a Mod Rewrite rule to point a subdomain to a TLD? Example; cars.test.com -\> Mycarsite.com

Am using the shared cookie, tables (for the users), and Domain access in D7. Now all I need to do is craft a rewrite rule that can point all the requests going to subdomain.tld.com to goto mytld.com.

CLARIFICATION/EDIT: This is specifically a drupal question. I shared the users with test.com & cars.test.com so that I can do a single sign on. So I did the typical adjustments to settings.php and crafted the single db with prefixes per site. The only "out of the box solution" that works with D7 for an SSO solution is sharing the DB and and sharing cookies. I got that part working. Now this is the part that am experimenting with but am not sure its possible. I want all requests that goto cars.test.com appear as if they are coming from mytld.com. I already have mytld.com parked on the host. But when I goto cars.test.com using the mod rerewrite rules from @acouch below, it redirects me test.com. Is this possible?

# Answer
This should work:

```
RewriteCond %{HTTP_HOST} ^subdomain\.tld.com [NC]
RewriteRule ^(.*)$ http://mytld.com/$1 [L,R=301]

```
> 0 votes

---
Tags: redirection
---


# Question
Title: How do you handle static HTML forms saved in a "Basic Page" in Drupal 7?
I am a Drupal newbie and have been asked to help with some issues on a Drupal implementation. I have been asked to handle HTML forms that have already been designed and saved in "Basic Page" as either "full html" or php.

I have googled but could not find an references to such form handling. Almost every piece of code I have seen generates forms using Drupal Form API. There is enough documentation to work with forms generated using the Form API.

I would like to know if there is a way to handle these static(ally generated) forms and if so how.

# Answer
I think the reason you can't find any documentation is because doing this sort of thing is very much discouraged in Drupal.

Drupal's form API exists for a good reason:

* It allows theme/module developers to build up a form very easily
* It provides a unified approach for themes and modules to add elements/validation/logic to any form that exists in the system. A good example of this in action is the Captcha module, which has the capacity to hook into any form in the system and add CAPTCHA protection.
* It provides automatic protection against Cross Site Request Forgeries (CSRF).

If you're not up for coding your forms you should instead check out the Webform module which has an easy to use UI allowing you to build up nodes with forms on them, and it has very powerful administration features.

If you really want to do it without using the Form API or Webform modules, though, you could probably try something like this in a custom module:

```
function MYMODULE_init() {
  if (isset($_POST['my_post_var'])) {
    // Do something with the $_POST data
  }
}

```

Be warned that your forms will not be protected from CSRF, nor will they have the ability to be changed by other parts of the system. It's also just not the 'Drupal' way to do things :)
> 1 votes

# Answer
To be honest, you best bet is to recreate the forms using the Webforms module. Unlike FAPI, you get a nice UI for making them, and several options for handling the form data once received.

Otherwise, you have to make some hook\_menu entries to handle the POST, and more code to handle the actual data.
> 0 votes

---
Tags: forms
---


# Question
Title: How to alter the result of my view using filters?
I have a view with 2 exposed filter.. I only want to change the result of my view when filters are used, ie if they have any value and press the button to run the filters.

I try to used the hook\_views\_pre\_render, but doesn't work...

```
function node_db_views_pre_render(&$view) {
   if($view->name=="demo" && $view->current_display == 'page_1' &&  $view->exposed_input['date_filter'] != NULL) {
       $get_date = $view->exposed_input['date_filter'];
       $min = $get_date['min']['value'];
       $max = $get_date['max']['value'];

         $query_power = "SELECT h.id, h.name, count(c.room_id) as busy
                         FROM table_1 c JOIN table_2 h ON c.id = h.id
                         WHERE '%s' < c.in_date OR '%s' > c.in_date
                         AND '%s' < c.out_date OR '%s' > c.out_date";

         $result = db_query($query_power, $min, $min, $max, $max);

       $items = get_rows($result); // this is a function gets the data from the sentence and makes a array.

       $view->result = $items;
   }
}

```

Exist other hook that can help me?..Thanks :D

# Answer
> 1 votes
you should use hook\_views\_query\_alter, because hook\_views\_pre\_render is called after the query is done, so you cannot influence your database request anymore.

The views documentation has been added to the Drupal api docs recently, so for more info look at: http://api.drupal.org/api/views/docs%21views.api.php/group/views\_hooks/7

or

http://views.doc.logrus.com/

---
Tags: views, forms
---


# Question
Title: How do I structure a simple Drupal 7 site/theme?
I'm coming from WordPress CMS and right now (to be honest) I'm a bit overwhelmed by the (seemingly) complex Drupal theming/content management system.

I have a website with the following pages (I've simplified it a bit but that shouldn't be a problem):

* Home (contains 3 containers with text/lists that should be editable through the CMS)
* About (editable text)
* Jobs (lists all available job offers, also editable)

I want to start my theme from scratch. I have my html.tpl.php where I have title and meta stuff; then I have the page.tpl.php with my layout. That layout is the same for every one of my pages; the only thing that changes is the content inside my content-div.

How and where do I code the structure for my "Home" page? Is every editable text container a region to which I assign a block I created? Is my "Home" page basically a node whose code should be in a extra node--\[home\].tpl.php file?

I googled a lot, but I couldn't find good instructions on starting a theme from scratch. All the tutorials I found only changed some basic things in a theme or did sub-theming but there was nothing that could show me how to structure my site.

Maybe someone can help me or point me to a good tutorial; coming from a WordPress background i'm very confused right now.

# Answer
> 5 votes
It sounds like most of the things that you need to do (i.e. creating and placing content on the site) are not related to a theme, but rather related to site building. Folks coming over from Wordpress are usually confused by the split between theming and site building in Drupal, it's very different from Wordpress.

I would strongly recommend reading Drupal's Site Structure Guide. Your homepage and "about" page will most likely be a combination of node content and blocks, while your "jobs" page will involve creating a custom content type and a Views page listing the nodes of that content type.

The majority of your work to set up the content of the site and it's output can happen before you even begin theming. Theming is usually a later step in site building and should be considered a very superficial aspect of building the site. There are few situations where you would need custom templates for each page or node type, most of the arrangement of content and even layout can be handled via the Drupal UI.

Once you complete the site build in Drupal and move on to theming, the Drupal Theming Guide will be your starting resource for learning how the Drupal theme layer works.

# Answer
> 2 votes
I would strongly recommend not starting from scratch, especially if you haven't used Drupal before. Instead look for a starter theme that suites your needs and go from there. At the very least grab a starter theme and use that as a guideline for how to start your own.

Zen is one of the most popular and is extensively documented (maybe a little too much), some other ones such as Basic or Clean are a little more sparse and might suit your needs better.

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