# Question
Title: add #ajax property to email field in node add form usion hook_form_alter
I've tried to add the property "#ajax" to email field but It dosen't work, I've tried all this :

```
$form["field_user_email"]['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );

$form["field_user_email"]['und']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );
$form["field_user_email"]['und'][0]['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );

```

# Answer
If the field is provided by the Email Field module it'll probably be:

```
$form["field_user_email"]['und'][0]['email']['#ajax'] = array(...

```

If it's just a standard text field it will be:

```
$form["field_user_email"]['und'][0]['value']['#ajax'] = array(...

```
> 3 votes

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


# Question
Title: How to list articles by an author in a views?
In Drupal 7, I have defined a node type 'article' which has an 'author' field (The author is not a user, but just a 3rd party contributor). Now I want to list articles by the each author in a view. How can I do that?

I know that it can be done somehow using contextual filters but got quite perplexed so appreciate your help.

# Answer
In your case, i would create a Vocabulary "authors" and add them with a Auto Tag Widget to the Content Type. And add the Authors as a Taxonomy Tag. There are much more Handly then Text Fields. Then you can easily Create a View with the author Tag. And much more, you can also add more fields to the Taxonomy such as author Picture and Author Description.
> 2 votes

# Answer
Ideally the author should be a reference either to an user of the site or to a content type call author, then like you mention using a view you will pass an argument or contextual filter and show only nodes that have that author.

If in you case you don't use a reference, then on your view you just need to add a filter indicating the value of the field with the author name.

Here is where to set the filter:
> 0 votes

---
Tags: views
---


title: How to show mySQL BLOB data

text:
# Question
Title: How to show mySQL BLOB data
Is there a simple way to look at BLOB data that Drupal 7 stores in some tables?

There is a trick to configure phpmyadmin but apparently it's not working with version 3.3.9.2 that comes with MAMP.

# Answer
If you need to peek, say into user-\>data, which is seralised data array, just use `drush sqlc` to bring yourself to an sql command line, then type:

```
 select uid, name data from users where uid = <whateveruidyouwant>;

```

This works for any data, and if you are brave you can even edit the serialized data via command-line but is not recommended unless you know what you are doing.
> 2 votes

# Answer
I would json\_encode the array into a variable and spit it out via devel.

```
$var = json_encode($yourarray);
dpm($var);

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: Drush scripting fails on call to drush_pm_enable()
I'm trying to script the automatic download and install of a set of modules for a Drupal 7 site.

At this point, I have Drupal and all desired modules downloading using a drush make profile, and installation of the site by calling drush\_invoke\_process on site-install.

I'm trying to get the downloaded modules activated after the installation of the site. I have tried a number of things, the latest of which is:

```
(code here...)
drush_bootstrap(DRUSH_BOOTSTRAP_DRUPAL_FULL);
drush_set_context('PM_ENABLE_MODULES',array('ctools', 'views', 'views_ui'));
drush_pm_enable();
(code here...)

```

Every attempt to enable the downloaded modules results in the following error:

> PHP Fatal error: Call to undefined function drush\_module\_enable() in /Users/lhridley/sp/Drupal/tools/drush/commands/pm/pm.drush.inc on line 904

Any ideas?

# Answer
> 2 votes
The Drupal and Drush bootstrap processes are fairly complicated things; it is best no to try to figure out how to call them yourself. If you want to bootstrap and call arbitrary PHP code, you can do so using Drush via `drush @mysite ev 'php code here'`.

As for calling Drush code directly, you should use drush\_invoke\_process, just as you are for the site-install command. So, instead of `drush_pm_enable()`, instead use `drush_invoke_process("@self", "pm-enable", array('ctools', 'views', 'views_ui'))`.

However, if you are running site-install on an installation profile, you should not need to call pm-enable, as the installation profile should take care of that for you. If you're not sure how to build an installation profile, you can have Drush generate one for you. You'll need to use the prototype generate-profile command, which can be found at http://drupal.org/node/1368242. It does not work for D6 sites yet, but works fine for D7, so should be good for your purposes. Take a look at the list of modules generated in your profilename.info file; these will be enabled for you during site-install.

---
Tags: drush
---


title: Problem in Indexing webform result

text:
# Question
Title: Problem in Indexing webform result
I have created full text search in webforms using Search Api and its working fine earlier but when i added some new records, the new records are not indexed and not able to displayed them on view. I don't know why new records are not indexed.

# Answer
> 2 votes
You'll need to re-index the site when new records are being added. You can do it by visiting *http://your-site-url/admin/config/search/settings* and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.

---
Tags: webforms, search
---


# Question
Title: "render ($user_profile)" in user-profile.tpl.php = no output
Following the discussion in http://api.drupal.org/api/drupal/modules--user--user-profile.tpl.php/7 I created a user-profile.tpl.php file in my theme directory, but the code

```
<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); print ("you are here"); ?>
</div>

```

prints the "you are here" but not the `$user_profile` array. Any suggestions as to what I might be doing wrong?

# Answer
> 1 votes
Try installing and enabling the devel module, then edit it so that it reads

```
<div class="profile"<?php print $attributes; ?>>
  <?php krumo($user_profile); ?>
  <?php print render($user_profile); ?>
</div>

```

That will show you what the data actually looks like...

# Answer
> 0 votes
or you may consider all variables that available for your template with debuggung like:

```
debug($variables);

```

---
Tags: users
---


title: Passing filters to a View

text:
# Question
Title: Passing filters to a View
I think this is an easy problem, but cannot solve it. I need to pass arguments from my module to a View3; suppose that i want to pass a part of the node title and need to get all the nodes that start with that value. I cannot expose filters because i have a particular layout that am not able to desing using exposed filters, so i need to pass arguments programmatically. I thought to use Contextual filters but i have not found a way to specify the "Starts with" directive ... What can i do to pass argument?

# Answer
For this purpose is better to use exposed filters. You can hide output of this filter in theming - it still be working. Just pass filters vlue in GET parameters to view's page.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to check node table for entry by current date before inserting new node?
How can I check the database table for specific node entries by date before inserting a new node?

I want to check the node table for any node with the current date, if found, I want to delete the old one and insert a new node.

How can I achieve this.

# Answer
This should do the trick:

Make a module and insert following code, switch "foo" with your module name.

```
    /**
    * Implements hook_node_presave($node).
    */
    function foo_node_presave($node) {
      // Lets search for nodes on the current date.
      $somedate = strtotime(date('Y-m-d'));

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('created', $somedate, '>=');
      $query->propertyCondition('created', $somedate + (60 * 60 * 24), '<');
      $result = $query->execute();

      if (!empty($result)) {
        node_delete_multiple(array_keys($result['node']));
      }
    }

```

Obviously you might want to do some additional checks before deleting the nodes:

```
// Nodes of the same type
$query->propertyCondition('type', $node->type);

//Only delete published nodes
$query->propertyCondition('status', 1);

```
> 2 votes

---
Tags: nodes
---


title: Panels: Show sub terms and child nodes

text:
# Question
Title: Panels: Show sub terms and child nodes
I've just used panels to display child terms on taxonomy pages. For example If my heirarchy is like this...

```
Catalogue
--Category 1
----Sub Cat 1 (contains nodes)
----Sub Cat 2 (contains nodes)
----Sub Cat 3 (contains nodes)
--Category 2
--- Sub Cat 4 (contains nodes)

```

...the 'Category 1' page shows links to Sub cats 1, 2 and 3. That's working fine.

The problem is that once you get to one of the sub categories that contain nodes, the node teasers are not displaying. Is there a way of making these display?

# Answer
Either:

Build a view, taking a term argument, and returning the tagged nodes. Output it in Panels. This will give you the greatest flexibility.

Or:

Look for a "Term to Node" relationship under "Context" in the relevant variant. There might a suitable relationship to pull in the nodes that way, but you may find it hard to control what the nodes look like.
> 1 votes

---
Tags: 7, panels
---


title: Can I run 2 active polls on my site?

text:
# Question
Title: Can I run 2 active polls on my site?
We have a regular poll on our homepage, which I set up by selecting 'most recent poll'.

However, I want to add a different poll on a seperate page on my website. Can I do this? I can't find polls as a block or node function other than 'most recent poll'

Help?

# Answer
Define an auxiliary content type (say MyPoll).

I added a Node reference CCK field to standard Poll and a CCK Node Referrers (backreference) field to MyPoll. You can then easily create one (or even more!) polls as "children" of your MyPoll node, and attach their teaser content (the voting widget) to the MyPoll node.

As MyPoll is a "standard" content type, you can do whatever you want with it in views... including the display of the referred poll widgets. It's not straightforward...

I was inspired by http://www.lullabot.com/articles/photo-galleries-views-attach. Look at it this way: "galleries" are "mypolls", and "images" are "polls".
> 0 votes

# Answer
You can also see and try this module Pollfield
> 0 votes

---
Tags: blocks, polls
---


# Question
Title: theming username field in user-register form
i'm trying to theming my user register form. i would like to have a custom function for the username part. So, i'm doing

```
$form['account']['name']['#theme'] = 'my_custom';

```

i define my hook\_theme and just for testing purpouses, this is my custom function

```
function theme_my_custom( $variables ){
  return 'testing code...'
}

```

My problem is when i go to user/register, i still can see the label for my username. Only the input is replaced by the code of my function. I would expect replace the element entirely, but this is not happening.

Any clues? Thanks.

# Answer
As you can see on the Form API reference page, '#theme' Only affects the input box itself. To remove other things generated by the form API, you'll have to clear the array -

```
$form['account']['name']['#title'] => '';
$form['account']['name']['#description'] => '';

```

or just

```
$form['account']['name'] = array(...);

```

To reset existing elements.
> 1 votes

# Answer
or you may use #after\_build property for your form elements.
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How to manage a views term filter at run-time?
I have a D7 View for which i need to pass filters at runtime and cannot use exposed filters. I use

```
$filter = $view_search_works->get_item($display_id, 'filter', 'filter_name_tid');
$filter['value'] = VALUE;
$view_search_works->set_item($display_id, 'filter', 'filter_name_tid', $filter);

```

for the filter i have defined for a taxonomy term.

If i define the filter with the "Is one of" and select all the taxonomy listed terms,when i pass one of the listed value, it runs fine.

The (big) problem is that if i define a new term (and it can happen) and pass it to the view, the term is not recognized and the view does not work.

Is there a way to say "all the taxonomy terms" for the filter? If i don't select a term when i define the filter, i get "No valid values found on filter:name".

# Answer
> 1 votes
Is it necessary to use a "Filter"? If you can use a "Contextual filter" instead, then this should work without you needing to specify which terms are allowed.

Another, much more complicated option, would be to implement hook\_entity\_insert and update the Views configuration on new terms.

---
Tags: 7, views
---


# Question
Title: Drupal autocomplete form, multiple values
I have created custom module to add user awards. This award = some text(*like Php developer of the month*) and image, and i need to implement feature, which can add this award to multiple users in this form This is my form:

```
function user_awards_admin_settings() {
    $form = array();
    $form['award_description'] = array(
        '#type' => 'textfield',
        '#title' => 'award description',
    );

    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Assign to'),
        '#autocomplete_path' => 'user_awards/autocomplete',
    );
    $form['user_awards_block_image'] = array(
        '#type' => 'managed_file',
        '#name' => 'user_awards_block_image',
        '#title' => t('Block image'),
        '#size' => 40,
        '#description' => t("Image should be less than 400 pixels wide"),
        '#upload_location' => 'public://'
    );

    $form['#submit'][] = 'user_awards_settings_submit';
    return system_settings_form($form);
}

```

And this is my autocomplete function:

```
function user_awards_autocomplete($string) {
    $matches = array();
    $return = db_query("SELECT name FROM users where lower(name) like '" . $string . "%' LIMIT 10");
    // add matches to $matches
    foreach ($return as $row) {
        $matches[$row->name] = check_plain($row->name);
    }
    // return for JS
    drupal_json_output($matches);
}

```

And submit one:

```
function user_awards_settings_submit($form, $form_state) {
    $file = '';
    if (isset($form_state['values']['user_awards_block_image'])) {
        $file = file_load($form_state['values']['user_awards_block_image']);

        $file->status = FILE_STATUS_PERMANENT;

        file_save($file);
    }
    $description = $form_state['input']['award_description'];
    $name = $form_state['input']['name'];
    db_query('INSERT INTO {user_awards} (name, award_description, fid) VALUES (:name, :award_description, :fid)', array(
        ':name' => $name,
        ':award_description' => $description,
        ':fid' => $file->fid,
    ));
    drupal_set_message('form has been submitted');

}

```

I need somehow to make `$form['name']` to be multiple(autocomplete) textfield, comma separated or so, how can i do it? **At this moment its only autocomplete first value of NAME field**

# Answer
> 1 votes
Add a `select` list to your form. Add some `#ajax` to your textfield. Every time the textfield changes content, add the value (via #ajax) to your select list. Use the values of your select list in the submit callback.

OR

You could to it by attaching a custom JavaScript file using `$form['#attached']['js']` with some good old JavaScript to fetch the users and add them to the csv textfield (autocomplete). Then split the values in the submit and add them to the database.

OR

Just use a `select` if that's OK with you.

# Answer
> 1 votes
try next code to autocomplete callback (d6 implementation from my custom module)

```
function _nodetype_autocomplete_multiple($string) {
  // The user enters a comma-separated list of content types. We only autocomplete the last content type.
  $array = drupal_explode_tags($string);
  // Fetch last
  $last_string = trim(array_pop($array));
  $matches = array();
  $result = db_query_range("SELECT type FROM {node_type} WHERE LOWER(type) LIKE LOWER('%s%%')", $last_string, 0, 10);
  $prefix = count($array) ? implode(', ', $array) .', ' : '';
  while ($type = db_fetch_object($result)) {
    $matches[$prefix . $type->type] = check_plain($type->type);
  }

  exit(drupal_json($matches));
}

```

you may want to see full code at github

---
Tags: forms, ajax
---


# Question
Title: How remove DIV elements in rendered search form in theme designing
# the rendered search form result in drupal 6 is

```
<form id="search-theme-form" method="post" accept-charset="UTF-8" action="/drupalcms626/%40q%3Dcontact">
    <div>
        <div id="edit-search-theme-form-1-wrapper" class="form-item">
        <label for="edit-search-theme-form-1">Search this site: </label>
        <input type="text" class="form-text" title="Enter the terms you wish to search for." value="" size="15" id="edit-search-theme-form-1" name="search_theme_form" maxlength="128">
    </div>
    <input type="submit" class="form-submit" value="Search" id="edit-submit" name="op">
    <input type="hidden" value="form-40ac94eba9b49795082bf8daf59eae58" id="form-40ac94eba9b49795082bf8daf59eae58" name="form_build_id">
    <input type="hidden" value="e030363baad8b89de124a2d09bcbeaa7" id="edit-search-theme-form-form-token" name="form_token">
    <input type="hidden" value="search_theme_form" id="edit-search-theme-form" name="form_id">
    </div>
</form>

```

======================================= Now I want to remove all DIV tags in rendered result.

I mean

```
 1. <div>
 2. <div id="edit-search-theme-form-1-wrapper" class="form-item">
 3. </div>
 4. </div>

```

elements

anybody knows how can I do this via theme functions in template.php or page.tpl.php or modifying other \*.tpl.php files.

Please help me.

# Answer
> 2 votes
There are two theme functions you need to override:

1. `theme_form()`, in which the wrapping `<div>` is hard-coded with this line:

```
return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';

```
2. `theme_form_element()` which contains all of the extra `<div>`s you're trying to get rid of.

The latter is quite a long function so there may well be some duplication, but I don't know how else you would do this.

# Answer
> 2 votes
you may create a template for your form and there you may render what you want

like:

```
function mymodule_form_alter($form,&$form_state,$form_id){
switch($form_id){
case 'search-theme-form':

$form['#theme'] = 'my_theme_function'
}

}

function mymodule_theme($vars){
return ('my_theme_function'=>array(
'render element'=>'form',
'template' => 'my-theme-function'
),
);}

```

then create a template file with name my-theme-function.tpl.php in your module's folder or current theme's templates folder and clear the cache.

everything from your form array is available in your tpl.php file as $form variable which you may render something from it. If you want to change anything for your form array do it in your form alter hook.

# Answer
> 0 votes
You can use the theme developer module. It tells you which theme function and/or template to use to modify a certain part of your page.

---
Tags: theming, search
---


# Question
Title: Clone a SelectQuery instance : what am I doing wrong?
I've got a SelectQuery which I've created using db\_select(). Then, after I've executed the query, I'm trying to clone it as I need to generate a few more queries based on the original one.

However, for some reason the clones I get from the original query doesn't seem to be clones. This is what I do.

```
// Create query
$q0 = db_select('track', 't');
$q0->fields('t', array('id','number','title');
[...]
$tracks = $q0->execute()->fetchAll();

// Clear fields on original query.
$fields = &$q0->getFields();
$fields = array();

// Clone original query. The below queries should not have
// any fields set as they just got cleared above.
$q1 = clone $q0;
$q2 = clone $q0;

// This gets weird. The queries $q1 and $q2 should be separate
// clones, independent of each other. So should their fields.
// However, setting fields on $q1 also sets fields on $q2.
$q1->fields('t', array('id'));

// Output : Array ( [id] => Array ( [field] => id [table] => t [alias] => id ) )
print_r($q2);

```

The fields() function on SelectQuery simply sets an array (see below). I thought that cloning an instance of a class containing an array would copy those arrays by value...and not by reference? Is this a special cloning "feature"?

```
protected $fields = array();

public function &getFields() {
  return $this->fields;
}

```

# Answer
As you have seen in bug report #1671848 the special getters of these special drupal objects breaks the clone behavior. The problem is that by reference getter are used and this imply hazardous behaviors in PHP internals of returned values.

I think it will be quite very long until this bug get fixed. So one of the solution is to avoid such writings:

```
$fields = &$q0->getFields();
$fields = array();

```

This is not the way to empty something in an **object**. here the `&` is the fault. after such a write the internal array stored in the object is broken and the object record it as a reference, you've been breaking object encapsulation and bad things happen (sse the bug report). Use a setter, And if there is not setter to do that clone the queries before havinf any field added to the query (so it's empty).
> 1 votes

---
Tags: 7, database
---


title: Change URL of /blogs

text:
# Question
Title: Change URL of /blogs
How would I go about writing a function to change the url of */blogs* to */news*?

# Answer
Since the blog URL is hard coded, make an alias using the (core) path module.
> 5 votes

---
Tags: nodes
---


# Question
Title: User generated review site where users are matched when they review products similarly
On my site users will be able to give a 1 to 5 rating for various different products. I want to show users other users that have rated products in a similar way.

So in simplistic terms, if the followong users rated a prodcut like so:

User A - 5 stars User B - 4 stars User C - 1 stars User D - 0 stars

Then User A and User B would be matched, and User C and User D would also be matched.

How sophisticated an algorithm is achievable with only drupal modules and minimal php? Ideally a point system would find the similarity / difference between users’ ratings for all the products that they have both rated, and then find the top 5 closest matches and rank them accordingly. Thanks

# Answer
> 0 votes
This module looks like it would do the trick. http://drupal.org/project/fivestar\_rec

Details from its project page:

> This module makes content recommendations based on users Fivestar votes. It provides two types of recommendations:
>
> * "Users who liked this also liked": Shows a list of nodes on a node's page. Recommendations are computed based on whether the the nodes received similar Fivestar ratings from users.
> * "Recommendations for you": Shows a list of recommended nodes to the current user based on the user's previous ratings. This is personalized recommendations to each particular user.
>
> The recommendations are provided with the Views module and are fully customizable.

# Answer
> 0 votes
This should be achievable using some combination of Flag, Fivestar, and Views. You can use Views to find users that match criteria based on the current user. You shouldn't need *any* PHP, in theory at least.

---
Tags: rating
---


# Question
Title: dbQuery with condition and date_format()
I have a request that should return a list of nodes that have a creation date \<= 6 months. It works well with `$query->where()` but I want to use `$query->condition ()`.

Query with CONDITION:

```
$query = db_select('node', 'n');
$query->innerJoin('field_data_field_date_de_publication_news', 'fn', 'fn.entity_id = n.nid');
$query->innerJoin('field_data_body', 'fb', 'fb.entity_id = n.nid');
$query->fields('n', array('title', 'status', 'nid'));
$query->fields('fn', array('field_date_de_publication_news_value') );
$query->condition('fn.field_date_de_publication_news_value', 'MONTH(NOW())-6', '<=');
$query->orderBy('fn.field_date_de_publication_news_value', 'DESC');
$rows = $query->execute();

```

But if I replace CONDITION with WHERE it works:

```
$query->where(" MONTH(fn.field_date_de_publication_news_value) <= MONTH(NOW())-6" );

```

I also tried:

```
$query->fields('fn', array("DATE_FORMAT(FROM_UNIXTIME(field_date_de_publication_news_value), '%m')") );

```

# Answer
> 2 votes
`condition()` can only be used for simple expressions (`=`, `>`, `<`, `<>`, `BETWEEN`, `LIKE`, and a few others).

Using `where()` as you are already is the correct way to construct a more complex query.

---
Tags: entities
---


title: How do I use theme('pager')?

text:
# Question
Title: How do I use theme('pager')?
I have problem to understand how I should use `theme('pager')` as explained on EntityFieldQuery display pager.

I can't make it work (display pager and links to resulting pages).

Does `pager(10)` in `EntityFieldQuery` automatically invoke the pager? Should it be displayed with `print(theme('pager'))`?

Is this functionality included in Drupal core (7.15)?

I am doing my queries in template.php and injecting the query result in article.tpl.php through a variable.

As a workaround, I am thinking of doing two queries, one to find out what the number of nodes that meet a condition is, output links with numbering, attach the variable to those links, read the variable in another query and select the resulting nodes with `range($i,$j)`.

# Answer
> 7 votes
> Does `pager(10)` in `EntityFieldQuery` automatically invoke the pager?

Yes; it even avoids the usual problem of multiple pagers on a single page conflicting, by getting a new delta from the `PagerDefault` class.

> Should it be displayed with `print(theme('pager'))`?

Yes (but obviously only if there is more than one page worth of results to display).

> Is this functionality included in Drupal core (7.15)?

Yes.

This works perfectly for me:

```
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();
$nodes = node_load_multiple(array_keys($results['node']));

$build = array(
  'nodes' => node_view_multiple($nodes),
  'pager' => array(
    '#theme' => 'pager',
  )
);

```

That's returned from a menu callback function, so will be passed through `drupal_render()`. When it does so, a list of node teasers is displayed with the expected pager right below.

If the same example doesn't work for you then there must be something wrong with your installation, or something in a custom/contributed module conflicting with the core pager system.

---
Tags: theming, paging
---


# Question
Title: Refresh a table after a selection of records
I want to write a module with a textfield, a submit button and a table. The starting page displays an empty textfield, the button and the table that shows all the records. When the user writes something in the textfield, and clicks the button, the web page refreshes itself; then the table should contain only the records with the same Name Field as the string that the user wrote. Unfortunately, it doesn't works: The new page displays the same records shown before, even if the query produced a correct table.

This is the code I use.

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

  $form = array();

  $form['textfield_input'] = array(
    '#type' => 'fieldset',
    '#title' => t("Compilare i campi in base alla ricerca che si desidera effettuare.")
  );

  $form['textfield_input']['nome'] = array(
    '#type' => 'textfield',
    '#title' => t('Inserisci un nome'),
    '#size' => 15,
  );
  $form['textfield_input']['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Find"),
  );

  $select = db_select('persone_prova_db', 'p');

  // Join the users table, so we can get the entry creator's username.
  $select->join('indirizzi_prova_db', 'i', 'p.residenza = i.id');

  // Select these specific fields for the output.
  $select->addField('p', 'id');
  $select->addField('p', 'cognome');
  $select->addField('p', 'nome');
  $select->addField('p', 'codice_fiscale');
  $select->addField('i', 'id');
  $select->addField('i', 'via_piazza');
  $select->addField('i', 'civico');
  $select->addField('i', 'comune');
  $select->addField('i', 'provincia');

  // Make sure we only get items 0-49, for scalability reasons.
  $select->range(0, 50);

  // Get all entries in the prova_db table.
  $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);

  if (!empty($entries)) {
    $rows = array();
    foreach ($entries as $entry) {

      // Sanitize the data before handing it off to the theme layer.
      $rows[] = array_map('check_plain', $entry);
    }

    // Make a table for them.
    $header = array(t('Id Persona'), t('Cognome'), t('Nome'), t('Codice Fiscale'),
                t('Id Indirizzo'), t('Via/Piazza'), t('Num. Civico'), t('Comune'), t('Provincia'));
  }else {
    drupal_set_message(t('No entries meet the filter criteria.'));
  }

  $form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
  );
 return $form;
 }
 function prova_db_advanced_list_submit($form, &$form_state) {
  drupal_set_message(t("Tabella"));
  drupal_set_message(t("Il nome inserito è @name_to_find",  array('@name_to_find'=>$form_state['values']['nome'])));
  $name_to_find = $form_state['values']['nome'];
  $select = db_select('persone_prova_db', 'p');

  // Join the users table, so we can get the entry creator's username.
  $select->join('indirizzi_prova_db', 'i', 'p.residenza = i.id');

  // Select these specific fields for the output.
  $select->addField('p', 'id');
  $select->addField('p', 'cognome');
  $select->addField('p', 'nome');
  $select->addField('p', 'codice_fiscale');
  $select->addField('i', 'id');
  $select->addField('i', 'via_piazza');
  $select->addField('i', 'civico');
  $select->addField('i', 'comune');
  $select->addField('i', 'provincia');
  $select->condition('p.nome', $name_to_find);

  // Make sure we only get items 0-49, for scalability reasons.
  $select->range(0, 50);

  // Get all entries in the prova_db table.
  $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);

  if (!empty($entries)) {
    $rows = array();
    foreach ($entries as $entry) {
      // Sanitize the data before handing it off to the theme layer.
      $rows[] = array_map('check_plain', $entry);
    }
    drupal_set_message(t("Table: @rows", array('@rows' => $rows)));
    $form['table']= array('#type' => 'value', '#rows' => $rows);
      $form_state['rebuild'] = TRUE;
  }else {
    drupal_set_message(t('No entries meet the filter criteria'));
  }
}

```

I don't understand where I'm wrong. I searched if someone else have the same trouble, but I haven't found the way to solve this problem.

Can anyone help me?

# Answer
`$form` is an array that is not passed as reference to the form submission handler; therefore, any change done to `$form` from the submission handler is local to the form submission handler. This is similar to what happens with the following code.

```
$array = array('a' => 10);
$array = update_array($array);
check_array($array);

function update_array($array) {
  return $array + array('b' => 20);
}

function check array($array) {
  $array['b'] = 30;
}

```

After that code is executed, `$array['b']` is still equal to 20.

The only parameter that is passed by reference is `$form_state`. If you want to pass a value back to the form builder, from the form submission handler, or the form validation handler, you need to use `$form_state`, which mean the form submission hander should use code similar to the following one.

```
$form_state['table_rows'] = $rows;

```

The form builder should use the following code.

```
if (!empty($form_state['table_rows']) {
  $rows = $form_state['table_rows'];
}
else {
  // Execute the query that gets every row in the database table.
  // Assign the found rows to $rows.
}

$form['table'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('Empty Rows')
);

```

The values you are placing in `$rows` is wrong. What you are using in an array similar to the following one.

```
array(
  'column 1 name' => 'column 1 value',
  'column 2 name' => 'column 2 value',
)

```

The array theme\_table() is expecting is one of the following.

```
  array(
    'column 1 value', 'column 1 value', 'column 2 value'
  )

```

```
 array(
    'data' => array('column 1 value', array('data' => 'column 2 value', 'colspan' => 2)), 'class' => array('column-class')
  )

```

Supposing the changes to the content of `$form` would be propagated externally to the form submission handler, the code for the form builder is writing `$form['table'] without first checking if`$form\['table'\]`is set; this would mean losing the value for`$form\['table'\]\` set from the form submission handler.
> 1 votes

---
Tags: forms
---


# Question
Title: How to define another teaser for the second theme?
I have two themes: regular (1st) & mobile (2nd). Mobile theme binded with subdomain m.mysite.com.

**I can't show my mobile node teaser in mobile theme.**

I've created that teaser for mobile theme in Display Suite. Next I need to show this one in mobile theme taxonomy tag page. But I can't define theme in DS. When I use \[taxonomy-term.tpl\] in mobile theme to define mobile teaser, but vars doesn't works: changing $view\_mode has no result (type machine name on mobile teaser), $content array is empty. I tryed to use Views, but in displays there is no options to define a theme.

What can I do? Thnx

# Answer
> 0 votes
Problem solves by the following:

1. Created DS template for default teaser in 2nd theme: ds-2col--node-article-teaser.tpl.php
2. Place into it code to define my new node\_teaser\_mobile to show:

print render(node\_view($node, $view\_mode = 'node\_teaser\_mobile', $langcode = NULL));

---
Tags: views, theming, nodes, display-suite
---


# Question
Title: Not_compatible_with_d7 after installing User Points Contributed modules
does anyone know why it displays 'Not\_compatible\_with\_d7' beside a number of modules in the User Points Contributed modules project after install as though it was a missing module even though they all say they are compatible with D7 (and they installed fine).

# Answer
> 0 votes
The reason you see that error message is that the content of the votingpoints.info file is the following one.

```
name = Votingpoints
description = Rules integration for users earning points as they vote on nodes. With the rules approach, the node author can be assigned userpoints too.
package = Userpoints
dependencies[] = userpoints
dependencies[] = rules
dependencies[] = not_compatible_with_d7
core = 6.x

```

not\_compatible\_with\_d7.module is reported as dependency of the module, and Drupal tells you that module doesn't exist.

What happened is that a Drupal 6 module has been committed in the Drupal 7 branch of the project; in this way, who wants to port the module for Drupal 7 can easily create a patch for the Drupal 7 branch of the project. The problem is with the script creating the archives containing the code of a Drupal.org project adds the like "core = 7.x" overriding the "core = 6.x" line added to the votingpoints.info file. This would cause Drupal to think the module is compatible with Drupal 7, which is not true.

The only workaround the authors of the modules found was to add, as dependency, a module that doesn't actually exist. That is the only thing that can be done, until the packaging script used from Drupal.org overrides the line reporting the Drupal version with which the module is compatible.

---
Tags: userpoints
---


title: how to manage url redirects in drupal 7

text:
# Question
Title: how to manage url redirects in drupal 7
My website is currently accessible via 2 address

www.mydomain.com and mydomain.com

What is the best way to manage redirects. I would like

mydomain/blah to redirect to www.mydomain.com/blah

# Answer
> 3 votes
I always use the vhost file for this:

```
# Enforce domain.
RewriteCond %{HTTP_HOST} !^example.com(:.*)?$
RewriteCond %{HTTP_HOST} ^(?:.*?)(:.*)?$

RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

```

I would much rather to this on the Apache level, than PHP, to keep it as fast a possible.

Similar configuration for nginx here.

# Answer
> 3 votes
You can open up the .htaccess file that's in the root directory of your Drupal install and uncomment the last two lines of this code snippet starting with RewriteCond and RewriteRule.

```
  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

Right after this snippet in the .htaccess file, there's another couple of lines to uncomment if you wanted www.example.com to redirect to example.com.

# Answer
> 1 votes
Looks at a redirect module like 301 redirect, I have not tried it but the description seems to cover what you require.

---
Tags: 7
---


# Question
Title: Is making field.tpl.php print the URL of the node the displayed field is attached to possible?
Currently I have this setup with Views but I would like to take views out of the picture to optimize the site and fix a couple of problems that occure as a result of using Views.

What I am trying to achieve is if my nodes have content in a Body of Text called excerpt that it will show a button that links to the node's url and append the text "/excerpt" at the end of the node's url which will then display a different page with the content of excerpt on it.

I'm using Drupal 7 and am modifying a Zen subtheme.

# Answer
The solution is`<?php print drupal_get_path_alias("node/".$element['#object']->nid); ?>`

This will print the URL Alias of the node that the respective field is attached to.

I found that I could get the NID of the node the element was attached to by doing`<?php print_r($element['#object']);?>`to find all of the available options for`<?php $element['#object']?>`when I found I could get the NID from that field I then put it inside of`<?php drupal_get_path_alias() ?>`and have it return the desired text.

It took a day to find it but it works. Hopefully someone else can benefit from this as well.
> 1 votes

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


# Question
Title: Easiest way to export specific user-generated content?
I'm using Drupal 6.x on a site that has many users. There are about 20 "Pro" users that function as authors. I need to export an individual author's posts in order to later import them into WordPress. What might be the easiest way to accomplish this?

Bonus! I also need to export the comments associated with each article, AND change all comment authors to "Anonymous." Should I do that after the export through SQL, or is there an easier way?

I am looking into the Views module, but it's pretty far over my head... I would certainly prefer a simpler solution if that is possible.

Thanks for the help in advance!

# Answer
Views module is the only solution which makes your task very easy.

1.Simply create a view and add the necessary **fields** you want to export.

2.Add a **display** (data export).

3.In **DATA EXPORT SETTINGS** name your path with .csv extension example data.csv

Finally call the path on your browser. That's it

Another difficult way is to write queries and then create a php code to export the result to csv
> 1 votes

---
Tags: importing-exporting
---


# Question
Title: How do I make a form in Add Content using Drupal 7?
I am trying to get my Drupal 7 website working with PHP and an external database. I would like to have user interaction via forms, but all the examples I can find on the web hint that you have to write your own module to do this. I couldn't find a good description of even that process from the ground up. Is there a way to add a form using the standard Add Content -\> Article or Basic Page? Is that a bad way to do things? I would like a page that is a form and when the user presses the submit button the same page loads, but now with the data retrieved from the database that was requested.

# Answer
> 1 votes
I'm not sure if you really can do this with it, but have a look on: Webform

# Answer
> 0 votes
I suggest you 3 method to add a node programatically

* first method

```
// required for Drupal 6
module_load_include('inc', 'node', 'node.pages');
// which nodeform you want
$node_type = 'YOURNODETYPE';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node
$node = array(
 'uid' => $user->uid,
 'name' => (isset($user->name) ? $user->name : ''),
 'type' => $node_type,
  );
  // Invoke hook_nodapi and hook_node
  node_object_prepare($node);
 // Or you can also use an exiting node, for example
 // $node = node_load(123);
 // and the display the form:
 $output = drupal_get_form($form_id, $node);

```
* second method

```
 module_load_include('inc', 'node', 'node.pages');
 $node_type = 'YOURNODETYPE';
 $form_id = $node_type . '_node_form';
 global $user;
 $node = array(
'uid' => $user->uid,
'name' => (isset($user->name) ? $user->name : ''),
'type' => $node_type,
);
node_object_prepare($node);
print drupal_get_form($form_id, $node);

```
* third method

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
$output = drupal_render($form);

```

useful link(maybe)

# Answer
> -1 votes
no. I thought you want to do this in your custom module . if you not very skillful in module developing I suggest you use `php block`. enable `PHP filter` module in default core drupal module, then create a block in `Home » Administration » Structure » Blocks` put this in `body`
**change nodetype to your optional contenttype you have**

```
  <?php
   module_load_include('inc', 'node', 'node.pages');
   $form = node_add('nodetype');
   $output = drupal_render($form);
   ?>

```

and in text filter select `php filter` .save it and in block list put it in your optional region and determine **Visibility settings** with you optional.

---
Tags: nodes
---


# Question
Title: Notice: Undefined index: main_profile in include() (line 54
```
global $user;
$user->uid ;
print_r($user->uid);
print "print out the user value" . $user->uid;

$uid =3;

$account = user_load($user->uid);

$profile = profile2_load_by_user($account);

$print_first_name =  drupal_render(field_view_field('profile2',$profile['main_profile'], 'field_first_name'));
print $print_first_name;

```

What I have attempted to do is to pass the `$user->uid` to the `user_load` function. When I pass `$uid = 3` to the `user_load` function it seems to work fine. I am wondering what approach I should try to fix this problem.

error message:

EntityMalformedException: Missing bundle property on entity of type profile2. in entity\_extract\_ids() (line 7562 of /home/td6/public\_html//includes/common.inc).

# Answer
Your mistakes is here `main_profile` , profile type always start with **profile\_name** . just need change main\_profile to **profile\_main**

```
global $user;
$user->uid ;
print_r($user->uid);
print "print out the user value" . $user->uid;

$uid =3;

$account = user_load($user->uid);
$profile = profile2_load_by_user($account);

$print_first_name =  drupal_render(field_view_field('profile2',$profile['profile_main'], 'field_first_name'));
print $print_first_name;

```

If you want see all your profile type and correct name and it's contents print\_r or var\_dump `$profile`

```
$profile = profile2_load_by_user($account);
print_r($profile);

```
> 1 votes

---
Tags: users
---


# Question
Title: Login form - hook_form_alter destinations broken
I have a custom log in template along with some alterations. It seems to work just fine everywhere except where I have `...?destination=foo/bar`.

The template code is:

```
<div id="fdanconia_login">
  <div id="fdanconia_login_form">
    <?php print render(drupal_get_form('user_login', $form)); ?>
  </div>
  <div class="register_now">Don't have an account? <b>Register now</b></div>
  <div id="fdanconia_register_form">
    <?php print render(drupal_get_form('user_register_form')); ?>
  </div>
</div>

```

The module code is:

```
function fdanconia_menu(){
  $items['login'] = array(
    'title' => 'Login',
    'page callback' => '_fdanconia_login',
    'access callback' => true,
  );
  return $items;
}

function fdanconia_theme(){
  $themes = array(
    'fdanconia_login' => array(
      'template' => 'fdanconia_login',
      'arguments' => array(),
    ),
  );
  return $themes;
}

function fdanconia_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  switch ($form_id) {
    case 'user_login':
      // Redirect users to the new login page
      if (isset($_GET['destination']) && $destination = $_GET['destination']) {
        $options = array('query' => array('destination' => $destination));
        unset($_GET['destination']);
      } else {
        $options = array();
      }
      if (arg(0) == 'user' && !$user->uid) drupal_goto('login', $options);
      $form['name']['#description'] = 'Email';
      $form['pass']['#description'] = 'Password';
    break;
    case 'user_register_form':
      if (arg(0) == 'user' && !$user->uid) drupal_goto('login', array('query' => array('destination' => $destination)));
      $form['account']['name']['#type'] = 'hidden';
      array_unshift($form['#validate'], '_fdanconia_login_validate');
    break;
  }
}

function _fdanconia_login() {
  drupal_add_css(drupal_get_path('module', 'fdanconia') . '/fdanconia.css');
  drupal_add_js(drupal_get_path('module', 'fdanconia') . '/fda.js', 'file');
  return theme('fdanconia_login');
}

function _fdanconia_login_validate($form, &$form_state) {
  $email = $form_state['values']['mail'];
  $form_state['input']['name'] = $email;
  $form_state['values']['name'] = $email;
  $form_state['complete form']['account']['name']['value'] = $email;
}

```

So, when I log in with a destination no matter what it redirects to the default log in page as if there were no destination parameter. However, the destination shows up in the URL. I can even manually put a destination in the URL and when I submit the form, I am not redirected to the proper destination. There is nothing in watchdog about the log in other than a session has been created.

What is going wrong here?

# Answer
> 1 votes
In Drupal 7 redirection needs to both `$form_state['rebuild'] = TRUE;` and `$form_state['redirect'] = 'whatever';`

```
//Implementation of hook_form_alter()
function custommade_form_alter(&$form, &$form_state, $form_id)
{
    switch($form_id) {
        case 'comment_node_article_form':
            $form['#submit'][] = 'custommade_custom_submit';
    }
}

//Custom submit handler
function _custommade_custom_submit($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = 'whatever';
}

```

# Answer
> 1 votes
I think in D7 you can also use the redirect property, this would be in your form\_alter:

```
  $form_state['redirect'] = array('http://www.example.com/my-external-path', array('external' => TRUE));

```

$form\_state\['redirect'\] takes the same values as drupal\_goto(), which itself uses url() to generate its destination path. It is possible to add an array of options including 'external=TRUE' to your redirect value if redirect is external.

Not sure if this will help in your case though.

---
Tags: hooks, users, forms
---


title: Auto increamented field in webforms

text:
# Question
Title: Auto increamented field in webforms
I need to create a auto generated number in web forms. I have used serial module for this but its working on webform in content. Please help me how i can do this.

# Answer
Create a custom module and alter the fields value using `hook_form_alter()`

```
<?php

function pahcom_form_edit_module_form_alter(&$form, &$form_state, $form_id) {
    if($form_id =='formid) {
        $new_value = rand(100000,10000000);
        $form['submitted']['vendor_id']['#default_value']=$new_value;
        //$form['submitted']['vendor_id']['<h</h4>default_value']=$new_value;
    }
}

?>

```
> 2 votes

# Answer
Could you not use the sid of the submission? This will already auto increment
> 1 votes

---
Tags: 7, webforms
---


# Question
Title: No search results display when using core search
I have added Drupal the search module block and it displays the search form.

When I type and click on search button, it displays nothing, just a refresh in page only.

What do I need to do to get search results to show up? I could use alternative search modules if that is recommended/necessary.

**Note**: I've already indexed the content. In configuration page, it's showing "*your 100% content has been indexed*".

# Answer
Actually, It was just a refresh happens to the page, while clicking the search button. Anyway, I just added custom search module in drupal and its now working fine :). Thanks for all :)
> 0 votes

---
Tags: search
---


# Question
Title: Query with db_select() to select node by id and join field and terms
I am trying to write a query using db\_select that selects a particular node by id, and then joins it's field\_data\_field\_projectresources column and also selects the terms from taxonomy (because this is a term\_reference field)

I have tried numerous attempts but I am finding myself stuck (I didn't even get to the part about joining the dr\_taxonomy\_term\_data table)

```
 $query = db_select('node','n')
  ->condition('n.nid','5')
  ->fields('n')
  ->fields('p');
 $query->Join('field_data_field_projectresources','p','p.entity_id = n.nid');
 $result = $query->execute();

 while($record = $result->fetchAssoc()) {
   print_r($record);
 }

```

Any help appreciated, Thanks

# Answer
> 8 votes
I hope this works for you:

```
 $query = db_select('node','n');
 $query->join('field_data_field_projectresources','p','p.entity_id = n.nid');
 $query->fields('n',array('yourfieldnames'))
       ->fields('p',array('yourfieldnames'))
       ->condition('n.nid','5');
 $result = $query->execute();

```

Here is another answer that will help you very much.

Check out documentation for 'join' on drupal.org.

---
Tags: database
---


# Question
Title: Is there a module for scalable input / output for unlimited value fields?
In a field with unlimited values a user may easily enter 100+ items. While the db does allow unlimited entries, the client side input does not seem too scalable since it shows all values on the same page. Perhaps some kind of **paging** or Views would be great. Is there such a module?

# Answer
> 3 votes
You could of course write both a formatter and a widget to implement some sort of paging, but that doesn't change the fact that Drupal will always load all 100+ field items when loading the node *and* saving (by doing a DELETE first and then an INSERT) of all 100+ field items when saving that node.

There isn't really a nice way to do this properly using fields. In case of references (node, user, ..), a possible workaround is to reference those entities to the current one, so that each one only has one (or a few) references, instead of 100%. Then you can display them on the referenced entity using a view.

Using a non-relational field storage implementation like MongoDB can help with the storage performance problems because it's a single load/save operation, no matter how many fields and field items you have. But it's still one global operation for all field items at once.

# Answer
> 1 votes
I have a workaround for this one. It is not pretty, but it works.

1. Make your field single value. (very important, so Drupal loads only one field item).You may use this item to hold some metadata about this field. I use it to save total number of field items.
2. Create another table, which holds your actual field values, indexed by the entity ID of your field.
3. In your formatter or widget, add the necessary pager to load current page You must work your own part on save, delete and validation, essentially some form validation and submit code.

In this way, you only load the values of field per page, and you can even do AJAX on current page.

One issue I think it is worth to take attention: Drupal 7's behaviors is based on jQuery 1.4 (I suspect that .once has only jQuery 1.4 version). If you want to use features on jQuery 1.7 or later, you need to load it with noConflict function. I find it works perfectly with two versions of jQuery and jQueryUI on the same page.

# Answer
> 0 votes
I will try to make it a module. So far I have a module customized for one field with complicated data structure. I can do pagination, adding new field item by ajax, and sorting field item by JQueryUI Sortable. The field Item is themable.

---
Tags: 7, entities
---


title: Using Page Title with Node Tags

text:
# Question
Title: Using Page Title with Node Tags
I'm using the following modules

* Meta Tags
* Page Title

I need to be able to make the sites title work like this:

Use the title set in Meta Tags for each Node first of all, if this isn't set then default to the Page Title module.

If this isn't set, just use the pages title.

How do I set a precedence for the titles? Do I have to hook into html\_head\_alter?

Any help is greatly appreciated,

Cheers

# Answer
Have you checked the auto nodetitle module with the token Module. Then you can create the node Titles with tokens. Check also the Automatic Entity Label i think its better for your Usecase
> 3 votes

# Answer
Er, just checking, think I was actually referring to the master metatags settings page when using the word 'global' there.

Whilst debugging I changed my settings on the node itself, but also in admin/config/search/metatags I thought I would need to set the rule 'globally' in admin/config/search/metatags, as this is where the content types get their configuration settings form. Then i assumed, this could be overridden on a per node basis by setting the page title on the node itself.

I've added some attachments to confirm my settings.
> -1 votes

---
Tags: nodes, 7
---


# Question
Title: How to redirect to a node/add page after clicking on a flag link
I want to set a flag to link to a node creation page - i.e., when a user clicks on the flag ("Apply for this Job") they should be redirected to a Job Application creation page where they can fill out an application for the job.

So for flag action I selected the "Redirect to URL" action and entered node/add/job-application. But when a user clicks on the flag there's no such redirection, the user is never sent to the node creation page. Am I missing something or just using the wrong method?

# Answer
> 1 votes
Ok, I myself test this for you, please first install and enable `Rule` and `Rules UI` ,after it (I suppose you have a flag with 'myflag') . Go to `dmin/config/workflow/rules` and `Add new rule` ,set your name and in **React on event** in flag group select `A node has been flagged, under "myflag"` save it ,after it in **Actions** section choose `Add action` , in **Select the action to add** in `system` group choose **Page redirect** ,after it set your path want to redirect it in **Value**. (is better check **Force redirect**). I hope works for you correctly.

# Answer
> 0 votes
If you jobs is too force I suggest you handle your job with jquery and javascript.

something like this

```
$('.flaglinkclass').click(function(){
  document.location.href = "youroptionamlpath";
 });

```

---
Tags: flags
---


title: Webform - trying to set submit handler

text:
# Question
Title: Webform - trying to set submit handler
On a Drupal 7 Webform I've added a button using a markup field like this:

```
<button name="get" value="" type="submit" class="primary-submit submit" id="get">
Get Address
</button>

```

I am directing it to a submit handler like this:

```
function new_webform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {
    $form['submitted']['name']['get']['#submit'][]='new_webform_get_submit';
    dpm($form);
  }
}

```

I can tell the button `#submit` is being changed, but the whole form is submitted instead of executing the handler code. What am I doing wrong?

# Answer
> 1 votes
Turns out the form was not actually being submitted but the custom handler was not being processed because the form validation was failing. I disabled it with

```
$form['submitted']['name']['get']['#limit_validation_errors']=array();

```

and now the handler works.

# Answer
> 1 votes
In a general scenario, to add a custom submit handler to any Drupal form you can implement hook\_form\_alter or hook\_form\_form\_id\_alter

you will have to add the submit handler in the #submit array, something like this,

```
$form['#submit'][] = 'my_custom_submit_handler'; //this function will accept $form and $form_state as args.

```

same can be done for #validate if you want a extra validate handler.

Cheers.

---
Tags: 7, webforms
---


# Question
Title: submit handler not working when using hook_form_alter
I am using hook\_form\_alter to add validation and submit handlers to the registration form:

```
<?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#validate'][] = 'blah_register_validate';
    $form['#submit'][] = 'blah_register_submit';
  }
}
?>

```

They were both working fine until I added the following hook:

```
<?php
function MYMODULE_user_login(&$edit, $account) {
  drupal_goto('user');
}
?>

```

The validation function still works but the submit function gets bypassed completely - it doesn't get called at all by form\_execute\_handlers() in form.inc. As soon as I remove hook\_user\_login, it works again. Anyone have an idea why?

**Update:**

hook\_user\_login() gets called by user\_login\_finalize() in the User Module. Unfortunately, this happens before my submit function gets called - so obviously when I use drupal\_goto() the submit function will never get called. Can anyone confirm if I am adding the submit handler correctly, is there another way?

# Answer
> 3 votes
If you check out `drupal_goto()` you can see it calls `drupal_exit()` which is not something you want to do in a hook. The comments for `hook_user_login()` discuss this a little, finishing with this snippet:

```
function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location
  $redirection = 'node/394';

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}

```

Also mentioned is the login destination module.

# Answer
> 1 votes
read about drupal\_get\_destination function. *Used to direct the user back to the referring page after completing a form*.

You should try something like this(*If I understand the question*) : `drupal_goto('user', array('query'=>drupal_get_destination()) );`

If you trying to add a *new* Submit handler to an existing `user_login_form` you should try this:

```
 $form['new_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#submit' => array('blah_register_submit'),//name of your submit function
    );

```

---
Tags: forms
---


title: Block Module jQuery Slider for Homepage

text:
# Question
Title: Block Module jQuery Slider for Homepage
I have a simple jquery slider for the homepage of a website, which works in my static HTML/CSS layouts.

I want to incorporate this front-end mark-up into a block module that will allow an admin to add/edit/remove slides. Is there a good module that already does this that I could hack with to get this functionality. Or even better does anyone know a good tutorial (doesn't have to be for a slider), that shows developing a module where you can add/edit multiple items specific to that block module (separate to the main content); in my case it would be adding/editing slide items to the slider.

# Answer
> 3 votes
From reading your question, I take it you have zero integration with Drupal. You simply hardcode your entire slideshow in a block.

What I would suggest is that you start with creating a new content type, and then apply either Field slideshow or Views slideshow onto it.

> Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.
>
> Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

> Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

# Answer
> 1 votes
To create a slider u need install this modules *(1) Views (2) Views UI (3) Views Slideshow (4) Views Slideshow: Cycle (5) Chaos tools (6) Link (7) Libraries (8) Token (Optional)* First of all you need to create Image Cache with core module named **Image Styles** to resize your images for slider. Then u need to create new Content type with hidden comments and hidden author and date info. After this you will need to add some fields to this content type: **1) Image Field** with this settings

> ```
> (1) Label: Slider Image
> (2) Field: slider_image
> (3) Field type: image
> (4) Widget (form element): image
> (5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
> (6) On the image field configuration settings page you can configure as you wish.
>
> ```

2)Link Field:

> ```
> (1) Label: Slider Link
> (2) Field: slider_link
> (3) Field type: link
> (4) Widget (form element): link
>
> ```

Next you need to create content and upload there your images After this you will need to create new View, where you can display your slider what ever you want.

Full tutorial you can find HERE

---
Tags: javascript, blocks
---


# Question
Title: Drupal Commerce hide cart to non authenticated users
I have a drupal 7 commerce install. I have made the views only accessible to authenticated users, but when I am not authenticated, and type in "mysite.com/cart" I still can see the cart (even though it has nothing in it).

I am using the content access module to prevent non authenticated users from viewing my produces, but I don't want anyone who is not logged in, to even know the website doubles as a store. How do I hide the cart page?

# Answer
> 5 votes
A quick fix might be to write a tiny custom module that overrides the `access callback` for the cart page:

```
function MYMODULE_menu_alter(&$items) {
  $items['cart']['access callback'] = 'MYMODULE_cart_access';
}

function MYMODULE_cart_access() {
  if (user_is_logged_in()) {
    return user_access('access content');
  }

  return FALSE;
}

```

---
Tags: commerce
---


title: CCK compound field?

text:
# Question
Title: CCK compound field?
Given an arbitrary list of CCK fields, I would like to compound them together so that a **add more items**-click adds one more of the entire collection of fields.

Much like the field collection functionality, back-ported to CCK.

# Answer
> -2 votes
Follow this link and you will get you answer.

---
Tags: entities
---


# Question
Title: Problem with drupal 7 multisite installation
OS: UBUNTU 11.10

What I want to achieve:

www.example.local **Main Installation**

www.example1.local **Installation inside sites folder**

I took the following steps:

Installed drupal 7 as normal installation in the folder `/var/www/example`.

in **/etc/hosts** added the following:

```
127.0.0.1   www.example.local

127.0.0.1   www.example1.local

```

Then in **/etc/apache2/sites-available** ::

`ServerName www.example.local`

`DocumentRoot /var/www/example`

in `example` file.

and

`ServerName www.example1.local`

`DocumentRoot /var/www/example/sites/www.example1.local`

in `www.example1.local` file.

I created folder

> /var/www/example/sites/www.example1.local

and copied default.settings.php and made a `settings.php` from it.

Now , when I go to www.example.local I get the normal(main) installation it works fine.

But when I go to `www.example1.local` I see the list of files in the `www.example1.local` **folder**

What is the step I am missing? Or did I do something wrong ? Thank you in advance.

PS: I have not made any change in settings.php of the subsite.

# Answer
> 2 votes
Documentroot is not proper for the second case. It should be like this

```
ServerName www.example1.local
DocumentRoot /var/www/example

```

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


title: Menu item to view with wildcard

text:
# Question
Title: Menu item to view with wildcard
I created a view that dynamically displays some nodes depending a wildcard in the path. The view path is something like /fruits/% So /fruits/apples would show all the apple nodes, /fruits/oranges all the orange nodes and so on.

Works great when I directly go to a path like www.mysite/fruits/apples but I can't create a menu item with the path 'fruits/apples', I always get the message The path 'fruits/apples' is either invalid or you do not have access to it. Also tried creating URL aliases for the path but same message.

/\* Update \*/

I use this code to get the argument I need to load the right 'fruit', it returns false when no term\_id is set, and that seems to be a problem. When return true, I can set the menu item but then the view will always try the display the page in stead of showing the 'No Results Behavior'

```
$term = taxonomy_get_term_by_name(arg(2), 'fruit_type');
$term_id = key($term);
if(isset($term_id)){
  $handler->argument = $term_id;
  return TRUE;
}

return FALSE;

```

# Answer
> 1 votes
Don't confuse `fruits/apple` with `fruits/apples`. Drupal will not allow you to create menu entries for paths whose Views Contextual Filter argument does not validate.

---
Tags: 7, views, routes
---


# Question
Title: 7- Disable a block or edit it without access to the admin interface
I activated php code in a block in the header, and I put "echo $user;" instead of "echo $user-\>name;".

Now I get an error on page load and can't edit the block to correct the mistake.

If I could change the active admin theme back to bartik, that would also solve the problem.

Any ideas welcome. Thanks

Edit: ok I think I solved by deleting my custom theme folder. Good that the block was only enabled for the custom theme.

# Answer
If you have devel installed, you can edit the default theme by editing theme\_default variable. http://yoursite.com/devel/variable/edit/theme\_default

Or deactivate the block in your database

update blocks set status = 0 where delta = 'block';
> 0 votes

---
Tags: 7
---


# Question
Title: How can i authenticate a user without using Drupal functions?
I need to authenticate a D7 user from a php page from outside a Drupal session. In D6 i could have used the md5() function, now i've seen that this is not possible due to changes to D7 authentication. How can i do it without using Drupal functions?

# Answer
> 1 votes
If you look in the `includes/password.inc` file in your drupal 7 installation, you can see how drupal 7 hashes up the password and then code that up separately or just include that file in your other script. A quick tutorial on this can also be found here.

---
Tags: 7, users
---


# Question
Title: Display content on a node which is referenced in another node
I have a content type called 'style' and another one called 'style - description'. Unfortunately, it's necessary to split the two up. 'style' will be a sort of portal page, while 'style - description' contains further information about said style.

So, 'style - description' has an entity reference field that points to one of the 'style' nodes. I want to display content from a 'style - description' node on the 'style' node that has been referenced.

I've been trying to do this through a view with a relationship and a contextual filter, though I don't seem to be getting anywhere with that. Anyone any ideas?

# Answer
I think you forgot to add a **relationship** in your views.

If you use References module it works.(i know it'll be deprecated soon but for now it works well and save my life few times:))

* In your content type add a field `node reference` to the article
* In your views add a contextual filter \[node:id\] (add some validation criteria about your content type)
* After add relationship
* After you can hide the fields (don't forget in the setting formatter: rendered node)

After that you'll have the result you want.
> 1 votes

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


# Question
Title: Is there a Drupal.org issue queues module? Which module does Drupal.org use?
Does Drupal.org use a module for its project issues tracking? I would like to implement it on our D7 site.

Does this exist as a module or is this something proprietary to drupal.org? If it is not a module, what is the closest I can get for Drupal 7?

# Answer
The Project project, and Project issue tracker project, together make up most of the functionality that you are looking for. Since you ask about D7, it's worth noting that the modules are currently under upgrade to D7.

Project:

> Projects are generally assumed to represent software that has source code, releases, and so on.

Project issue tracker:

> It allows users to submit issues (bug reports, feature requests, tasks, etc) and enables teams to track their progress.
> 5 votes

---
Tags: 7, community-official-site
---


# Question
Title: FacebookforDrupal Publish to stream isnt working?
I am trying to publish a node onto facebook. Below is my code. In hook\_nodeapi(), I have placed a dpm("test") but it isnt showing. I am assuming that this function is not called at all?

```
function fb_stream_ext_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  dpm("test");
  if ($op == 'insert' || $op == 'update') {
    if (isset($node->stream_publish) && $node->stream_publish) {
      $attachment = array(
        'name' => $node->title,
        'href' => url('node/' . $node->nid, array('absolute' => TRUE)),
        'description' => filter_xss($node->teaser, array()),
      );

      /*
        if ($picture = $GLOBALS['user']->picture) {
        $url = url($picture, array('absolute' => TRUE));
        $attachment['media'][] = array(
        'type' => 'image',
        'src' => $url,
        'href' => $url,
        );
        }
      */
      if ($logo_path = theme_get_setting('logo_path')) {
        $url = url($logo_path, array('absolute' => TRUE));
        //dpm($logo_path, "logo_path is $logo_path and url is $url");
        $attachment['media'][] = array(
          'type' => 'image',
          'src' => $url,
          'href' => $url,
        );
      }

      $user_message = t('Check out my latest post on !site...',
                        array('!site' => variable_get('site_name', t('my Drupal for Facebook powered site'))));
      $actions = array();
      $actions[] = array(
        'text' => t('Read More'),
        'href' => url('node/' . $node->nid, array('absolute' => TRUE)),
      );
      fb_stream_publish_dialog(array('message' => $user_message,
                                     'attachment' => $attachment,
                                     'action_links' => $actions,
                               ));
    }
  }

  // Another way to add like button, as part of a node.
  if ($op == 'view' && variable_get('fb_stream_ext_nodeapi_add_like', FALSE)) {
    $url = fb_scrub_urls(url('node/' . $node->nid, array('absolute' => TRUE)));
    $node->content['dff_like'] = array(
      '#value' => "<fb:like href={$url}></fb:like>",
      '#type' => 'markup',
      '#prefix' => '<div class="dff_like_wrapper">',
      '#suffix' => '</div>',
    );
  }
}

```

Any known solution for this?

# Answer
I found the solution myself:

Yes, DrupalForFacebook is out of date. as Dave states here

hook\_nodeapi() is a drupal 6 function, not a drupal 7 function.

The solution is simple: to find a hook function that can replace \_nodeapi.

This function does the exact same thing as hook\_nodeapi().

If one changes

> yourHook\_nodeapi

to

> yourHook\_node\_presave($node)

problem is solved.

Thank you for all the help given.
> 0 votes

# Answer
Sorry, there is no hook\_nodeapi() for D7. In D7, there are seperate hooks for create, update, view and delete operations. You could use this Link as a reference. You could insert your dpm("test"); inside hook\_view() to test it.
> 0 votes

---
Tags: 7, social-network, nodes
---


# Question
Title: How to use nested select queries in Drupal 7
How can I write the following query in a Drupal-friendly way?

```
select max(cnt) from
(select COUNT(*) as cnt from Det a,
dbo.Mem b where a.no=b.no
group by b.no) X
go

```

# Answer
> 3 votes
Since you're going cross-database I think using `db_select()` could get quite complicated. I might be wrong though, it might just work.

Either way, you could always just run the query directly with `db_query()`:

```
$sql = '
  select max(cnt) from
  (select COUNT(*) as cnt from Det a,
  dbo.Mem b where a.no=b.no
  group by b.no)';

$count = db_query($sql)->fetchField();

```

---
Tags: database
---


title: Custom node color from role

text:
# Question
Title: Custom node color from role
How to create custom node background color from role id
e.g. admin - **red**
manager -**green**
auth user - **blue**, automatically?

Find examples (template.php)

```
function themename_preprocess_node($variables) {
  $account = user_load($variables['user']->uid);
  //$account = user_load(array('uid' => $node->uid));
  $user_roles = $account->roles;
  if (in_array('administrator', $user_roles)) {
    $my_class = 'user-admin';
  }
  elseif (in_array('authenticated user', $user_roles)) {
    $my_class = 'user-author';
  }
  elseif (in_array('test user remove', $user_roles)) {
    $my_class = 'user-power-author';
  }
  elseif (in_array('VIP', $user_roles)) {
    $my_class = 'vip-author';
  }
  if (isset($my_class)) {
    $variables['attributes_array']['class'][] = $my_class;
  }
}

```

This doesn't work

# Answer
**UPDATE** From the code you've added it looks like you want to add the class based on the node author. You can use much the same principle:

```
function MYTHEME_preprocess_node(&$vars) {
  $account = user_load($vars['node']->uid);

  foreach ($account->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

```

Each node will have the `role-rolename` classes added to it (see original answer below).

**ORIGINAL ANSWER**

Quick and easy way:

```
function MYTHEME_preprocess_html(&$vars) {
  global $user;

  // Loop over the user's roles and add a class to the body class array.
  foreach ($user->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

```

That adds classes like `role-administrator` and `role-authenticated-user` (and any other roles the user has) to the `<body>` tag. From there you should be able to target things easily with CSS (e.g. `body.role-manager{background:red}`).

Remember to clear Drupal's caches after you've added the preprocess function, or the changes won't get picked up.
> 1 votes

---
Tags: 7, nodes
---


title: Change value of a button in a form

text:
# Question
Title: Change value of a button in a form
I'm using an eCommerce module. In a 'view cart' node, there is a 'remove' button so users can remove items they no longer wish to purchase, however, instead of the 'remove' value on each button, I'd like to have a simple icon and no text, how would I go about making this change? I understand it would probably be a form alter function in the template.php file, but I'm not sure how to set it up.

# Answer
Yes, you can done it in form\_alter . first need to know what is your button name in $form in form\_alter, I suggest you `print_r` or `var_dump` `$form` and found your button (buttons usually are in `#actions`) . after it I suggest you handle your job with add a `css class or id` to your button and with css style it .

```
function yourcustom_form_alter(&$form,$form_state) {
  $form['actions]['yourbuttonname']['#value'] ='';
   $form['actions]['yourbuttonname']['#attributes'] =array('class'=>array('yourcssclass'));
}

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Changing a template using user role and publishing variables
I've been trying to get the following function to work in Drupal 7, where an unauthenticated user sees a different article template (in this case, node--article2.tpl) than a user that's logged in. I get no php errors, but the template doesn't change if I'm logged out. What am I doing wrong here?

```
<?php
   function mytheme_preprocess_node(&$variables) {
   $node = $variables['node'];

   if($node->type === 'article'){
   global $user;
   if($user->uid == 0){
   $variables['template_file'] = 'node__article2';
  }
 }
}

```

Additionally, I'd like the function to look at an article's published state as well. We're using the custom publishing options module that adds a publishing state of "archived."

So basically unauthenticated users will get a different template that has a publishing state of archived.

# Answer
change code

> $variables\['template\_file'\] = 'node\__article2';

to

> $variables\['theme\_hook\_suggestions'\]\[\] = 'node\__article2';
> 0 votes

---
Tags: 7, theming
---


title: Drupal Commerce Rules & Custom Actions

text:
# Question
Title: Drupal Commerce Rules & Custom Actions
When the checkout process is complete I'd like to record the SKU and the user ID in a separate table in my database.

Is the best approach to use the Rules module, using the 'Completing the checkout process' event and writing a custom action?

If so, how would I be best going about this?

Advice on how best to achieve the above would be appreciated.

# Answer
> 4 votes
I don't know of any modules that enable you to write db records in rules actions.

I guess you could write a custom rules action to write to your custom table and grab all the data in rules but it's just as easy to do something like below using hook\_commerce\_checkout\_complete:

*The trickiest part is obtaining the SKU*

```
<?php
  function hook_commerce_checkout_complete($order) {
    $ow = entity_metadata_wrapper('commerce_order', $order);

    foreach ($ow->commerce_line_items as $line_item) {
     $sku = $line_item->commerce_product->sku->value();

     $record = array(
      'uid' => $uid,
      'order_id' => $order->order_id,
      'order_numer' => $order->order_number,
      'sku' => $sku,
     );
     drupal_write_record('my_custom_table', $record);
    }
  }
?>

```

Hope this helps.

---
Tags: commerce, rules, actions
---


title: How to display tokens on a page in D7

text:
# Question
Title: How to display tokens on a page in D7
Drupal 7 built tokens into core. Is there a way to display tokens on a page without modifying a template?

# Answer
Token Filter does the trick. After the module is enabled, you can edit or create create a text format that replaces tokens with text: admin/config/content/formats
> 0 votes

---
Tags: tokens
---


title: Adding custom content to $form

text:
# Question
Title: Adding custom content to $form
I have a page that is displaying a form, and I want to add some text to the top of it.

I create my own module for the form, and have it set up like this:

```
function hook_menu(){
  $items['page'] = array(
    'page callback' => 'form_function',
  );
}

function form_function() {
  $form = drupal_get_form('return_form');
  return $form;
}

function return_form(...){
  $form['element'] = ...
    .. ;
}

```

I want to add onto this form with a paragraph or two to go above the form. I looked at the form api for something i could use from '#type' but I found nothing. Any suggestions are welcome.

# Answer
> 0 votes
you could try using hook\_form\_alter()

For e.g.

```
<?php
function your_module_name_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    //First element in the form.
     $form['element']['#prefix'] = '<div>Your paragraph before the form.</div>'
  }
}
?>

```

---
Tags: 7, forms
---


# Question
Title: How to import content for content types with user-defined fields
I've got a large amount of data I would like to turn into pages in Drupal. Most of the data to import correspond to custom fields I created in a new content type (let's call it *directory*).

For example, I have things like zip code, address, state, etc. that I would like to import as *directory* content.

I've been working with the feeds module, but so far I haven't been able to figure out if it can map to custom fields in a content type (I'm beginning to suspect that it cannot).

I'm using Drupal 7

# Answer
> 0 votes
Feeds just needed a bit of time to add the required functionality.

# Answer
> 1 votes
I suggest you look into migrate module. This module is very flexible, very well documented and can easily handle and ease the pains of content migration. Custom content, users, comments, etc .. and just about whatever you throw at it can be set up as 'migration tasks'.

Good-luck!

---
Tags: 7, feeds, importing-exporting
---


title: Views Sort by Taxonomy with headers

text:
# Question
Title: Views Sort by Taxonomy with headers
I have a bunch of nodes that are of the type expert. Expert nodes have a flexible sized list of expertise categories. So an expert would be a person, (Patrick McDougle, Patricia O'Connor …) and a expertise category would be (Autism, Aging, Bulimia …) Using Views 3 and Drupal 7 I would like to end up with something like this:

**Aging**
Patricia O'Connor

**Autism**
Patrick McDougle
Patricia O'Connor

**Bulimia**
Patrick McDougle
...

Is there a way to do this, without having to create my own views template?

# Answer
The trick is to add a view of taxonomy terms, and then add a relationship to the content. You'll also have to hide some fields and add a grouping field in the unformatted list settings. Details are below.

* Create a new view that shows "Taxonomy terms" of type "expert \[vocabulary\]" sorted by Unsorted
* Continue and edit
* Add a relationship under Advanced \> Relationships
* Choose "Taxonomy term: Content with term" (Relate all content tagged with a term) & apply to all displays
* You'll now be able to add a field and the content will show up. Click add next to Fields and select the Content Title or whichever field the name is stored at.
* Uncheck "Create a Label" and apply.
* Click on Format \> Settings, and select "Taxonomy term: Name" in the "Grouping field Nr.1" dropdown, and click Apply. This will create a heading of the taxonomy term.
* Hide the taxonomy terms from showing up extra times by clicking on the "Taxonomy term: Name" field, and click "Exclude from display."
* Uncheck "Link this field to its taxonomy term page" so that the taxonomy term is not linked to it's page.
* Save the view, and view the page.
> 3 votes

# Answer
You can do this by choosing Table in format, then group by expert category.
> 0 votes

---
Tags: views, theming
---


title: Creating a custom registration page

text:
# Question
Title: Creating a custom registration page
I would like to modify the look of a user registration page that I am creating. It contains content profile fields and a recaptcha area. I have created a user-register.tpl.php file and updated my template.php file so that this template file is recognized.

I would like to pull out the pieces of the registration form and place them with specific divs for styling. The problem I am having is that I cannot get the fields. I have tried using

```
print drupal_render(drupal_get_form('user_register'));

```

but that creates a white page. When I try to just print drupal\_get\_form('user\_register') I get nothing as well. So I am stumped as to what I am doing wrong. It would appear that the drupal\_render command is not returning anything so I can't figure out why that would be.

Here is my modification to my template theme:

```
function mytheme_theme($existing, $type, $theme, $path) {
  return array('user_login'=>array(
    'template'=>'user-login',
    'arguments'=>array(
        'form'=>NULL),
    ),
    'user_pass'=>array(
        'template'=>'user-pass',
        'arguments'=>array(
            'form'=>NULL),
    ),
    'user_register'=>array(
         'template'=>'user-register',
         'arguments'=>array(
            'form'=>NULL),
    ),
  );
}

```

This would seem it should work but it doesn't. It is almost like that form does not exist.

I am using Drupal 6.26. Any help would be appreciated!

Thanks

# Answer
I found what was causing the problem with not being able to display form elements as described above. The issue was this line in my templates file:

```
function mytheme_preprocess_user_register(&$variables) {

   $variables['intro_text'] = t('some text.');
   $variables['rendered'] = drupal_render($variables['form']);
}

```

It looks as though you can only call drupal\_render once. Any subsequent calls to drupal\_render are ignored as Drupal as already marked the code as rendered. There should be a way to force a re-render if necessary or be able to get the already rendered results. If someone knows how to do this please reply to this post.

The solution was to remove this line from the templates.php file and everything worked.
> 0 votes

---
Tags: forms, users, 6
---


# Question
Title: How to offer Views as options in a Content-Type field
I would like to add a field to a content type (Events) that gives several views (Certificates of Completion) as options. Thus, when creating an Event the admin can select which certificate will be associated with this Event.

I'm hoping there is a module for this, but as you might imagine Google can't figure out exactly what I'm asking when my query is predominantly filled with generic drupal terms like "Content Type", "Field", and "Views".

Any recommendations will be greatly appreciated.

# Answer
You could create a taxonomy for that content type and assign values to it like "Certificates of Completion", etc. Here is the Link for the taxonomy docs.
> 0 votes

# Answer
The closer module I can think of is the View reference module.

> Defines a field type View reference which creates a relationship to a Views display and allows the view to be displayed as the content of the field.
>
> This module is modeled on the Node reference module, and usage is similar.
>
> Additionally, you may enter arguments for each view by a delimiter separated list with support for PHP generated arguments.
> 0 votes

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


title: Integrate solr search with og group

text:
# Question
Title: Integrate solr search with og group
I search the method to implement apache solr search with og group and search on the content associated with group.

I want that the user can search the content of a specific group or for all group.

Thank

# Answer
If you want to integrate SOLR with Organic groups, you can use the Apache Solr Organic Groups Integration module but it is in dev mode.

Also, while searching, you can filter data, and alter queries as required.
> 1 votes

---
Tags: organic-groups, search
---


# Question
Title: ordering profile 2 module profile type tabs
i am using profile2 module, i create some profile types, but in profile section in admin/structure/profiles i can't ordering them,is this profile default or this is only my problem? i means if i add another `profile type` it just come below of anothers and any feature to ordering them

can i ordering them in `form_alter`?

```
function hook_form_alter($form,$form_state){
   change order of theme here ??? how
 }

```

# Answer
> 0 votes
Yes, by default profile2 module not cosidered any ordering of it's profile types. if you want to change default ordering of them you have some solution. create a `template file` for `user_profile` . Another way is ordering them with form alter in your custom module

```
function hook_form_alter(&$form,$form_state) {
 if ($form_id == 'user_profile_form') {
     // do this for all your profile types
     $form['profile_yourprofiletype']['#weight'] = 'your optional order';
   }
 }

```

---
Tags: users
---


title: Add field to vocabulary itself

text:
# Question
Title: Add field to vocabulary itself
I have a situation where I would like to add a field to a vocabulary itself. In other words, I need an editable field on the form that normally appears at `/admin/structure/taxonomy/my_vocabulary/edit` and not a field that appears each term in the vocabulary. Unfortunately, the `description` column in `{taxonomy_vocabulary}` is too limited for what I need.

What is the best way to go about this? If possible I would like to avoid making a custom module with a custom table, form-alters for the vocabulary edit page, etc.

Thanks.

# Answer
> 6 votes
So the basic problem is that a vocabulary is not fieldable. In theory this is easy to fix, but I don't know if they lack this functionality because it would cause technical difficulties, or to avoid confusion users.

To make a vocabulary fieldable, implement hook\_entity\_info\_alter:

```
function hook_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_vocabulary']['fieldable'] = TRUE;
}

```

# Answer
> 6 votes
You can use the Fieldable vocabularies module.

> This module exposes the Vocabulary to the field system. It defines a single bundle and a single view mode.

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


title: How to hide or keep away /node

text:
# Question
Title: How to hide or keep away /node
I want to avoid the URL pointing to a node on my site contains the "node" part (e.g. http://example.com/node/1). Is it possible?

# Answer
You need the Path module for URL aliases. (It is a Drupal core module.)

Once the module is enabled, you can edit a node, and set a path alias for the node. Now, you can access your node through the path alias you just created.
Drupal will use the path alias you set as URL for the node, except for sub-paths (e.g. node/1/edit).
> 2 votes

# Answer
The best way is using Pathauto module. It's suitable for your work.

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 1 votes

# Answer
You can use the Path module for the URL alias, and for every pages use a path alias.
> 0 votes

---
Tags: nodes, uri
---


title: Using profile2 help

text:
# Question
Title: Using profile2 help
I am using the profile2 module and have three different types of registration forms. I am wondering should certain categories be stored in the main profile which is a profile type already constructed by the profile2 module. The fields I was considering putting in main are the name and location of the user and there profile picture. One user profile is for students and another profile is for teachers. I was wondering for the registration form if I should store the name and address details in the main profile and then the more specific details about the student in the student profile and the same format for the teacher profile. I was just wondering which method is more efficient for the drupal database. If I put the location and name in the student profile and the location and name in the teacher profile wouldn't this be duplicates of the fields first and surname and the address. Does this clear things up. I can provide further details if you require them.

# Answer
I would suggest you have the least amount of profiles required, if you can fit all the fields naturally into the main profile do that. If however you have a large number of fields which warrant another profile, add another for each group of fields which would make sense to bunch together.

For example, if you were building a jobs site... you would have all your account settings for the website in the Account profile like username, email, password. Then create another tab for Education, another for experience etc?

Really it is hard to provide more details on best practice because profiles can have quite a wide scope depending on your specific requirements
> 1 votes

---
Tags: 7, users
---


# Question
Title: What is the best way to put comments section to user profile
I need add ability to add comment for user profile. What i am thinking is, create a content type with empty body and leave just comments, and afterwards insert that node to user\_profile. But i don't know how to append comments to user profile tpl file. How to do this, or maybe other suggestions?

> After some research i decided to make my own module to add comments on user profile, i will make a block and insert this block to only user page *user/*\*, and will track user id to show proper comments.

# Answer
If you use Profile2, this creates profiles as node type entities so you can turn comments on as each profile will have settings similar to that when you create content types.
> 2 votes

# Answer
If you want add comment to profile in template files, do you think how you want realate those with eachothers?
I suggest you using modules like commentfield . install and add a comment field in your profile type.

Your right, please look at this issue and this
> 1 votes

---
Tags: users, comments
---


# Question
Title: Show field collection fields with profile field
I have used Recruiter module to manage job and resume and its working almost well but when i m displaying resumes it has field collection like Personal information which contain some field like name, address etc. and some normal fields. Now i want to show all of them in table.I tried field collection views but its showing all field collection data in single column called personal information with other fields.

Please let me know how i can do this....really struggling in drupal.

# Answer
> 2 votes
If I'm reading it correctly, you should be able to create a relationship based on your Field Collection field.

Under Advanced (this might be collapsed in the Views UI - it normally is by default) click relationship, and then click on the Field Collection field containing your user information.

Now you'll find when you go to add a field into your Views display, that there are more fields available to you. These are the fields stored in the Field Collection entity that you can now style in a table, an accordion, a list...whatever you fancy!

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


# Question
Title: How to create file field instance that allow teaser and full description and not allowed extensions but denied extensions?
I need to change the default Drupal functionality of file field:

* I want to be able to allow upload of all files types, EXCEPT the extensions listed (reversing the current funcitonality)
* I also want to be able to add a teaser field and a description field to the file.

Any ideas?

# Answer
The second part of your question is easy with the File Entity module - it turns file uploads into fieldable entities, so adding your teaser/description field is just like adding a field anywhere else in Drupal (make you sure you read the README file - it's not overly clear at first). The module is also on an unstable release, but Dave Reid is pretty damn awesome so I can't imagine it'll be that way for long :-)

Off the top of my head, I can't think of an answer to the first part though I'm afraid.

**EDIT**

There's an issue here that has a couple of patches for Core that give you a radio box to either *Allow only these file types* or *Allow everything EXCEPT these file types*. I've not tested the patches as I don't really want to patch Core for something that I personally don't need, but definitely give it a read!
> 1 votes

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


title: drupal commerce customization

text:
# Question
Title: drupal commerce customization
I'm trying to build a site for registering educational classes...(sell them)

I want to use Drupal commerce, and add some properties like time,teacher etc. but I want to add some things:

every class has specific capacity. I want users to first, register, then if someone wanted to register, register something like reserved...meanwhile,if sb cancelled order, the reserved people would be registered, after all, we approve the people, no matter registered or reserved, then they can pay....

another thing is that I want that products expire after a while, for example until the tomorrow registration(buying) is allowed.

Is it possible to do these with commerce or Drupal?

# Answer
I didn't get the first part. About the expiring date you can use Scheduler.

You can decide when you want to unpublish or publish some content (Product display in your case).
> 1 votes

---
Tags: commerce, rules, users, datetime
---