# Question
Title: How to Associate Page Title with Author as Variable or Token or Relationship
I have created a custom content type for each of several contributing users for multi-blog purposes. I then used Views to create a page for each content type and thus a "blog home page" for each user. I have also modified my theme's node.tpl.php file to reflect the custom look I want for displaying the teasers for all the custom content that is created.

The current header portion of my node.tpl.php file:

```
<?php if (!$page): ?>
  <header>
<?php endif; ?>
<span class="uppercase">
  <span class="blog_title"></span>
  <span class="post_date"><? print " | "; ?></span><? print render($date); ?></span>
</span>
<?php print render($title_prefix); ?>
<?php if (!$page): ?>
  <h2 class="title" <?php print $title_attributes; ?>>
    <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
  </h2>
<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($display_submitted): ?>
  <span class="submitted">By
    <span class="uppercase"><?php print $submitted; ?></span>
  </span>
<?php endif; ?>
<?php if (!$page): ?>
  </header>
<?php endif; ?>

```

I can display the custom content title with $title, the date it was submitted by $date and the author by $submitted. What I would like to include is the title/link to the page (that was created by the view of the custom content type associated with the author).

Is this something I can use relationships for to somehow generate a token and/or variable?

I don't really have any idea about how to approach this; any ideas or advice are much appreciate... thanks!

# Answer
> 0 votes
1. In your theme template.php file add preprocess\_node as below.
2. The below code will grab the author of current node for your custom content type.
3. And $node\_author will be available to user on node.tpl.php
4. With the help of $node\_author you can make the link

```
//
//Override or insert variables into the node template.
//
function MYTHEME_preprocess_node(&$variables) {
  //dpm($variables);
  if($variables['type'] == 'my_custom_content_type') {
    $node_author = $variables['uid'];
    $variables['home_page'] = $node_author;
  }
}

```
5. In your views add contextual filter for author uid to grab from url.
6. This should work for you.

---
Tags: views, tokens
---


# Question
Title: Is there a module for "mail routing" in Drupal 6?
Is there a module, with D6 support, that allows one to "route" e-mails.

For example, by default, e-mails would be sent out by the regular mechanism, but for some e-mails, say based on their ID or destination domain, where tracking is interesting, they could instead be passed of to a third party service (such as MailChimp, ExactTarget, MailGun etc).

# Answer
> 0 votes
You could try: https://drupal.org/project/reroute\_email While it's mainly designed to reroute all email to predefined addresses, e.g during development, you could use it as a starting point for similar functionality.

---
Tags: emails
---


# Question
Title: How to cancel multiple user accounts and keep their content without using built-in admin GUI?
How do I cancel/delete multiple user accounts without deleting content created by those users and without using the built-in admin GUI?

Ideally if there was a way via VBO or rules or any related modules that would be awesome.

# Answer
> 0 votes
You can check out some of these things. Please test this before using it on your real build.

Delete All module

> > This module is used to delete all content and/or users from a site. This is mainly a developer tool, which can come in handy in several cases, listed below.
>
> The usual way to do this is to go to Administer -\> Content then select all the nodes and delete them. This works if you have a handful of nodes only. If you have hundreds or thousands of nodes, then it is not a practical solution.
>
> Another option is to directly delete the nodes from the node table in the database. This does not work properly, since there are also comments, and many tables for add on modules that needs to be cleaned.
>
> This is a test site that the client was using for a period of time, and they must clean it up before starting with real data. You are testing something that creates a lot of nodes (e.g. aggregator), and want to do it over and over again. You created a site in the past and want to replicate it again, but with new content. Note that for nodes, comments and all additions to nodes that contributed modules may have added. For users, any additional module data will also be deleted.

but you can also use Drush and this command `drush delete-all users`

---
Tags: users, rules, views
---


# Question
Title: Creating a form where users can edit their own submissions
I'm beginning with Drupal. I've got to set up a multistep form which allows users to add content. I want them to be able to edit their own submissions too.

I began to code a custom module in drupal/php but I'm not sure it's the easiest way. I've heard a lot about Drupal native forms or content types that could do it as well as a custom module.

My question is : what kind of modules do I need to build a multistep form with own submissions edition ?

# Answer
In the Home » Administration » Structure and in the content type add new content type and create your forms as you need

You can edit every content type i.e. node and for editing own submissions you can set appropriate permissions like 'edit own content' in the Home » Administration » People under permissions tab

For multistep forms you can in the hook\_form\_alter() create

$form\['redirect'\] = 'your\_next\_form\_path';

By using redirect as soon as the form is submitted you will be redirected to other form (only thing is proper path for node or form needs to be mentioned).
> 0 votes

---
Tags: 7, forms, nodes, users
---


title: Create link with node id parameter

text:
# Question
Title: Create link with node id parameter
When I create a new content type, I want to prefill a link field following this format :

```
/my/specific/link?node_id=<CURRENT_NODE_ID>

```

Is it possible to access the node id before his creation? Or a specific id to refer to this new content type??

\[EDIT\]

More details : I want to add a content type, which is a job offer. In this content type, there is a Link field, that refer to a web form to apply to the job offer. So I need to prefill the link field, with the node ID to know the job you are applying for.

# Answer
> 1 votes
You do not need a link field for that. You can generate link at theme level for example. Or even better in `hook_node_view`:

> The module may add elements to `$node->content` prior to rendering. This hook will be called after `hook_view()`. The structure of `$node->content` is a renderable array as expected by `drupal_render()`.

Last but not least, if you really want it to be a field, use Computed Field and have it calculated at save.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.

---
Tags: nodes
---


# Question
Title: Alter views style using regenerate feature?
I created a views using feature and export the views in my second site. After some time I need to change in views style. After change in style I regenerate the feature and export again.

I disabled the previous version and enable this version. The changes in fields are altered but changes of styles plugin are not altered. I cleared the cache and also uninstalled and installed again, but it didn't work at all.

Anyone used feature module like this? Am I missing something?

# Answer
You do not need to enable / disable features on prod server after uploading the new files

First, on your prod site clear all the caches

Then go on the view's page `admin/structure/views` click on the dropdown list beside your view, you should have an operation 'revert' : that's it

If you dont have 'revert' operation, (and disable is present) it means the views is up to date with your feature's file

Of course, the start point is to re-export your feature's files from your local site and upload them to your server (do not export/import your view, the code must be in the feature's files)
> 1 votes

---
Tags: 7, features
---


# Question
Title: user login form: name and password default values
Currently, when the user is loggged out, on user login form, the username field is filled with text, which probably is taken from a cookie (not sure) - it is the name of someone who logged in before. The password is also filled with dots, representing previously logged in password.

How to prevent it, i.e. always display username and password fields empty?

P.S. Why I need this? Because the requirement is that in the user name box there is a placeholder behavior with text "Username". (HTML5 placeholder). I noticed that it works well when the browser has no username remembered and does not work at all when the browser remembers the username and password.

# Answer
Clear your browser cache, and make sure you don't have any accounts set to be "Remembered".
> 0 votes

# Answer
Usually, it's the browser that remembers login names and passwords, allthough some sites place a cookie upon successful login that they use to populate the username field on your next visit.

I don't think Drupal does this by default so I think in your case, it's the browser that remembers the login name and password.

There is one way to avoid this and that's by changing the name of the form fields. Browsers 'know' to remember usernames because the name of those fields is usually something like 'user', 'username' or 'login'.

If you change the name attrribute of the login input field to, say, 'bycicle', browsers will stop remembering those values automatically.
> 2 votes

# Answer
Set Autocomplete=off at both username and password input fields.

```
ex: <input type=text id=uname Autocomplete=off>
    <input type=password id=pword Autocomplete=off>

```
> 0 votes

---
Tags: 7, forms, users
---


# Question
Title: How to get 'add more items' / multiple fields working when creating a custom content type's create/edit input form using templates and theming (D7)?
For *single instances of each field*, I've successfully followed arajashe's excellent answer for controlling what input fields get displayed in the content type's create/edit form here: https://drupal.stackexchange.com/a/68975/1082 \- an answer to question: How do you theme a content type's create/edit form in Drupal 7?

But what about fields where you can add more, where you specify in the settings that more than 1 of a field can be added, or even unlimited.

In this case, the above answer does not work. When I click the 'add more items' button for such fields, in my custom form, the new field does not display. Given that I have already displayed the first instance of the field, I would expect the markup output to include a place holder for contain the new input field that would be inserted as a result of clicking the button.

I've started to debug the code involved - 2 screenshots

The first is in `field.form.inc` and shows the ajax call back code - the code that is called when the `add more items` button is pressed. This does the job of inserting the markup for the new instance of the field input. For some reason (which is why I'm asking this question), the markup for the second field is not being inserted alongside the first field by this function, when I use a custom template.

The second screenshot shows 2 fields of the same type and the markup that generates them. This is when no custom template is being used - i.e. the default, out-of-the-box input form for add content type that comes with Drupal.

# Answer
The successful answer I found would be **not** to build the form from scratch as described in: https://drupal.stackexchange.com/a/68975/1082

But instead to use the standard default content type entry form and to customise it to only show certain fields, using the php `unset` function to hide the input fields that you don't want to be displayed (provided they are non-mandatory of course).

In theme code, `template.php`

```
function theme_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'machine_name_of_your_form')
  {
    unset( $form['field_email'] );
  }
}

```

The benefit of this approach is that you start with a *working form* and take things off that you don't need.

Contrast that with building a custom form from scratch which doesn't have that guarantee of working - well I found this anyway - as it seemed that even though here I included the essentials, things like multiple field handling didn't work and the submit didn't work either.

So starting with the complete form and tweaking worked for me.

**Update**

An approach better than `unset` (and in fact is the official Drupal approach), is to use the `#access` property on form fields to hide them. For example, in `your-theme_hook_alter` function (`hook_form_alter`) in your theme's `template.php` you would do:

```
$form['field_email']['#access'] = false;

```

More details here: http://themery.com/dgd7/advanced-theming/forms/with-templates (which is an excerpt from THE DEFINITIVE GUIDE TO DRUPAL 7 ebook and paper-based physical book from apress - see http://dgd7.org/ and http://apress.com)
> 1 votes

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


# Question
Title: How to allow filtering by only date parts selected by user and make not selected work as "Any"?
I am using the Date module and I am creating a view to display news content; I made a exposed filter to search news content by year, month, and day. When I search, I need to select all the date fields.

Is it possible to search entering values for just one of those fields?

How can I remove these validation in search time?

How can I remove this validation from exposed search filters ? I want to search content condition should like this:- **Year "OR" Month "OR" Day**

condition should not like this:- **Year "AND" Month "AND" Day**

# Answer
It **validated**, because by default it set to **AND operator** in your exposed setting. You can do it easily, but I have done it in Drupal 6, I don't have D7 setup. Check the below screenshots. Just select the **Method as OR** in the exposed filter setting.

Click the **setting icon** and then select the **OR** under method.
> 1 votes

---
Tags: views, datetime
---


title: APC caching with Drupal

text:
# Question
Title: APC caching with Drupal
I am confused how APC caching hooks into Drupal system or vice-versa.What I knew so far is APC caches the opcodes for the currently being executing PHP file so next time the various compilation steps can be avoided and then opcodes are served directly from RAM. Since a Drupal page is built with various functional blocks like blocks, node, I am not getting how APC helps it serving fast.I know it does but how?

# Answer
> 2 votes
APC is PHP's op code cache. If you enable it then it works for any PHP code. All of your Joomla/Wordpress or Drupal sites will execute faster provided you have high value of Hit/Miss ratio( or increase APC RAM if it's less).

If you want further optimization then Drupal can use APC for caching( instead of storing in mysql tables) using Drupal's APC module. I'm not sure about this sentence though.

I too was confused in the same way :)

---
Tags: caching
---


# Question
Title: Webform validate 18 years old (GNU Date Input Format)
I'm looking for a **valid** date pattern, to validate a user's birthday (`component date`).

I want to make sure the person is 18 years of age or older. However, Drupal requires the GNU Date Input Format.

**This seems not to work** \- Drupal shows no error message at all ?

There is also a related answer Field Validation: 18 Years or Older, but this seems to be super complicated and does not affect the module.

# Answer
> 0 votes
**Here's the solution for this annoying "feature":**

---
Tags: 6, webforms, datetime, forms
---


# Question
Title: How to hook into fivestar_ajax_submit function?
I have to add custom HTML element for rate stars and I tried to this with alter fivestar\_custom\_widget form and set:

```
$form['actions']['submit']['#ajax']['callback'] = 'MODULE_fivestar_ajax_submit';

```

I created MODULE\_fivestar\_ajax\_submit function where I call original fivestar\_ajax\_submit. My problem is that I can't instruct $form to use my function in place of original code.

-- edit --

In MYMODULE\_form\_alter() I'v got:

```
if ($form_id == 'fivestar_custom_widget') {
    $arg0 = arg(0);
    $arg1 = arg(1);
    if ($arg0 == 'node' && !empty($arg1) && ctype_digit($arg1)) {
        $node = node_load($arg1);
        $form['votes_counter'] = array(
            '#markup' => '<div class="votes-countes">' . format_plural($node->field_rating[LANGUAGE_NONE][0]['count'], '1 vote', '@count votes') . '</div>'
        );
        $form['#submit'] = array(
            'MYMODULE_fivestar_form_submit'
        );

        $form['actions']['submit']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
        $form['#submit'] = array('MYMODULE_fivestar_ajax_submit');
    }
}

```

and submit function:

```
function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);
    $result['#commands']['data'] .= format_plural(100, '1 vote', '@count votes');
    return $result;
}

```

# Answer
My friend helped me with this solution:

```
function MYMODULE_element_info_alter(&$info) {
    $info['fivestar']['#process'][] = 'MYMODULE_fivestar_process';
}

function MYMODULE_fivestar_process($element) {
    $element['vote']['#ajax']['callback'] = 'MYMODULE_fivestar_ajax_submit';
    return $element;
}

function MYMODULE_fivestar_ajax_submit($form, $form_state) {
    $result = fivestar_ajax_submit($form, $form_state);

    $type = $form_state['build_info']['args'][1]['content_type'];
    $id = $form_state['build_info']['args'][1]['content_id'];
    $votes = fivestar_get_votes($type, $id, 'vote', $GLOBALS['user']->uid);

    $result['#commands'][] = array(
        'command' => 'insert',
        'method' => 'replaceWith',
        'selector' => 'span.vote-count',
        'data' => '<span class="vote-count">' . format_plural($votes['count']['value'], '1 vote', '@count votes') . '</span>',
        'effect' => 'fade'
    );
    return $result;
}

```

This code adds and change votes counter displayed after fivestar voting widget.
> 0 votes

---
Tags: ajax, forms, rating
---


title: Cannot access $node on Computed field

text:
# Question
Title: Cannot access $node on Computed field
I'm using computed field for my content types, but when I used $node, in Display Code, it doesn't display anything :

```
global $node;
$display_output = l("Apply", "apply_form?job_offer=".$node->nid);

```

# Answer
First of all, you are supposed to write to `$entity_field[0]['value']`. Second problem is that fields operate on entities, not nodes, so you need to use `$entity` instead. You can always use Devel module and `dpr($entity)` to see what's in it.

`node id` should be in the entity field if it is a node. In which case you can load it with `node_load()`.
> 0 votes

---
Tags: nodes, entities
---


title: populate checkbox value in text area

text:
# Question
Title: populate checkbox value in text area
I am a drupal newbie and am having the following problem:

In my custom content type page, I have multiple check boxes and a text area, among other fields. What I want is that, I would like the values of the checked check-boxes to be pasted inside the text area. The checkboxes are created as a multi-value field (field type = list, widget = check-box). Basically what I want is, every time the user checks/unchecks one of the checkboxes, the text area should re-populate with values of all the checkboxes that are currently selected.

I tried using the dependency fields module, but it did not solve my problem. Have anyone encountered this need before?

Based on what I read, it seems this might be possible using hook\_node\_presave, however I am not sure where to add this. I am using a template called norma, so I edited its template.php and added a function like so:

```
function norma_node_presave($node)
{
 print_r($node);
 exit;
}

```

However, nothing has happened... :(

Any pointers on how to solve this is very much appreciated...

# Answer
`hook_node_presave($node)` should be included in a custom module and not in your theme !

Look at Creating Drupal 7.x modules if you want to try so.

In your hook do something like that :

```
function norma_node_presave($node){

  $value = array();
  foreach( $node->field_checkbox['und'] as $checkbox){
    $value[] = $checkbox['value'];
  }

  $node->field_textfield['und'][0]['value'] = implode('<br>', $value);
}

```
> 3 votes

# Answer
The best idea would be to use Javascript (so that as you check the checkbox the field value changes), you can do something like this.

```
$(document).ready(function() {
    $('#checkbox1').change(function() {
        $('.field1').val($(this).val());
    });
});

```

Or something like that, I can't guarantee that code works but it should get you started.
> 0 votes

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


# Question
Title: Drupal 7 - Profiles 2 Module - Share profile data or migration
I'm making a platform for 2 types of users:free and paid.

The issue I encounter is the data of the users when updating from one profile to another.

If the user has "free" profile he gets some fields, but when updating the "paid" profile has the same fields+extra.

I first thought of showing the "paid" fields as an extra to the "free" (so the users with "paid" profile have both "free" and "paid" profiles assigned to them), but the issue appears when the user wants to create the profile directly paid as he has no option completing the "free" ones only after he has registered.

Is there any way to make the fields autopopulate (when completing the "field\_1" in "free" the data to apear in "field\_1" in paid)? Or to make the data viewable cross multiple profile types?

Conclusion:I need a way for the data to ve visible cross profiles

# Answer
I think you can use a `hook_form_alter()` to add visibility conditions on your `user_profile_form` elements :

Add these kind of attributes on field you want to hide for free users :

```
'#states' => array(
   'visible' => array(
      ':input[name="field_1"]' => array(
         array('value' => 'paid'),
     ),
   ),
),

```
> 0 votes

---
Tags: users
---


title: How to make a View of role?

text:
# Question
Title: How to make a View of role?
I need to make a page with the list of the roles (I have 10 roles in the site) and the possibilities of changing their name,I tried to use views but was not possible. I want something like the drupal's role page, but just with the modify button. Some ideas?

# Answer
> 0 votes
In views you cannot access to a list of roles, only to the user entity.

I suggest you to get this list of the roles by a drupal function

Try with user\_roles()

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


# Question
Title: How can I use rules to grab fields from one content type to another then delete the old nodes?
I have an D7 site using feeds that create dozens of nodes daily populated with RSS articles. I use the body fields from these articles as well so I can read them on-site without clicking to the actual publisher. Means my database is getting bigger. Here's what I want to do:

Any node over 4 weeks old of 'feed' type needs to create a new node called 'feed archive' and do this by using the old title and just the article URL - no other fields need to be transferred. Then the old node can be deleted. So I basically dump all the body content and other fields attached to the old 'feed' node and just leave the title and URL and create a new node with these two things.

I have created a rule using VBO views before so kind of understand that, but don't know how I say: 'create a new node, only grab these two fields from it, then delete it'

Any help greatly appreciated.

# Answer
> 0 votes
In your rule, i think your can write a custom php code:

```
  //$node is your original node

  $node_new = new stdClass();
  $node_new->type = 'content_type_2';
  $node_new->status = 1;
  $node_new->uid = $node->uid;
  $node_new->title = $node->title;
  $node_new->promote = 0;
  $node_new->created = $node->created;
  $node_new->timestamp = $node->timestamp;
  $node_new->field_article_url = $node->field_article_url;

  node_save( $node_new );
  node_delete( $node );

```

---
Tags: rules, views
---


title: User tabs for anonymous users

text:
# Question
Title: User tabs for anonymous users
The user tabs are:

View

Edit

My content (created with Views with path user/%/track)

Every user can edit his profile with the user tab "Edit". When registered user enters other profile the two tabs "View" and "My content" are available, without "edit" (that's fine), but what about anonymous users?

When I enter from anonymous user into /user/1/track I see the content but without the tabs(View and My content).

How can I make these tabs displayed from anonymous users?

Do I have to use hook\_menu\_alter for this core element?

EDIT:
"View user profiles" is already activated for anonymous users in permissions page and **user/1** and **user/%/track** are accessible for anonymous users, but the tabs are missing.

# Answer
> 0 votes
I found the problem. I forgot that that I've deactivated the .tabs-wrapper with CSS for the anonymous users. hook\_menu\_local\_tasks\_alter and krumo helped me to solve out that the access of the tabs is ok.

# Answer
> 1 votes
This is a permission issue. Simply enable the permission **"View user profiles"** for anonymous users.

---
Tags: users, routes
---


# Question
Title: What arguments can I use when defining a service?
Looking at system.services.yaml, I noticed that some of the services arguments are strings starting with @. They seem to contain a reference to another defined service.

```
system.manager:
class: Drupal\system\SystemManager
arguments: ['@module_handler', '@database', '@entity.manager']

```

Are those @-arguments only references to other services? Are there any other type of arguments I can use when defining a new service?

# Answer
> 5 votes
Yes, the `@` arguments are references to services. From Symfony's Introduction to Parameters:

> You can of course also reference services, which looks a bit different in each format. You can configure the behavior if the referenced service does not exist. By default, an exception is thrown when a non-existent service is referenced.
>
> ### Yaml
>
> Start the string with @ or @? to reference a service in Yaml.
>
> * @mailer references the mailer service. If the service does not exists, an exception will be thrown;
> * @?mailer references the mailer service. If the service does not exists, it will be ignored;

You can also use `%`-wrapped parameters which are slightly different; they can be used to refer parameters or get access to special `SYMFONY__` prefixed server environment vars. (See How to Set External Parameters in the Service Container.)

---
Tags: 8
---


# Question
Title: How to abort the ajax request and redirect in the ajax callback of form element
I want to redirect users in the AJAX callback, but nothing I tried works.

How could I achieve that?

# Answer
> 8 votes
If you've got ctools installed (nearly all Drupal sites do), you can make use of `ctools_ajax_command_redirect()` in your AJAX callback, e.g.

```
ctools_include('ajax');
$commands[] = ctools_ajax_command_redirect('path/to/redirect');
return array('#type' => 'ajax', '#commands' => $commands);

```

---
Tags: forms, ajax
---


# Question
Title: Drupal Commerce: How to validate payment method settings?
The code add settings for commerce\_mymodule (for example) commerce payment module. Can I validate 'mymodule\_deadline' variable and how?

```
/**
 * Payment method callback: settings form.
 */
function commerce_mymodule_settings_form($settings = NULL) {
  $settings = (array) $settings + array(
    'mymodule_min' => '',
    'mymodule_secret' => '',
    'site_mode' => 'DEMO_MODE'
  );

  $form = array();

  $form['mymodule_deadline'] = array(
    '#type' => 'textfield',
    '#title' => t('Order payment deadline'),
    '#description' => t('Deadline for payment - default 7 days (max. 30 days).'),
    '#default_value' => $settings['mymodule_deadline'],
  );

  return $form;
}

```

# Answer
> 2 votes
I found a solution - because it is a FORM I using the FORMAPI. More accurate hook\_form\_alter() to add my custom validation handler and next is trivial. Code:

```
/**
 * Implements hook_form_alter()
 */
function commerce_mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rules_ui_edit_element') {
    if ($form_state['element_settings']['payment_method']['method_id'] == 'commerce_mypaymentmethod') {
      $form['#validate'][] = 'commerce_mypaymentmethod_settings_validate';
    }
  }
}

```

and validation function

```
function commerce_mymodule_settings_validate(&$form, &$form_state) {
  $deadline = (int) $form_state['values']['parameter']['payment_method']['settings']['payment_method']['settings']['mymodule_deadline'];

  if ($deadline < 1 || $deadline > 30) {
    form_set_error('', t('Enter only digit positive value between 1 -30 (days) in Order payment deadline. @value', array('@value' => $deadline)));
  }
}

```

# Answer
> 1 votes
The easiest way to validate an individual form element is to use the #element\_validate property:

```
$form['application_login'] = array(
  '#type' => 'textfield',
  '#title' => t('Application Login'),
  '#default_value' => decrypt($settings['application_login']),
  '#required' => TRUE,
  '#element_validate' => array('_commerce_qbms_element_validate_encrypt'),
);

/**
 * Validates form elements.
 */
function _commerce_qbms_element_validate_encrypt($element, &$form_state, $form) {
  form_set_value($element, encrypt($element['#value']), $form_state);
}

```

In this specific case of validating a Drupal Commerce payment method setting element, the solution provided by @svetlio was not adequate for my needs. This was due to the fact that I needed to encrypt my element's value before sending to the database, and for whatever reason (I suspect the Rules module), this was not possible using his solution.

This is also the solution provided by the creators of Drupal Commerce: https://drupal.org/node/1179626

---
Tags: 7, commerce
---


# Question
Title: Command option to ignore errors during drush dl <list of modules>
Just trying to start creating prefab lists (of modules etc.) and building my site development environment at the moment. I'm trying to call `sudo drush dl (list of modules)` and it works until it can't find one and stops the entire process.

Is there a switch I can use to get drush to continue through the list and perhaps even list the terms which failed to download (not important). I've just seen a sentence alluding to creating your own drush commands, but figured I'd check the community first as that could take a big chunk of scarce time!

Thank you for contributing to this great site, hopefully one day I can return the favour!

# Answer
Sorry... Found out how to work around such a situation:

By skipping the explicit download function `dl` and just using the enable `en`command

`cd **module path**`

`drush en **file list**`

you get an automatic download option, which I think by adding -y you can automatically answer yes to all pompts. It's just a problem that sometimes the module names won't always match the package name.
> 1 votes

---
Tags: drush
---


# Question
Title: How to change the order of the payment methods in Commerce?
How can I change the order of the payments methods in the last step before placing an order in Drupal Commerce?

# Answer
> 6 votes
Changing the weight of the Rules for payment methods will change the order on order review page.

---
Tags: commerce
---


# Question
Title: Create a taxonomy view that links to different photos
I'm creating a website for a business who sells and installs rail fencing for their clients.

For the fence, there are three different categories of interest:

* fence type (2 rail, 3 rail, etc)
* fence application (barrier, dog fence, horse fence, etc)
* fence material (pressure treated, pine, etc)

I'm trying to create a method of giving the site visitor to choose how they want to look at the pictures.

Each time a fence is installed and photos are taken, I want the business to be able to sign in, create a node called "Photos," Add a title, cover image, body, group of images, and then tag the node using the 3 categories above (on three separate taxonomy lines).

From there, the site would automatically arrange the added photos into the pre-configured view based on its categories.

http://fence.ckasdf.net is the site.

The menu item marked "Photos" shows a view that separates each slideshow by "job" or node called Photos. This works as expected.

The menu item marked "View: Fence Application" is a view of taxonomy and shows the various applications. Clicking on each link shows the various nodes (jobs) that have been tagged with that particular application, and clicking on a node shows the picture slideshow.

Instead, after a taxonomy term is clicked, I want it to load a page showing a slideshow that includes all the photos relevant to that taxonomy term.

# Answer
> 0 votes
Here I am adding the screenshot for the configuration section for this module which you will find in your vocabulary manage display.

Screenshot

---
Tags: views, taxonomy-terms, nodes, javascript
---


# Question
Title: 'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box
Within our 'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box. One possible way of implementing this would be to utilize hook\_block\_view\_alter or hook\_block\_view\_MODULE\_DELTA\_alter within a custom module and then add this new link to the bottom of this block.
Is this the best way to add this link to the 'Search Form' block?

# Answer
> 0 votes
You could either use the `hook_block_view_alter` to add the link, just like you say. Or you can implement the `search-block-form.tpl.php` in your theme and add the link in the template file.

---
Tags: blocks
---


title: List of nodes within a block

text:
# Question
Title: List of nodes within a block
I have a page for available job positions, which has some content but I'd like to also place a list of the jobs in the middle of this content.

I would like this list to be dynamic based on currently published "job" nodes. The problem is this content is within a block. I know about views and can easy create a list with views, but I don't want this list to be a stand-alone block. Is there a way to pull a dynamic list like this into a pre-made block?

# Answer
There are multiple ways to do this.

1. You can create a view page with list of nodes and you can add other content in the views header or footer area.
2. You can create it as view attachment and can add to other view.

Basically views have a great flexibility to get embedded in one another,panels, nodes etc.
> 1 votes

---
Tags: 7, views, blocks
---


# Question
Title: "Rendered" View style for a Taxonomy Term?
When creating a View for content Nodes, the "Format \> Show" options includes "teasers" and "full posts" in addition to "fields". But for Taxonomy Terms, the only option appears to be "fields". I have Taxonomy Terms that have additional fields attached, and have the Display Preferences set to show/hide various fields for a teaser/full display of that term. Since different Taxonomy Terms have different fields, I want to use the Term's configuration rather than hard-code it into the View.

Is there a way to add a rendered View of a Term itself? Or do I need to create a separate View for each Term I want to summarize and define the "teaser" display again in the View?

# Answer
At "Format \> Show" there is an option "Rendered entity".

Apply it and then you can choose term's "View mode" in the select dropdown.

Also you can install Display Suite and notice new option "Display suite" at "Format \> Show".
> 1 votes

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


# Question
Title: Number of users currently checking a node
I need to build a view "preferably a nodejs\_view" that could count the number of logged in users that are currently checking a node.

Lets say we have 10 users currently checking node/123, I need to create a view that shows something like this:

```
node: 123
viewers: 10

node:124
viewers: 2

```

Is there any modules that could provide that? any idea how to build such thing?

# Answer
> 1 votes
viewers ,though this module is in drupal 6 but it can give you a good start.

---
Tags: views
---


# Question
Title: Trouble adding markup in a node with hook_node_view()
I'm trying to add a piece of markup with a field in hook\_node\_view(). It's a little thumb icon for a music site, and I want to overlay this image over another field image (which I'll do with CSS). However, it's not rendering, and I feel pretty confident that I'm going about it the right way. Here is my addition to the node array:

```
$node->content['like'] = array(
            '#theme' => 'image',
            '#path' => '/sites/default/files/likeimg.png',
            '#alt' => 'like',
            '#prefix' => '<div class="like">',
            '#suffix' => '</div>',
            '#weight' => -1,
            '#attributes' => array(
                'class' => array('like-img')
            )
        );

```

What am I missing? I am using Display Suite with fields in blocks, and Omega 3.

# Answer
Do you call the render function of your `like` content inside the `node.tpl.php` ?

```
print render($content['like']);

```
> 1 votes

# Answer
`hook_node_view()` is only called within modules that define node content types (ie. through `hook_node_info()`.

What you want to use is `hook_node_view_alter()`, and render the content in your template file like **Mike Vranckx** suggested.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Making drupal_goto Ignore ?destination=foo
I frequently come across cases in my Drupal 6 sites where a user might encounter my module's pages with the ?destination=foo querystring appended to the URL, from previous interactions on the site. Results of this vary from "inconvenient" to "very aggravating."

The default behavior of `drupal_goto()` checks for the destination parameter first, and disregards the arguments to `drupal_goto()` if it is present.

Is there a Drupal-native way to use drupal\_goto() in a way that ignores `destination`?

(Yes, I know I can recreate a version of `drupal_goto()` in a utility function, but I would prefer a Drupal-native solution if one exists)

# Answer
> 15 votes
It's actually quite simple, just unset `$_REQUEST['destination']` before you invoke `drupal_goto()`.

# Answer
> 4 votes
Actually, `unset($_REQUEST['destination'])` doesn't work for me, but I was able to get it work with this instead: `unset($_GET['destination'])`.

---
Tags: 6, redirection
---


# Question
Title: How to create a relationship between a table in a database and content type in views d7?
A table table\_A is present in database with a abc\_nid and abc\_code columns. I have a node having abc\_nid as node\_nid
How can I link a abc\_code (from the table\_A) in a view using relationship(non programmatically) or any other way ?

# Answer
> 3 votes
You can certainly implement this functionality by creating a views plugin:

1. In your `<module_name>.module` file implement `hook_views_api()`.
2. In your `<module_name>.views.inc`, implement `hook_views_data()`. Something roughly like this:

```
/** This hook should be placed in MODULENAME.views.inc and it will be
 * auto-loaded. MODULENAME.views.inc must be in the directory specified by the
 * 'path' key returned by MODULENAME_views_api(), or the same directory as the
 * .module file, if 'path' is unspecified.
 */
function MODULENAME_views_views_data() {
  $data = array();

  // Select/Create a category.
  $data['table_A']['table']['group'] = t('Your category');

  // Define the join with your table.
  $data['table_A']['table']['join'] = array(
      'node' => array(
      'left_field' => 'abc_nid',
      'field' => 'nid',
    ),
  );

  $data['table_A']['abc_code'] = array(
    'title' => t('ABC Code title'),
    'help' => t('Some help text.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
  return $data;
}

```

You can choose the appropriate handlers:

If required you can add you own handlers by extending the handlers. But, adding a handler is **required**.
3. This will provide you a *field*, a *filter* and a *sort criteria* in your view of nodes which will *display/filter/sort* the fields on the basis of the value of `abc_code` for that particular field.

---
Tags: 7, views
---


# Question
Title: Getting nodes based on what the user has in their profile
I have a term reference field in my user accounts and I have nodes that are also tagged with that same vocabulary.

I have a view set up to display all the nodes, but I want it to display only nodes that have the terms that the users has checked in their account.

**Example:**

```
Node: Shirt
Term(s): Blue

Node: Skirt
Term(s): Green, Blue

Node: Dress
Term(s): Red

Node: Shoes
Term(s): Purple

```

My user has terms: Blue, Red

I would like to see nodes: Shirt, Skirt, Dress

# Answer
> 0 votes
One of the possible solution can be

* Create a view to show the nodes with contextual filters as taxonomy,remember to allow multiple taxonomy terms may be separated by '+' in the contextual filters.
* Create a custom menu item in your custom module and in the page callback of which grab the taxonomy terms in the global user object and call the above created view programmatically.
* Here is a snippet showing how you can call your view programmatically with contextual filters.

```
views_embed_view("your_view_name", "your_view_dsiplay", $taxonomy_terms_+_separated)

```

See the following screenshots.

In my test installation, I created the following taxonomy terms: test1,test2,test3,and test4. I created 4 nodes too, each of them using one of those taxonomy terms (node1 =\> test1, node2 =\> test2, etc.).

The following is the screenshot of a view page showing the nodes using the taxonomy IDs passed as contextual filters.

>

These are the screenshots of the view configuration for those for contextual filters.

>

>

>

---
Tags: views
---


# Question
Title: How to change URLs of Mini-Calendar Block View?
I'm using the calendar module in drupal 7. I put the block-view mini-calendar but I want to make a change to the URL of each day's link of the month that showing me.

By default, the URL sent me to the full schedule of activities in that month (use event\_calendar content type). However, I want to change that view and I just want to make a simple listing of activities for the month.

How I can change the URL to do access the new view I want to create?

Sorry for my english. Thanks in advance.

# Answer
Here goes a well description for altering date links in calendar http://eureka.ykyuen.info/2011/08/07/drupal-customize-the-day-link-inside-the-mini-calendar-navigation-block/
> 0 votes

# Answer
In mini-calendar view go to advanced -\> other -\> Link display and change it
> 1 votes

---
Tags: 7, datetime
---


# Question
Title: How to compare nodes of different types but same fields?
Is there any way to compare nodes of different types but with the same fields?

* I have 2 content types: **Flats to rent** and **Flats wanted**
* Both types have the sames fields: **rooms** and **city**
* In a view I have a list of the **Flats wanted** and each one has a button: **find flats**
* When you click the **find flats** button I need to show all the **flats to rent** that have the same values for: **rooms** and **city** than the clicked **flat wanted**

I already get it working by creating a View using `$_GET` variables in the url and **arguments**. But I need to use clean urls, then`$_GET` must go out.

Is there any way to do this in a cleaner way? I need to do it using View because I need to be able to apply bulk operations in the resulting list.

Maybe a module could do this??

Thanks

# Answer
I would create a custom field handler. This gives you full PHP power about how the link of the "find flats" button will look like.

Writing your own handlers for views maybe looks difficult at the beginning. Once you understand it you will use it a lot. Here I found a how to about how to do that (it's for views 2). You'll find a lot of real world examples in all modules that do support views. Look for code like `MYMODULE_views_handlers` .
> 1 votes

# Answer
Just because you enabled clean\_urls does not mean you cannot amend additional arguments. On the contrary, Drupal will intelligently pass your additional arguments directly to the View or to whatever module.

For example, these paths:

```
example.com/node/1/edit
example.com/node/1/edit/foo/bar

```

will both take you to the same place.

If your view is at the path 'flats' you could simply append arguments to the url:

```
example.com/flats/arg1/arg2/arg3

```

and Views can handle them just fine.

I wouldn't recommend panels.
> 0 votes

# Answer
Try Node Compare. At the moment it is the most elegant and easy solution to compare nodes in Drupal.
> 0 votes

---
Tags: nodes, uri, views
---


# Question
Title: Selecting the right pattern for adding in robots.txt
I've some views with exposed filters but I find that Googlebot is indexing them. In short I don't want any of those Views content by generated exposed filters to be seen by Google.

This page has listed more about it.

I want a pattern which should work for almost all views by restricting access to content generated by changing exposed filters.

Will this cause any issues?:

```
Disallow:/*&sort_order=*

```

Assuming we always specify sort order in Views. Is there any other module(s) which may generate url containing this parameter?

# Answer
Adding the line you suggest to you site's `robots.txt` will stop *googlebot* from crawling the URLs that contain this string.

However, what attributes modules add to the URL is up to the module. You need to examine the source code of the modules you use to avoid any conflict. I doubt there is anyone here with encyclopedic knowledge of what attributes *every* module use (there are more than 20000 on Drupal.org).

Instead of searching through modules for possible conflicts, I would invent a "magic" string that is pretty much guaranteed to be unique or not used for any *other* purpose by a Drupal module (e.g. "dontcrawlme") and add that "magic" string to the path to the views I don't want crawled, or add a dummy attribute with "magic" string as name to those views, then Disallow any crawling of an URL containing the "magic" string. This is simpler and more robust than relying on `sort_order=` being unique for exposed filters in Views.

You need to take care not to overwrite your custom additions to `robots.txt` when you do a minor upgrade of the Drupal core.

Note that wildcards is not part of the Robot Exclusion Standards (but are supported by *googlebot* and *bing*), so don't expect any rule with wildcards to be widely recognised by robots.
> 1 votes

---
Tags: views, google-search-console
---


# Question
Title: How to show upcoming events in the current month with calendar module?
I'm using Drupal 7 Module Calendar, Views and Panels.

I used the block-mini-calendar view of Calendar module to display on my frontpage.

Then I created a custom view to display only a list of the day's events selected by the user.

I put as Context-Filter: `Date: Date (node) (Content: Dates - start date (event_calendar_date)`)

```
And Filter Criteria:
Content: Published (Yes)
Content: Type (= Event Calendar)

```

Then, I created a panel-page that receive the arguments of the date by URL and passes to my view created (My view created above I've put in my panel created with the URL of events/%date).

All previous flow works well. I'm listing all events of the day selected by the user. But, I need to display all events that are within the range of parameter passed in the URL(day selected) and the last day of the current month that the user is.

What changes should I do in my view?

Sorry for my english. Thanks in advance.

# Answer
> 1 votes
Try paginating the view by Date,I guess should get the month options in the pagination as well.I do not have a drupal set up with calendar so can not confirm, you have to give a try.

# Answer
> 1 votes
Using the Date module, you can add a filter for the current date using relative values.

```
number space? (unit | 'week')

```

Add two Date filters, each for the event date.

* Value is **greater than or equal to** "-15 days"
* Value is **less than or equal to** "+15 days"

Basically we're saying to give us all events that have a date within 15 days of us, behind us and ahead of us. You can increase/decrease those values as needed.

---
Tags: 7, datetime
---


# Question
Title: drupal_mail_system is returning empty object
I have installed mime module for sending html mails. Im receiving Drupal security update on my site but not sending/receiving any mails through my code.

```
$settings = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $email_to,
  'subject' => $email_subject,
  'body' => $email_message,
  'headers' => array(
    'From' => $conf['FROM_email'],
    'Sender' => $FROM,
    'Return-Path' => $FROM,
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
  ),
);

$system = drupal_mail_system($my_module, $my_mail_token);
if ($system->mail($settings)) {
  print 'success';
}
else {
  print 'failed';
}

```

I tried to `print_r($system)` which is supposed to return object of mail system interface but all I received was `HTMLMailSystem Object ( )`. What am I missing?

# Answer
> 0 votes
You forgot to call `format` method.

Try the following snippet:

```
$from = variable_get('system_mail', $my_email);
$message = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $my_email,
  'subject' => $message_subject,
  'body' => array($message_body),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);
$system = drupal_mail_system($my_module, $my_mail_token);

// The format function must be called before calling the mail function.
$message = $system->format($message);

if ($system->mail($message)) {
  drupal_set_message('SUCCESS');
}
else {
  drupal_set_message('FAILURE');
}

```

---
Tags: 7, emails
---


# Question
Title: Can I group fields by their Field Group in Views?
I'm using Field Group module to manage field in content type and I want to display field as table in views, but group field not showing properly. What should I do?

I attached an example below.

e.g.

# Answer
> 1 votes
Field group doesn't actually do anything with regards to data storage or grouping, it only provides fieldsets and formatters for data *entry* and grouping fields together on display.

It seems to me that you'd find either Field Collection or Tablefield more useful for this use case.

With TableField, you can just output the field in Views, as it's already a table.

With regards to Field Collection, it's a little more work, but much more flexible. You should be able to add a relationship in Views to the the field collection entity that contains your fields, and then group by the entity ID of said field collection in views.

You will also probably have to use something like Views Field View to embed your grouped Field Collection fields into your original view if the other fields aren't to be laid out like tables..

---
Tags: views, entities
---


# Question
Title: Panels Node template with additional arguments
The basic crux of what I'm trying to achieve is this:

When viewing a node - Content Type A (which is currently overridden with a panels node template) I want to be able to show a views block that will display the fields from one node of content type B.

To control which node from Content Type B would display on Content Type A pages, the idea was to set up a views pane with a contextual filter, so that any two nodes from hte two content types could be displayed together. This works fine by itself and in the preview.

But, I am having trouble getting panels to comply with my wishes!

I can set up a node template panel, but can't work out how to pass the second argument to the view pane. And I have tried to create a new panel to override the node so that I can pass the argument to the pane but it isn't overriding the node.

Any ideas how I can do this please?!

# Answer
> 1 votes
You need a few components to make this work properly.

1. You View must have a display of type "Content pane".
2. A contextual filter.
3. In the Pane settings you should set your argument input to be "From context", and then picking an argument source that matches what your contextual filter wants. Most likely that will be a node id. (The argument setting could be a specific argument, first, second or so, as well, but that's generally not a very good idea)
4. Add the View *pane* to your panel page, *not the View* itself. If the Pane doesn't show up in the listing, your Pane settings are wrong.
5. Done.

# Answer
> 0 votes
To pass URL argument from Panel to Content pane, try:

1. Add Contextual filter to the View. E.g.: Views contextual filters taxonomy name
2. Change settings in 'View -\> Pane settings -\> Argument input' to load the argument 'From panel argument' (e.g. First). Try other options for your needs.

---
Tags: panels, views
---


# Question
Title: How do you pass page arguments from panels to a view?
I'm creating an online store using Ubercart. I have Views and Panels installed. I'm using the Page Manager and Panels to configure each of my pages. I've modified the default view to accept taxonomy terms as arguments.

My question is simple, "How do you pass arguments from Panels to a View?"

I followed the direction's at this URL, but, in the process, actually discovered a much better way (I posted the solution in the article, but I'm also going to post it here):

\[a link\] http://itscommonsensestupid.blogspot.com/2009/04/passing-arguments-from-panel-to-views.html)

I will post the best solution to this question in a couple of hours.

# Answer
> 1 votes
Example scenario:

There is a panel containing View Content Pane.

Panel URL: /panel\_url

Example with argument: /panel\_url/term\_name

With BEF: /panel\_url?category=123

How to set up (having existing panel and added Content Pane):

1. Add Contextual filter to the View. E.g.: Views contextual filters taxonomy name
2. Change settings in 'View -\> Pane settings -\> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

---

In addition, if you're using Better Exposed Filters, you could do the following improvements.

To set the current active link based on the argument (if you're using select\_as\_links):

```
/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}

```

To set the current active link based on the argument (if you're using select):

```
/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'DROPDOWN_NAME') { // name of your select list
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

```

To make the links SEO friendly, you can try something like:

```
/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}

```

---
Tags: 6, ubercart, panels, views
---


title: Override exposed filter dropdown values

text:
# Question
Title: Override exposed filter dropdown values
I have exposed filter of taxonomy with dropdown. I want to override the dropdown menu, so that when I filter through this exposed filter, the url contains title of taxonomy and not the ID of taxonomy.

So, I have used `hook_form_alter` to override this dropdown, and made it in the form,

```
<option value='TEXT'>TEXT</option>,

```

initially it was like

```
<option value='ID'>TEXT</option>,

```

But in this case it is not filtering out any results, please suggest how can I make it work.

Thanks for your time.

# Answer
> 2 votes
If I'm understanding correctly, you're trying to pass an argument from an exposed filter to a contextual filter, on a Views page? If so, it seems like you haven't built the contextual filter part.

1. Add a Contextual Filter, "Has taxonomy term ID"
2. Enable "Specify validation criteria"
3. Set validator to "Taxonomy" and pick your vocabulary.
4. Under "Filter value type", choose "Term name converted to Term ID." Click Apply.
5. Make sure the Views page path is set to something with an argument -- i.e., "/your-search-page/%" -- the % tells Views to expect some kind of argument.

Let me know how this works. Note in the future, it helps if you post the code you've tried (Even a View export).

# Answer
> 3 votes
Implementing hook\_form\_alter() alone is not enough. The View query will check the taxonomy by term id. Now you just altered it to title in the dropdown values.

You would then need to implement hook\_views\_query\_alter() and alter the query condition as your need. Assuming you have a taxonomy term field **field\_cat**, your view query will have the following similar condition - `field_data_field_cat.field_cat_tid = {the_selected_value}`

Now, you need to check it against **taxonomy\_term\_data.name**:

```
function MYMODULE_views_query_alter(&$view, &$query){
    if($view->name == 'your_view_name'){
        $conditions = $query->where[1]['conditions'];
        $k = 0;
        foreach($conditions as $cnd){
            if($cnd['field'] == 'field_data_field_cat.field_cat_tid'){
                $replaced_condition = array(
                    'field' => 'taxonomy_term_data_field_data_field_cat.name',
                    'value' => $cnd['value'],
                    'operator' => $cnd['operator']
                );
                $query->where[1]['conditions'][$k] = $replaced_condition;
                break;
            }
            $k++;
        }
    }
}

```

Hope this helps.

# Answer
> 0 votes
It depends on the purpose.

If you want the the url to look something like `http://example.com/viewurl?name=taxonomyname` Then you should do the following

1) Create a taxonomy view instead of a content view. This is done by selecting taxonomy from the drop down of "Show"
2) Add a filter `Taxonomy term: Name` make it exposed
3) Add the required fields. Please note that if you want to add the fields in the content then you need to create a relationship of the `type Taxonomy term: Content with term` other wise you would not be able to display the content fields.
4)This would create the exposed field as a text field and not a drop down. So now in your custom field you would need to convert the text field to a drop down using a custom module where you would use the `[hook_form_alter][1]` to change the element to a drop down. You will need to get the entire terms to create the options. For this you would be using the function `[taxonomy_term_load][2]`

That was the answer for what you asked.

Now if your purpose is just to create clean url for your results then you should use the contextual filters instead of the filter criteria.

# Answer
> 0 votes
Normally you can change that in hook\_form\_alter():

```
/**
 * Implements hook_form_alter().
 */
function foo_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name != 'YOUR_VIEW_NAME') {

      foreach ($form['select_list']['#options'] as $key => &$value) {
        // your code here
        if ($value === '') {
          $value = t('Example default value');
        }
      } // end: foreach

  } // end: if
}

```

You can also override the value in the preprocess function of the specific element, e.g. my function to override the select value, but you'd need to change the list of #options list, as you could have illegal choice error:

```
/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'DROPDOWN_NAME') { // name of your select list
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

```

---
Tags: 7, views
---


# Question
Title: Including JS files in template.php to control weight/order/group
I'm looking to include a few JS files (some libraries, others are custom modules with dependencies on libraries). Originally I had all JS files added through our .info file, and while I could control the order of the files manually my moving them up and down, that would result in all the JS files loading on every page.

Is it a better idea to add JS files through template.php in the template\_preprocess\_html function? For each JS file I can attach a group property (one of the constants of JS\_Library, JS\_DEFAULT, or JS\_THEME) to control the ordering, and also control which pages need to load which files.

Thoughts?

# Answer
> 0 votes
You can try JS injector module which provides an UI for that

---
Tags: 7, javascript
---


title: Can't rearrange menu items on Drupal 6

text:
# Question
Title: Can't rearrange menu items on Drupal 6
I encountered a strange situation. I have a Drupal 6 site with a very large menu tree. I can add new menu items but I cannot rearrange menu items. I can move the items, but when I submit the changes, the menu item gets back to the old position. I tried to disable javascript and set the weight manually, I tried to empty the cache, even disabled it completely. I tried to rebuild the menu with DEVEL, but nothing helped.

I recently upgraded to PHP 5.3.27 so maybe it's related to this. I had some errors about timezone settings, but I corrected this with the timezone set in php.ini. I have no other errors in the log.

If I edit a menu item and set the weight, it works. If I set the weight from the DB, it works. The only thing that doesn't work is the rearranging on the items list page.

Edit: PHP log shows no errors even with E\_ALL reporting. I think the problem is with Drupal, as it only lets weights from -50 to 50 and the rearranging can't put the items where I want them. Whe I set weights of more than 50 in DB, the ordering was correct, just until I wanted to change the order withhin Drupal. Then, the manually set items scrambled. Is there a way I can set it up to allow values in a wider range? I don't want to rearrange everything via DB it's a pain in the ass.

# Answer
PHP 5.3 enforces a `max_input_vars` (see the accepted answer in PHP Warning: Unknown: Input variables exceeded 1000) and I've seen it create similar errors (page saves yet nothing is saved) when setting permissions for users on sites where there are lots of permissions and lots of roles, so, most probably the same is happening here with the menu UI when it has lots of menu items. To resolve it, bump up the value on your system (see php.net documentation for `max_input_vars`) until things work again.
> 1 votes

---
Tags: 6, routes
---


# Question
Title: Can a database query be written inside a template.php file?
I am writing a query inside the following function of template.php file

```
        function theme_name_process_views_view_field(&$vars) {
 if ($vars['view']->name == 'view_name') {
// query is written here
      foreach( $vars['view']->result as $key => $value ) {
          $nid = $value->nid;
          $query = db_select('abc_in', 'abc')
            ->fields('abc', array('study_abc'))
            ->condition('abc_nid', $nid , '=');
          $result =   $query->execute()->fetchField();
        $vars['view']->result[$key]->field_field_abc_in[0]['rendered']['#markup'] = "<div class='abc_code'>" .  $result . "</div>" ;

    } }

```

Is it ok to write a db\_query inside template.php file ? I an taking a data from custom table and inserting value into field of a view ?

# Answer
You can definitely do it, however you really shouldn't.

The theme layer is for presenting the data. The actual functionality and the data itself should come from modules.

If you mention what you are trying to do I can give some more information on where it should go instead

**Edit**

Based on your code example, if you are dealing with a custom data table the best thing would be to use hook\_views\_data() to let views know about your database table and fields. Then you would just use your new fields via the UI.

If you didn't want to go to that much trouble though you could use basically the same solution as you are using now in a custom module in one of the views hooks, like hook\_views\_post\_execute(), where you can loop through the results in a similar fashion as you are doing now.

You generally wouldn't be dealing with markup here though (like your abc\_code div). You're really only changing data here and then changing markup in the theme. Although your field should already have classes that let you specifically style it so adding that class probably shouldn't be necessary.
> 3 votes

# Answer
It is not a recommended practice to add db queries to your theme you should always separate logic behaviour from your presentation layer

Plus also you should always follow drupal standard for doing things
> 1 votes

# Answer
You shouldn´t write queries in "theme functions" or ".tpl files".

If you need the data to render the element you could considering to write the query in the preprocess function making the data available in the "theme function" or ".tpl file" in this way
> 0 votes

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


# Question
Title: How to get taxonomy term in Overwrite view exposed filters file?
views-exposed-form--CONTENT-NAME.tpl.php

Can we get content selected taxonomy term in this file

# Answer
Go to
Home » Administration » Structure » Views

Under the advanced tab at the right corner click on theme : Information There you can get a list containing file name for overriding templates.

From that you can create your file name accordingly
> 0 votes

---
Tags: nodes, views
---


title: Showing title keyword in autocomplete

text:
# Question
Title: Showing title keyword in autocomplete
I have just installed search auto complete module,its working fine,but the problem is its showing title before every result like:

title: Drupal 7.9 Release

tile:Understanding Drupal

Here Drupal 7.9 release and Understanding Drupal are my article title may be due to that its showing,but anyhow i want to remove this.

Thanks

# Answer
In search\_autocomplete.view\_autocomplete.inc file, line number 209 just replace it with the following line:

$object-\>label .= ' ';

that will remove the label (title) in search result.
> 0 votes

---
Tags: search
---


title: add facebook,twitter links to node page

text:
# Question
Title: add facebook,twitter links to node page
My requirement is that in my custom content type page, I need to add fields that link to facebook and twitter. This is easily do-able as two textboxes which contain the hyperlinks to the two site urls. However the way I want it is that, if there is a facebook URL added, in the display it should show a facebook icon clicking on which will take the user to the facebook URL, same with twitter. (It is not for sharing my page content in facebook, but for redirecting the user to facebook link provided - same with twitter)

I would like these two to be two standard fields in the content type so that added links to these two will trigger this behaviour. If the textboxes are empty, the icons will not show up.

Any pointers on how this can be achieved? I looked at the various social share modules in drupal, but most of them are for sharing/tweeting the page inside which they are added.

I appreciate any help...

# Answer
> 1 votes
You can use Link module to create facebook or twitter url field for your content type.

> The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

For facebook or twitter icon, you need to manage this through css or need to add extra field for icon and display node.tpl.php if there is value for the link field.

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


title: Field remember settings

text:
# Question
Title: Field remember settings
Let's say we have a content with these fields:

* Title
* Category
* Price
* Mobile
* Skype
* City
* E-mail

A checkbox for "Remember my settings" that will remember these fields:

* Mobile
* Skype
* City
* E-mail

When user is registered in profile edit will have an option to change (I guess this will be able to achieve with Profile2):

* Mobile
* Skype
* City
* E-mail

After changing these details, the next new content form will have a checkbox for "Use my settings" to use the settings from the profile form details. Is it possible to do this with a module or hook in Drupal 7?

I'm not asking for someone to explain me the details (even it's very welcomed), but I'm asking if it's possible, what module or hook should I use? I hope this doesn't sounds too broad.

# Answer
> 2 votes
I think you are looking for Remember values

> This module enables Drupal to remember entered values from selected fields upon new node submission, stores them in the database and then pre-fills appropriate fields on the next node-add form. This is useful when a user needs to enter many nodes at a time and some of the fields' values are repeating.

---
Tags: entities, users
---


# Question
Title: How to store Sharethis Values in the Database?
I am using the Sharethis Module and i want to sort some views by the number of total shares. But if i am understanding it correctly the values are not stored in the drupal database. Instead they are pulled from the Sharethis Servers. How can i store these values in the Drupal Database ?

# Answer
> 0 votes
You can use the Social Stats module to do that.

> This is a statistics module. It provides data from various social media sites. The data which is saved per node includes data from:
>
> 1. Facebook : likes count, shares count, comments count & total count.
> 2. Twitter : tweets count.
> 3. LinkedIn : share count.
> 4. Google Plus : plus one count
> 5. Total shares

Note: This is a sandbox project. I'm the author of the module.

---
Tags: views, database, social-network
---


title: Content publication authorization

text:
# Question
Title: Content publication authorization
I need some information on how to achieve a solution which will allow a group of users to create content but the content remains unpublished until multiple managers have somehow signed off on the content of the node page.

I'll be happy if the suggestion comes in the form of a module and/or a recipe on configuration steps.

# Answer
There are different modules out there for achieving this kind of results. Some of the ones I know are:

> Workbench provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

> The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.

> Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.
> 1 votes

# Answer
The Workbench module provides you a customizable editorial workflow. Here is a quote about it (from the module's project page):

> ... provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:
>
> * a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
> * the ability to control who has access to edit any content based on an organization's structure not the web site structure
> * a customizable editorial workflow that integrates with the access control feature described above or works independently on its own
>
> These features benefit the end users as well as Drupal Site Administrators and Technical Support.
> 1 votes

# Answer
modr8 provides an administrative interface for managing content in moderation.

Allows you to preview content, as well as approve or deny, and send messages to the author informing them of your choice.

> This module adds back that capability and also prevents posts that are in moderation from showing up in lists, on the /node page, etc., unless the user is the node's author or unless the user has the "administer nodes" or "moderate content" permission. This is NOT an access control module, however, so posts that are in moderation can still be viewed if a user knows the path (URL) corresponding to that post.

**or**

Moderation

> It allows moderators to review all posted content while already published. Included Ajax based functionality allows the moderators to preview the content and to change status like published, moderated, promoted, sticky without having to leave the page. A separate page provides a log, listing all status changes with who and when it was changed.

**and** also take a look at this Maestro module
> 1 votes

---
Tags: 7, users, nodes
---


# Question
Title: looping an image field with multiple values? alt or text?
I am about to implement a img gallery in a node template. The gallery has the usual HTML markup (a span with bgimage, wrapped by a div...) I do not have any knowledge on php, but - in the last 24h - i was able to modify some code snippets i found:

```
    <?php
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_project_image');
$image_url =file_create_url($node->field_project_image['und'][0]['uri']);
foreach ($image as $key=>$value) {
$output = field_view_value('node', $node, 'field_project_image', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail', //place your image style here

  ),
));

print '<div class="singleswipe">';
print '<span id="swipe_bg_image" role="img" style="background-image:url(\'' .$image_url. '\'); background-size:100%; background-position: 50% 50%; background-repeat:no-repeat">';

print '<span class="inner"></span>';

print '</span>';

print '<span class"title">title of the img???</span>';

print '</div>';

}
?>

```

This works somehow. BUT: it always shows the same picture. (Apparently it is always the same image\_url), plus: I don't have any idea how to implement the "title" or "alt" text for every single image. Please, I am in a serious need for help now...

# Answer
> 0 votes
You can follow the below code. Please change 'field\_flexslider\_example\_image' with your field name in content type.

```
<?php
$node = node_load($nid);

$image = field_get_items('node', $node, 'field_flexslider_example_image');

foreach ($image as $key => $value) {
$output = field_view_value('node', $node, 'field_flexslider_example_image', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail', //place your image style here

  ),
));

$image_url = file_create_url($value['uri']);
$alt = $value['alt'];
$title = $value['title'];

print '<div class="singleswipe">';
print '<span id="swipe_bg_image" role="img" style="background-image:url(\'' .$image_url. '\'); background-size:100%; background-position: 50% 50%; background-repeat:no-repeat">';

print '<span class="inner"></span>';

print '</span>';

print '<span class"title">' . $title . '</span>';

print '</div>';

}
?>

```

---
Tags: entities, media
---


# Question
Title: Ubercart how to provide expiry option for a product if its not in auction?
How to provide option for products to be automatically expired using ubercart.

I know one solution could be scheduler.

Is there any other solution which can be applicable only for add to cart products alone instead of auction item which already has expiry dates.

Thanks in advance.

# Answer
> 0 votes
There is one for Drupal 6, but there does not appear to be a solution for Drupal 7.

The easiest way may be to use rules with an additional field in the products content type and set the product to be unpublished after the date (see https://groups.drupal.org/node/240678 for an example).

Another more complex way would be to make a module that runs on cron (`hook_cron`) loops through all the products (MySQL select * from uc\_products for an example), add a new field to the products content type called expired, set it to a date (using the date module), upon looping through products get the entire node (including this field) and see if it is expired.

But scheduler can do what you want, you just need to add a new field to the content type for the expiration date and set it to expire on that.

---
Tags: 7, ubercart
---


# Question
Title: How to alter a field within an unlimited field collection?
I am trying to set the `#access` attribute to `FALSE` on a field that is within an unlimited field collection - so it is hidden from users. I am relatively new to Drupal so I'm not sure how to handle this. I tried to use `hook_form_alter` and some basic CSS - but I couldn't get either of the solution to work properly because of the unlimited field cardinality.

Here's what worked for one row in the field collection in a custom module:

```
$form['field_my_field_collection']['und'][0]['field_myfield']['#access'] = FALSE;

```

How do you alter a specific field in a field collection with unlimited values? Thanks in advance for any help - the Drupal community is awesome.

# Answer
> 6 votes
Since Drupal 7.8 you can leverage hook\_field\_widget\_form\_alter. You can alter any field widgets provided by field\_collection before the form\_alter of the main form.

```
function my_module_field_widget_form_alter(&$element, &$form_state, $context) {
  if ("field_my_field_collection" == $element['#bundle']) {
    if ("field_my_field_collection" == $element['#field_name']) {
      $element['#access'] = FALSE;
    }
  }
// dpm(array($element, $form_state, $context), "field_name: " . $element['#field_name'] );
}

```

# Answer
> 3 votes
Thanks for your help Mohammed, but I ended up using the following code in a custom module:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'myformid') {
$delta = 0;
$max_delta = $form['field_my_field_collection'][LANGUAGE_NONE]['#max_delta'];
while ($delta <= $max_delta) {
$form['field_my_field_collection'][LANGUAGE_NONE][$delta]['field_myfield']
[LANGUAGE_NONE][0]['#access'] = FALSE;
  $delta++;
    }
  }
}

```

---
Tags: entities
---


# Question
Title: What if I don't want node pages for content type?
I am creating a node type that I don't want to have a separate node page for. I am going to use a page view to pull them into a list. And they will link to a URL that is stored in a field for the content type.

These are simple content types and there is no need for them to have a node page. I know I can avoid having a page for them just by having no way to get there, but is there anything else to think about.

Maybe they should be something else besides a content type? Or is there a better way to not have node pages for a content type?

**Edit:**

I'm not really trying to prevent people from viewing these nodes. If they want to get to the node with the URL then that's fine. The nodes are just very simple(title, short blurb, link) and the node page would be pretty useless. I am just wondering if I shouldn't use some other Drupal construct for something like this.

# Answer
My choice would be using them as nodes as you are doing right now. Reason being

1. Building a custom solutions would be again writing codes to interact with database,a custom form so to keep it dynamic.
2. This is already been handled by drupal in very efficient way.
3. Also using node entities you have various options open for scaling later,you can add fields to it, enjoy no-custom code interaction with views.
4. According to me,we as a developer or content editor,site admin have better hold on entities rather than any custom solution.
> 1 votes

# Answer
You are looking for Internal Nodes

> Some content/nodes should never be viewed directly; only visible be through something else such as Views or Panels. This module **denies access to node/\[nid\] URLs** while allowing the content to stay published and otherwise viewable. Try the demo!
> 2 votes

# Answer
Try to redirect when trying to see a node view

```
/**
 * Implement hook_entity_view().
 */
function custom_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle) {

    case 'your_content_type':
      drupal_goto('another_url'); //or access_denied
      break;

  }
}

```

And check with the permissions to denied edit and delete access for these kind of nodes
> 1 votes

---
Tags: nodes, 7
---


# Question
Title: Adding translations to installation profile upon installation
Creating an installation profile for a french site.

I have hit a brick wall trying to have the profile install fr language translations. I have tried adding this to my profile as this comment http://drupal.org/node/1297438#comment-6308144

```
// Add french language.
locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', true, true);
drupal_set_message(t('The language %language has been add and is now the default language.', array('%language' => 'french')));

```

Code above generates a fatal error:

```
[drush] Fatal error: Call to undefined function locale_add_language() in /home/stef/jmt-www/build/www/profiles/jmt_profile/jmt_profile.profile on line 19

```

I have the fr.po file in profile/jmt\_profile/translations but have no clear way of getting the fr.po loaded. Has anyone dealt with installing secondary languages without going through ui?

# Answer
> 3 votes
You must include locale.inc before:

```
include_once DRUPAL_ROOT . '/includes/locale.inc';
locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', true, true);

```

---
Tags: users, installation, distributions
---


title: Drupal differential db restore

text:
# Question
Title: Drupal differential db restore
I have several Drupal sites hosted on my shared hosting server. Each site has a dev, test and production instances, with separate Docroots and Apache Vhosts and separate mysql db instances. Not using features module.

Production db has real live data in it. dev and test dbs have dummy data. But as per the development workflow, if a new module has to be installed the developers do it in dev and test instances. That creates a new table and some records in the dev/test db instances.

Now that if they want to have the same module installed in the production site, I want them to able to run an operation via web which takes that particular table/data to the production instance from dev/test.

To explain bit more: This is what I need.

A ==\> Test Site

B ==\> Production Site ==\> Real Data

A new module is installed in A. This creates a table and some records in A. We should be able to take that particular table/data from A and import into B keeping all the B's data consistent. And we dont really know what table is created in A. This is all done by the developers.

In a nut shell. B = (A U B) i.e. B should become A Union B

I tried mysqldiff but that works only for schema but not data.

Ideas please.

# Answer
This is a huge question.

I just can share my experience

First i export mysql data from live site with Backup and Migrate module.

I do restore it in my dev site. In this dev site, i beware to not send infortunetly emails, so i install Reroute email module. (great because the settings are not in database but in settings.php file)

Then i make my own dev on localhost with real datas

Depends if your have the abilities to do that, and if the datas are not so confidential to do so.

But **to stick with your question**, db diff is impossible is guess. And you have to upload the new module files and enabled them manually (or with drush). Settigs in drupal are totally encapsulated in db
> 0 votes

# Answer
You may want to look into **Percona Toolkit**.

There are two particular tools you may want to use

* **pt-table-checksum** : This tool can be used to determine which tables have a different checksum between a Master and Slave.
* **pt-table-sync** : This tool will actually find the row and column differences in data based on PRIMARY KEY values. I would suggest using the `--print` and `--sync-to-master` options to output the generated SQL to a text file.

# CAVEAT

I can see from the question that you do not have MySQL Replication set up. Therefore, I would suggest the following:

* STEP 01) Get two DB Servers
    + Server MDB : A copy of Test DB
    + Server SDB : A copy of Prod DB
* STEP 02) Setup Master/Slave Replication
    + MDB as Master
    + SDB as Slave
* STEP 03) Execute pt-table-checksum against the Master. The program should autodetect connected Slaves.
* STEP 04) Use pt-table-chekcksum output to see which table on the Master (Test) has a different checksum on the Slave (Prod)
* STEP 05) For every table that have mismatched checksum values, run pt-table-sync and send output to a text file.
* STEP 06) Take the generated SQL and execute it on the Slave.

When you are done with `STEP 05`, the Slave's data content should be the `B = (A U B)` you are looking for.

**WARNING : Thoroughly backup all your data on Test and Prod before doing this !!!**

Give it a Try !!!
> 0 votes

---
Tags: database, features
---


# Question
Title: How do I skip language selection with installation profile?
I am building an installation profile for Drupal 7 and trying to skip the language selection page.

In the .profile file I put the following code:

```
function efocus_install_tasks_alter(&$tasks, $install_state){
    $tasks['install_select_locale']['run'] = INSTALL_TASK_SKIP;
    $install_state['parameters']['locale'] = 'en';
}

```

This skips the page but apperantly the locale selection is not working for some reason. Anybody that has any experience with this? I am quite new to Drupal, just started a month ago and can't figure out why it is not working. Any tips on what I can try?

# Answer
This cannot work, because $install\_state is passed as value, not as reference. So changing it has no effects.

```
function efocus_install_tasks_alter(&$tasks, $install_state){
    $tasks['install_select_locale']['function'] = '_efocus_locale_selection';
}

// local callback function
function _efocus_locale_selection(&$install_state){
    $install_state['parameters']['locale'] = 'en';
}

```

This one works. I am simply replacing the standard\_locale\_selection with a custom function, which gets the install\_state passed as reference. So i can change the value...
> 6 votes

# Answer
Your code works, you just missed : `global`

```
function efocus_install_tasks_alter(&$tasks, $install_state){
  global $install_state;

  $tasks['install_select_locale']['display'] = FALSE;
  $tasks['install_select_locale']['run'] = INSTALL_TASK_SKIP;
  $install_state['parameters']['locale'] = 'en';

}

```
> 1 votes

---
Tags: users, installation
---


# Question
Title: Creating conditional fields: How should I implement hook_form_alter()?
*Backstory: I used and highly enjoyed Conditional Fields modules for D6 in the past. Currently using 7.x-3.x-dev. But had some issues recently with it and would rather just learn how to do it manually. Familiar with Devel, but had no luck successfully getting a complex `hook_form_alter()` to work. Always end up hitting a dead-end.*

What are the fundamentals of implementing a `hook_form_alter()`?

I'd like to get this process laid out and in one single location. Thanks.

# Answer
> 2 votes
The Conditional Fields module's features can be done with using #statesattribute from form api in D7.

If you want to implement it, of course you need to use `hook_form_alter()` to bring additionaly attributes on existing fields. There many tutorials about the usage of `hook_form_alter()`.

Example of using of #states attribute:

```
  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

```

Example from Examples for Developers module - form\_example module

---
Tags: forms
---


# Question
Title: Theming a custom data table from php code text format with Drupal 7
I have a working block of php code that runs inside a Drupal 7 Page:

```
<?php
$my_database= array(
  'database' => 'mydb',
  'username' => 'xxxxxx', // assuming this is necessary
  'password' => 'xxxxxx', // assuming this is necessary
  'host' => 'localhost', // assumes localhost
  'driver' => 'mysql', // replace with your database driver
);
Database::addConnectionInfo('database_db', 'default', $my_database);
db_set_active('database_db');
$sql = "SELECT tcol1, tcol2 FROM mytable LIMIT 10";

$result = db_query($sql);
$header = array('Col1', 'Col2');
$rows = array();
if ($result) {
  while ($row = $result->fetchAssoc()) {
    $row= array($row['tcol1'],$row['tcol2']);
  $rows[] = $row;
  }
}
db_set_active();
print_r($rows);
$output= theme('table', $header, $rows);
?>

```

This piece of code works fine and print\_r() prints all the data I asked for. The odd thing is that the theming fails totally, showing nothing. I have done some experimentation:

```
    $output= theme('table', $header, $rows);
    echo theme('table', $header, $rows);
    print theme('table', $header, $rows);

```

but all of them fail, showing nothing or disrupting drupal globally. How can I show my data in a nice table? I want to avoid writing html code and instead rely on Drupal theming.

# Answer
> 6 votes
The format of arguments to theme functions changed in Drupal 7, instead of

```
$output = theme('table', $header, $rows);

```

you need to use

```
$output = theme('table', array('header' => $header, 'rows' => $rows));

```

or, using a render array,

```
$build = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);
$output = drupal_render($build);

```

---
Tags: 7, theming
---


title: Services 3 Output alter hook

text:
# Question
Title: Services 3 Output alter hook
Are there any hooks to alter the Services modules output. For eg : If I get a result like this for a file object.

```
{
  "fid": "132",
  "uri": "public:\/\/512dab4918036.jpg",
  "filename": "512dab4918036.jpg",
  "filemime": "image\/jpeg",
  "uid": "1",
  "status": 1,
  "timestamp": 1361947464,
  "filesize": 2521,
}

```

I want to limit it for users with certain roles.

I am looking for this as I have made many services resource manually so I don't want to edit them all and simply use the output alter hook to do something.

Is it possible ?

# Answer
The available hooks for Services are documented in the api docs for services

You probably want `hook_services_request_postprocess_alter($controller, $args, $result);` which allows you to change the array of $result any way you want.
> 4 votes

---
Tags: hooks, services, 8
---


# Question
Title: Trigger ajax callback from input field webform
I have a form build with the webform module. When text is entered in the input box in this case webform component 2 I want it to execute a ajax function and put data in a div. However this is not working at the moment. When i connect the ajax to $form\['actions'\]\['submit'\] it does work.But i want it to be stuck to the input box not the submit function. The function is placed in the hook\_form\_alter.

```
$form['#node']->webform['components'][2]['#ajax'] = array(
  'callback' => 'callback function',
  'wrapper' => '#foo',
  'method' => 'replace',
  'effect' => 'fade',
);

```

# Answer
> 0 votes
I figured out you cannot attach ajax to webform components you need to add them to $form\['submitted'\]

```
$form['submitted']['TEXTFIELDNAME']['#ajax'] = array(
  'callback' => 'callback function',
  'wrapper' => '#foo',
  'method' => 'replace',
  'effect' => 'fade',
);

```

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


# Question
Title: How to make nice content manager approval page?
The client wants to allow users to upload files but only publish the ones that are approved by the content managers. The content managers want a nice way to flip through pictures and quickly accept or reject pictures.

I created a view where someone can flip through unpublished pictures.

Is there a way to add a check box that corresponds to the the published checkbox in the add content? Basically be able to edit the content within this simple view, but all they would need to edit is published/unpublished.

Any Ideas. Hopefully there is a way to do this without another module, but I'm not picky at this point.

# Answer
> 4 votes
I guess Views Bulk Operations (VBO) may help you here. Here is a quote about it (from the module's project page):

> ... This module augments Views by allowing bulk operations to be executed on the displayed rows. It does so by showing a checkbox in front of each node, and adding a select box containing operations that can be applied. Drupal Core or Rules actions can be used.

---
Tags: views, nodes
---


# Question
Title: how to load my css and js first on drupal 7
I'm using Omega theme as base theme and created subtheme. I disabled the "responsive grid" in subtheme.

It works perfectly in screen width 960px as "DEFAULT (960PX) LAYOUT SETTING (Normal)".

When i load the same website in Wide screen more than 1200 px, first it loads "DEFAULT (960PX) LAYOUT SETTING (Normal)" after it override my CSS which i wrote of Wide screen.

How to load my CSS and JS first to make sure the CSS will work for wide screen as well.

# Answer
> 0 votes
My advice is that you enable the responsive grid and then you could apply CSS to the site by using the following basic format. If you read my inline comments, I think you'll get the gist of it.

There is an alternate way to do this where each breakpoint's css is put in its own file. This involves adding some lines to your subtheme's .info file and is pretty well documented here.

This approach may seem overwhelming to you (it did to me at first), but you'll be making a responsive site (one that looks good on all devices) which is a really great skill to have. You test the different breakpoints by resizing your browser window or using browser developer tools. You should also test on actual devices, but I do my initial design and testing by just resizing my window.

```
/*CSS for genchstyle theme - all breakpoints*/

/*GLOBAL STYLE INFO FOR ALL DISPLAY BREAKPOINTS*/

    h2 {
    color:rgb(204,204,204);
    font-family:Arial,Helvetica,sans-serif;
    font-size:1.2em;
    }

/*MEDIA QUERIES FOR RESPONSIVE DESIGNS*/

/*Wide - larger computer screens and retina devices*/
@media all and (min-width: 1200px) {

    body{
    background:#000 url(../../../../default/files/grate-wide.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:100%;
    }

}

/*Normal - iPad horizontal & small-to-medium computer screens*/
@media all and (max-width: 1200px) {

    body{
    background:#000 url(../../../../default/files/grate-normal.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:100%;
    }

}

/*Narrow - iPad vertical & kindle fire, etc.*/
@media all and (max-width: 960px) {

    body{
    background:#000 url(../../../../default/files/grate-narrow.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:90%;
    }

}

/*Fluid - Small Mobile Devices & smart phones*/
@media all and (max-width: 720px) {

/*Background - mobile*/

    body{
    background:#000 url(../../../../default/files/grate-fluid.jpg) repeat;
    background-attachment:fixed;
    width:100%;
    font-size:90%;
    }

}

```

You can see this in action on the site I'm building (it's an omega subtheme).

I love Omega and I think you made a really smart choice basing your subtheme on it. But it's the responsive grid that makes it great! Just my opinion.

Oh - and I'm just naming this css file global.css and I'm storing it in my sites/all/themes/mytheme/css directory.

---
Tags: theming
---