# Question
Title: Why does the Node reference module search only for node titles?
I have two content types: *Type A* and *Type B*. *Type A* has 3 fields: title, location, and zip code.

I want to get references to *Type A* in a field for *Type B*. I have tried using the Node reference and the Entity reference modules, but they allow only to get options in autocomplete when I write the title of a *Type A* node. I want to get a list of all the *Type A* nodes with the zip code entered in the field.

# Answer
> 1 votes
You should use tokens and autonodetitle modules.

After enabling tokens and automatic node title , go to Stucture-\>content types -\> edit **(type A)** content type.
If you scroll below you will see an option Automatic title generation .
Click on 'automatic title generation' you will see an **Pattern for the title** and list of options containing token list
like curent user, current date, current page, node , random etc.
Click on node and find the token related to node Type A.
Like for the field location and field zip there will be token similar to this \[node:field-zip\],\[node:field-location\]
add this into **pattern for title** field. Now you can check the Type B autocomplete entity reference field for type A . you will find that as title is changed the entity reference field has location and zip in the title.

# Answer
> 0 votes
Text or Nodereference this module may solve your issue

> It simply adds a new widget and a new formatter for the text fields provided by the great text.module from the CCK project.
>
> The widget has autocompleting on both the existing field data and any existing node titles (you may want to filter this on specific content type(s), though, which is possible.) The formatter checks if a node exists with the title that is stored to the textfield, then it is displayed as a link to that node (if that textfield's widget is limited for any content type(s), then the target node must be one of the specified content type's, though).

# Answer
> 0 votes
The main issue here is that the node reference widget has no idea of the zip code field because it hasn't been submitted into the database yet. Yes, you have typed information into it, but until the form is submitted, it's still just out there with the client.

What you will probably have to do is code up some custom AJAX/AHAH for your form to look when your user has entered information into the zip code field, then pass that to drupal and then have drupal return your node information based upon that filter (See Views) and either repopulate or initially populate a drop down list of nodes.

Lots of information on this can be found in the Drupal Form API Reference and most probably some code examples in the aptly titled Examples Module.

Side note: If these were all node references, you could also investigate the Hierarchical Select Module.

---
Tags: entities, nodes
---


title: BeautyTips + Jquery Update not working

text:
# Question
Title: BeautyTips + Jquery Update not working
Is it possible to get BeautyTips working with a new version of jquery 1.7 or 1.8.

Firebug returns the error.

```
`Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'curCSS'` - jquery.bt.min.js?v=0.9.5-rc1:97

```

Is there a new version of jquery.bt.min.js that will work?

# Answer
> 1 votes
According to the jQuery blog, the function curCSS was deprecated in jQuery 1.8:

> $.curCSS: This method was simply an alias for jQuery.css() from jQuery 1.3 onward. Although it has never been part of the documented API, some external code has been known to use it, perhaps thinking it was “more efficient.” Now it’s “more gone.”

but since its simply an alias its possible to patch the beauty tips plugin to fix this. There is a patch here on Drupal.org that does just this and its been committed to the dev release. Its not ideal as you have to patch the library to get this to work but its really your only strategy since the beautytips plugin hasn't been upgraded for the newer versions of jQuery.

---
Tags: 7, ajax
---


title: Bypass customer profile duplication

text:
# Question
Title: Bypass customer profile duplication
How do you bypass customer profile duplication when editing a profile that has already been referenced on a few orders.

* I know it is a design feature to protect historic data as mentioned here
* I am editing the profile trough the ui

Is there a easy way to achieve this without module editing?

# Answer
Since you've already linked my article on the topic, I'll just answer definitively here that there is no way to do this through the user interface. The code I show in that article is the only way to bypass customer profile duplication, but if you wanted to you could apply it to a user interface in a custom module. Just be careful you don't give administrators more control than is safe for your historical order data.
> 1 votes

---
Tags: commerce
---


# Question
Title: Create custom language not based on english
I would like to add Canadian French as language, since there already is a French version of the site it would be very handy to just start from there.

When you create a new custom language it always copies the english language into the new one, you cannot select the language it should copy from. I also tried to set the default language to french and then create the new language but that doesn't change anything.

Anyone an idea how to do something like this? Or an easy way to switch the english for french after the language is copied?

# Answer
Be sure to create the new custom language:

admin/config/regional/language (use fr-CA language code)

Get the French po files from here:

https://localize.drupal.org/translate/languages/fr

Then import (choose Canadian French):

admin/config/regional/translate/import
> 1 votes

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


# Question
Title: Taxonomy term: "The requested page "xx" could not be found."
In a taxonomy vocabulary, I have terms such as: *groups/arts* (parent level.)

The URL alias of the term is set as *groups/arts* (Organic Groups.)

But when I want to access the page *www.example.com/groups/arts,* I get a "The requested page "/groups/arts" could not be found" error message. This is true regardless of *pathauto* being enabled or not.

If instead of writing the url I click on the view tab of the taxonomy term edit page (which should bring me to the page) I am sent instead to the root directory (www.example.com)

This issue started after I began using the default view provided for taxonomy. I used the view for for a different vocabulary that works well (the terms have their own pages that show.) However, if I disable the view then I get the same no page found result.

Is it possible that the taxonomy view messed up? Or can one not use it twice on the same site for different vocabularies?

Any pointer on those issues greatly appreciated. Thanks. :)

Any idea on how to fix this? Is it a .htaccess file issue? If I knew where to start looking that would already be a big help. Thank you. :)

# Answer
> 0 votes
I will answer my own question on this one:

On a site that has several vocabularies, enabling the selection of one of those vocabularies in the contextual filer of the default taxonomy view, removes the paths assigned to the terms of other vocabularies (those that have nothing to do with the view.) Those paths then default to the root directory and the term pages can no longer be found (or used in another view, etc.)

Un-selecting the vocabulary returns functionality to the term paths of other vocabularies but also allows the existing view to be displayed on all vocabulary term pages (this appears to be functioning as designed however.)

It appears to be a bug in the taxonomy module for which there is no fix. :(

---
Tags: taxonomy-terms, organic-groups
---


# Question
Title: Is custom token module sustainable for masive use?
Is the Custom Token module sustainable for massive use or should I create custom module?

Custom Token will be used for generating URL path, "massive use" means hundreds or thousands of nodes created per day.

# Answer
> 0 votes
In general - no, this shouldn't be a performance issue for your use case. The main problem identified with token module and pathauto is in generating the Token UI screen when dealing with a large number of tokens. There are good discussions on this here on stackexchange but I've also found that using the token tweaks module can resolve most of these.

In your use case case, your using just one token to generate the URL path which is then saved to the path alias table, a table optimized and indexed for performance. The only real demand is on token implementation but this is only done once, when saving the article and you're using objects that are already loaded (ex. $user, $node-\>nid) to generate it so it won't be a performance issue.

---
Tags: 7, tokens
---


title: jQuery Toggle not working in Drupal

text:
# Question
Title: jQuery Toggle not working in Drupal
**Problem**

I'm using jQuery toggle to make one block appear when another is clicked. The code works in jsfiddle but doesn't in Drupal.

**Set-Up**

I have a node with two blocks on it, applytoggle and tellafriend. Apply toggle:

```
<div class="applytoggle">
    //*Other stuff*
</div>

```

Tellafriend:

```
<div id="block-tellafriend-tellafriend-form" class="block block-tellafriend"></div>

```

In my template file I add the following script :

```
function mytheme_preprocess_page (&$vars) {
  drupal_add_js('sites/all/themes/tefltheme/toggle.js', 'file');

```

Which looks like this:

```
(function ($) {
    $('div.applytoggle').click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
    });
})(jQuery);

```

This works great in jsfiddle - http://jsfiddle.net/dr9vG/, but doesn't in my actual page. The script is loaded successfully and I've got other jQuery scripts loaded and running the same way which work (not related, different objects). Why doesn't this work?

# Answer
> 5 votes
Most likely because the JS code you write in JSFiddle is automatically run when the document is ready; the same isn't true in a normal environment, you need to be explicit:

```
(function ($) {
  $(function() {
    $('div.applytoggle').click(function() {
      $('.applytoggle_title, .block-tellafriend').toggle();
    });
  });
})(jQuery);

```

But to be properly *Drupal* you should use behaviors:

```
(function ($) {
  Drupal.behaviors.myToggle = {
    attach: function(context, settings) {
      $('div.applytoggle', context).click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
      });
    }
  };
})(jQuery);

```

---
Tags: blocks, javascript
---


# Question
Title: Why required form field has #required=FALSE on theme level?
I have a form with managed file field. Form has single field. I have declared this field as required and indeed after submit without file I have an error: Field is required.

I wanted to add HTML5 validation to this field, but in my custom theme\_file implementation $variables array has `#required => FALSE` for this field...

I have even red asterisk above this input field so I truly don't know what is wrong..

My custom theme\_file:

```
function custom_file($variables) {
    if (! _custom_isMyTheme()) {
        return theme_file($variables);
    }

    $tpl = <<<HTML
    <div class="inputFile" style="width:390px; height:36px;">
        <div class="inputFileContainer">
            <div class="inputFileField"></div>
            <div class="inputFileButton">%s</div>
        </div>
        %s
    </div>
HTML;
    dpm($variables);//devel shows #required property as FALSE
    return sprintf($tpl, t('Select'), theme_file($variables));
}

```

# Answer
> 2 votes
In short, the `hidden` input field that stores the file ID (fid) is what is required, but the displayed file upload element isn't. The actual "displayed" element is added to that form element in `file_managed_file_process()` in `file.module`. Specifically, check out line 440 of that file:

```
  // The file upload field itself.
  $element['upload'] = array(
    '#name' => 'files[' . implode('_', $element['#parents']) . ']',
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#title_display' => 'invisible',
    '#size' => $element['#size'],
    '#theme_wrappers' => array(),
    '#weight' => -10,
  );

```

This has no `#required` property, and so therefore defaults to `FALSE`. If you `dpm()` your element earlier in the process (before it's expanded to include more hidden elements and attach the necessary javascript and CSS to be a full-fledged "managed file" element) you'll see your `#required => TRUE`.

I would add an additional function to the `#process` property of your form element, which will run after `file_managed_file_process()`. In it, you can check if the original element had `#required => TRUE` and then also set that on the `$element['upload']` item. I haven't tried it, but I think that would get you what you want.

**Edit:** It would be wiser to do this in `#after_build` and not just append to `#process`. Here's an example:

```
<?php

function my_form_builder($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'Upload a File',
    '#required' => TRUE,
    '#after_build' => array('my_file_element_after_build')
  );

  return $form;
}

function my_file_element_after_build($element, &$form_state) {
  // Set the 'file' element to have the same #required property as its original form element.
  $element['upload']['#required'] = $element['#required'];
  return $element;
}

?>

```

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


# Question
Title: Best practice for language key for "und" in hook_form_alter
I'm modifying in a form in my custom module. Code looks like:

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

    if ($form_id == "someID") {

        $form['field_charity_author']['und'][0]['value']['#value'] = arg(3);
        //$form['field_charity_author']['#type'] = 'hidden';

    }

}

```

However, I think hard-coding `und` is bad. What should be the proper way to modify form fields properly in this case?

# Answer
Unfortunately, your self-answer is not so universal. Field language and node language are not the same things.
Field language is needed only if you are using Field Translation API (for example Entity translation). When you start using it, some fields are converted to translatable.

Translatable fields have language code, which really makes sense. But if the field is not translatable, the language code will always be (and for all content types, entities, etc) — `LANGUAGE_NONE` (best to use the constant `LANGUAGE_NONE` and not the string `'und'`).
So with your solution you can get a situation when a node is Russian, but a field of the node uses `LANGUAGE_NONE`.
Happily, fields are attached to the form with `'#language'` key, which always contains the correct language code.

```
$lang = $form['FIELDNAME']['#language'];
$form['FIELDNAME'][$lang][0]['value']['#value'] = $value;

```

If you have no access to attached form, Field Language API functions can be useful.
> 40 votes

# Answer
If you know the entity type and bundle use something like the following code, which calls field\_language().

```
$field_language = field_language('node', $node, 'field_charity_author');
$form['field_charity_author'][$field_language][0]['value']['#value'] = arg(3);

```

It will figure out the right language, and will work in multilingual sites.

Also have a look at field\_get\_items().
> 10 votes

# Answer
The whole `und` deal is one of the more annoying things in Drupal 7 that didn't work as well in practice as when it was designed.

Anyways you can get the first language using `array_keys` like this:

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

  if ($form_id == "someID") {
      $langs = array_keys($form['field_charity_author']);
      $form['field_charity_author'][$langs[0]][0]['value']['#value'] = arg(3);
  }
}

```

That should work all the time.
> 4 votes

# Answer
*(Answering my own question in case it helps someone. The answer worked for me.)*

I can write following line to get the language:

```
$lang = $form['language']['#value'];    //  Instead of "und"

```
> 0 votes

# Answer
re: kalabro's answer

his code didn't work for me - my code is a little different

```
$lang = $form['FIELDNAME']['#language'];
$form['FIELDNAME'][$lang]['#value'] = $value;

```

\[$lang\]\[0\] returned "u" but the full value of \[$lang\] is "und" and I did not need the \['value'\] either, because $form\['FIELDNAME'\]\['#language'\] was not an array, it was a string.
> 0 votes

---
Tags: 7, entities, hooks, i18n-l10n
---


# Question
Title: What is the difference between limit(1) and range(0, 1)?
In a query I tried using `limit(1)`; I got a WSOD, but when I use `range(0,1)` I don't get any WSOD.

What is the basic difference between `limit(1)` and `range(0, 1)`?

# Answer
> 2 votes
Base difference is that `range` is a method of `SelectQuery` class, and `limit` isn't.

Some APIs can extend SelectQuery and add `limit`. For example `$query->extendQuery('PagerDefault')` will return object of `PagerDefault` class that has `limit` method defined.

It may result in a syntax looking like `limit()` is invoked on `SelectQuery`, when in fact it isn't:

```
$query = db_select('node', 'n')
      ->fields('n')
      ->condition('type','problem','=')
      ->extend('PagerDefault')
      ->limit(20);

```

---
Tags: 7, database
---


title: Calculate bonuses for users

text:
# Question
Title: Calculate bonuses for users
I'm trying to implement bonus calculation system to my website. It should calculate bonuses for users.

This is how it should work:

* User1 can get 2% bonus
* User2 has for example 100 points
* The bonus for User1 is calculated as User2 points * User1 bonus % * level x%

There are different levels of bonuses.

* Level1 x% bonus: User1 gets amount x% of bonus from three users who have registered after User1. So User1 gets bonus from User2, User3 and User4.
* Level2 y% bonus: User1 gets amount y% of bonus from nine who have registered after User1, User2, User3 and User4. Like this: User1 gets bonus from User5, User6, User7, User8, User9, User10, User11 and User 12.

There are 9 levels and it continues like explained above. Users are multiplicated by 3 so users where User1 gets bonuses are: 3, 9, 27, 81.. etc.

Any ideas how to implement bonus calculation? I was thinking about using the Rules module, but I am not sure how it can handle this. Does performance suffer, if there are ten of thousands or even more users?

The Userpoints module will be used.

# Answer
> 1 votes
Treat bonuses as fields, and use Computed Field to manage calculations:

> Computed Field is a very powerful CCK 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. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

In user's profile, keep an Entity Reference to all users that registered from his links or gave his name at registration. Use simple recursion or deep scan to make actual computation, and you're there.

---
Tags: 7, users, rules, userpoints
---


# Question
Title: Does having too many content types negatively affect site speed and performance?
I building a site that could potentially utilize 20 different content types. The content types are very similar, but may only utilize one or two fields that are unique to that content type, and they would use the same 5 fields with each other. Does having 20 different content types slow the site down? Would it be better to build one content type and display the unique fields on a case by case basis using FAPI or the conditional fields module?

# Answer
The number of content types does not affect the performance of a Drupal site.

Sharing fields among the content types does affect the performance. This is because of the way CCK stores fields.

* If the field is not shared and allows only one entry, it is stored along with other such fields in a table designated for that content type. That way, all such fields can be loaded in a single query.
* If the field is shared or allows multiple entries, the field is stored in its own table, making an extra query (or join) per field necessary to load the field.
> 18 votes

# Answer
I would check out the performance of my database server and queries, web host, modules, and custom code before I would worry about having too many content types.

I have a few sites that have several dozen content types and they are screaming fast. Some of these content-types contain 100,000+ nodes as well.
> 1 votes

# Answer
I can't think of a reason why many content types would dramatically affect site performance. Maybe if you build views that display data from many different content types, the queries would be a bit slower, but as Criticguy says, other factors are much more important.

That said... Things to consider before creating a large number of content types, are user experience and maintainability.

I don't know which users are going to create content in your site, but you have to make sure that those users understand the difference between the content types. A large number of types can turn out to be a huge threshold if the end user doesn't know which one he needs to accomplish his task.

For maintainability, it can be a lot of work if you have to alter all content types in a later stage. Something as simple as adding a field or changing the comment settings suddenly becomes a tedious job.

A way to avoid both problems described above, would be to create a single content type which contains all fields, and use taxonomy terms to identify the type of content. To improve the user experience, you could use the Conditional Fields module to hide and show certain fields based on the taxonomy term (or other form values).
> 1 votes

# Answer
You could also merge the content types that share most data fields and organize the "differences" into groups inside the manage fields section at Content/Content Types.

If it appears too unwieldy you could use the Vertical Tabs module to clean it all up and keep your users from feeling overwhelmed. http://drupal.org/project/vertical\_tabs

I think simplifying the editorial flow for your authors is a good thing.
> 0 votes

# Answer
You are probably using 19 extra content types that you could save in different ways.

The first one, for example, using all the fields in the same, unique, content type, but giving the user the choice to fulfill them or not, depending on your/their needs.

The other is hiding the fields, using the nodeapi or a module like conditional fields: https://drupal.org/project/conditional\_fields

Depending on the context, project, requirements, you could find other ways or solutions.
> -1 votes

---
Tags: 6, performance
---


# Question
Title: Why submit button is losing disabled attribute after deletion of uploaded file?
The task is simple: submit button must be enabled only if file is attached to file input.

The form code:

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

    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['xml_file'] = array(
        '#field_prefix'      => '<span class="description">'.t('Only XML files are allowed').'</span>',
        '#type'              => 'managed_file',
        '#title'             => '',
        '#default_value'     => '',
        '#upload_location'   => CUSTOM_MODULE_UPLOAD_DIR,
        '#upload_validators' => array('file_validate_extensions' => array('xml')),
        '#required'          => TRUE,
    );

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

    return $form;
}

```

The form alter code:

```
function custom_module_FORM_ID_form_alter(&$form, &$form_state, $form_id) {
    if (! isset($form_state['clicked_button'])
        || $form_state['clicked_button']['#name'] == 'xml_file_remove_button') {
        $form['submit']['#disabled'] = TRUE;
    }
}

```

It works, but when I removed uploaded file by Remove button, refreshed form has enabled submit button, even if I am sure that above code was executed. What am I doing wrong?

Use case:

1. Go to page with a form, submit button is disabled - ok
2. Uploaded sample xml file:

3. Click the Remove button, form is refreshed but submit button is enabled instead of disabled

# Answer
> 1 votes
You can't do it, because on remove event, only HTML for file input field is reloaded. There is a need of using custom AJAX callback for this (such as ajaxSuccess). I don't know nothing about Drupal Ajax callbacks for this type of event too.

---
Tags: 7, forms
---


# Question
Title: How to implement a multiple (AJAX) field collection with the FAPI
Background: I have a field colleciton containing two fields. This field collection is attached to a profile entity and its number set to unlimited.

I am currently retrieving this field from the profile form to use it a custom form.

I get the form array and it is displayed correctly, but when I click on the button to add another element, I got a popup displaying this error:

> EntityMalformedException : Missing bundle property on entity of typefield\_collection\_item dans entity\_extract\_ids() (ligne 7663 dans /drupal\_project/includes/common.inc).

Anyone have a clue or hint of what is going on behing the scene ? Maybe a solution to solve this issue ?

Update: the form I am making is a ctools multistep form. I am opened to alternatives such as Dave Reid's multifield.

# Answer
> 1 votes
So, I followed the answer in the other thread Clive linked and this did the trick:

```
  $profile = new stdclass();
  $profile->type = 'some_profile_type';
  field_attach_form('profile2', $profile, $form, $form_state, LANGUAGE_NONE);

```

EDIT: Well, this is fixing the issue because it enables the form to use its widgets. But it remains a problem, the button part of the array is passed in form\_state as a value, and I have to delete it manually...

---
Tags: 7, ajax, entities
---


# Question
Title: translate(localize) specific title of web form use preprocess func
I have specific webform call careers , i have use webform localization model but the model does not translate the node title , some one told me to use preprocess node func. but i did not now how to create theme i try to write some thing like this

```
function [themeName]_preprocess_page(&$variables) {
  if($node['id'] == 6) {
  $node['title'] = t($node['title']);
    }

```

But it does not work

# Answer
> 1 votes
The code doesn't work because the function receives only a parameter, and that is not `$node`. The correct code should eventually be the following one.

```
function mymodule_preprocess_page(&$variables) {
  if(!empty($variables['node']) && $variables['node']->nid == 6) {
    $variables['title'] = t($variables['title']);
  }
}

```

I am assuming you want to change the title when the node ID is equal to 6.

---
Tags: 7
---


title: How to alter an existing Views display?

text:
# Question
Title: How to alter an existing Views display?
I know in order to create views displays you simply declare it as:

```
  $view = views_get_view('AN_EXISING_VIEW', TRUE);

  $handler = $view->new_display('page', 'YOUR_DISPLAY_NAME', 'YOUR_DISPLAY_MACHINE_NAME');
  $handler->display->display_options['title'] = 'TITLE';
  ...
  views_save_view($view);

```

You can do this in `hook_enable` in your install file or using `hook_views_default_views`

All I need is however to programatically alter an existing view display of a Workbench Moderation module (workbench\_moderation): 'YOUR\_DISPLAY\_NAME' and 'DEFAULT' in order add other fields and permissions on those fields.

My questions are:

1. How do I effectivelly get the specific display: e.g. `$views->get_display`?
2. How do I save it so that will not mess the views caches?

# Answer
> 1 votes
Views provided by a module are defined using `hook_views_default_views` \- and as almost anything, they can be modified using "alter" version of this hook, namely `hook_views_default_views_alter`:

Alter default views defined by other modules.

> This hook is called right before all default views are cached to the database. It takes a keyed array of views by reference.
>
> Example usage to add a field to a view:

```
$handler =& $view->display['DISPLAY_ID']->handler;
// Add the user name field to the view.
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;

```

Source code from API help page linked above.

---
Tags: views
---


title: Adding Page break to multi step form

text:
# Question
Title: Adding Page break to multi step form
I am having somewhat of a problem, I am trying to use ajax commands to go to the next case on my form. I dont really understand how to complete this and ive tried numerous ways without any success. Basically what im trying to do in my ajax callback load my preloader function into the #neato\_form div's with a 10 second delay and then make it go to case 2 which is step 2 on my form.

Ive included my ajax callback since this is the main problem. Along with my form and submit function in case ive done something wrong there.

Any Suggestions is greatly appreciated.

Ajax commands

```
function neato_form_ajax_callback($form, &$form_state)
{
    $commands = array();

    $commands[] = array(
        'command' => 'mortgage_response',
        'leadstatus' => 'success',
    );

    $commands[] = ajax_command_replace('#neato_form', preloader());
    $commands[] = ajax_command_invoke(NULL, "preloader");

    if($commands[0]['leadstatus'] == 'success'){

        $commands[] = ajax_command_replace('#neato_form', $form_state['step2']);
    }

    return array('#type' => 'ajax', '#commands' => $commands);
}

```

Form and Submit function

```
function neato_form($form, &$form_state)
{
    $form_state['step'] = isset($form_state['step']) ? $form_state['step'] : 1;

    $form['#prefix'] = '<div id="neato_form">';
    $form['#suffix'] = '</div>';

    switch($form_state['step'])
    {
        // Step 1
        case 1:
            $default_value = '';
            if(isset($form_state['values']['step_1']))
            {
                $default_value = $form_state['values']['step_1'];
            }
            elseif(isset($form_state['storage']['step_1']))
            {
                $default_value = $form_state['storage']['step_1'];
            }

            $form['step_1'] = array
            (
                '#type' => 'textfield',
                '#title' => t('Step 1'),
                '#required' => TRUE,
                '#default_value' => $default_value,
            );
            break;

        // Step 2
        case 2:
            $default_value = '';
            if(isset($form_state['values']['step_2']))
            {
                $default_value = $form_state['values']['step_2'];
            }
            elseif(isset($form_state['storage']['step_2']))
            {
                $default_value = $form_state['storage']['step_2'];
            }

            $form['step_2'] = array
            (
                '#type' => 'textfield',
                '#title' => t('Step 2'),
                '#required' => TRUE,
                '#default_value' => $default_value,
            );

            break;

        // Step 3
        case 3:
            $default_value = '';
            if(isset($form_state['values']['step_3']))
            {
                $default_value = $form_state['values']['step_3'];
            }
            elseif(isset($form_state['storage']['step_3']))
            {
                $default_value = $form_state['storage']['step_3'];
            }

            $form['step_3'] = array
            (
                '#type' => 'textfield',
                '#title' => t('Step 3'),
                '#required' => TRUE,
                '#default_value' => $default_value,
            );

            break;
    }

    $form['buttons'] = array
    (
        '#type' => 'container',
    );

        $form['buttons']['submit'] = array
        (
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#ajax' => array
            (
                'wrapper' => 'neato_form',
                'callback' => 'neato_form_ajax_callback',
            ),
        );

    return $form;
}

function neato_form_back_submit($form, &$form_state)
{
    $form_state['step']--;
    $form_state['rebuild'] = TRUE;
}

function neato_form_submit($form, &$form_state)
{
    $step = $form_state['step'];
    $form_state['storage']['step_' . $step] = $form_state['values']['step_' . $step];

    if(isset($form_state['values']['forward']) && $form_state['values']['op'] == $form_state['values']['forward'])
    {
        $form_state['step']++;
    }
    elseif(isset($form_state['values']['submit']) && $form_state['values']['op'] == $form_state['values']['submit'])
    {

        $items = array($form_state['storage']['step_1'], $form_state['storage']['step_2'], $form_state['storage']['step_3']);
        drupal_set_message(t('My !values', array('!values' => theme('item_list', array('items' => $items)))));

        $form_state['step'] = 1;
        $form_state['storage'] = array();
    }
    $form_state['rebuild'] = TRUE;
}

```

# Answer
I think you should attach your custom ajax preloader function to the form as follows:

```
$form['#attached']['js'] = array(
  array(
    'type'  => 'file',
    'data' => drupal_get_path('module', 'MY_MODULE') . '/js/ajax_preloader.js',
  ),
);

```

**ajax\_preloader.js**

```
(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('#steps-form', context).ajaxStart(function() {
        // ...
      });
      $('#steps-form', context).ajaxSuccess(function() {
        // ...
      });
    }
  };
})(jQuery);

```

alternatively, you can create your custom command (myPreloaderExample)

```
(function($, Drupal) {
  Drupal.ajax.prototype.commands.myPreloaderExample = function(ajax, response, status) {
    $('#steps-form').ajaxStart(function() {
      //...
    });
    $('#steps-form').ajaxSuccess(function() {
      // ...
    });
  };
}(jQuery, Drupal));

```

I'm not sure what your aim is, but if you're going to create a multistep ajax form with the following features:

* Show only the current form item
* Store all previously provided values (allow to preview all the values without loosing them)

You can create this kind of form as follows:

```
/**
 * An example of steps form.
 */
function steps_form($form, &$form_state) {

  // Because we have many fields with the same values, we have to set
  // #tree to be able to access them.
  $form['#tree'] = TRUE;

  $form['steps_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Steps form'),
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="steps-fieldset-wrapper">',
    '#suffix' => '</div>',
  );

  $form['steps_fieldset']['actions'] = array(
    '#type' => 'actions'
  );

  // Build the fieldset with the proper number of steps.
  // Use $form_state['step'] to determine the number of textfields to build.
  if (empty($form_state['step'])) {
    $form_state['step'] = 1;
  }

  // An array with form values.
  if (empty($form_state['storage'])) {
    $form_state['storage'] = array();
  }

  // Define the number of steps.
  $form_state['steps_number'] = 3;

  // build all textfields with steps
  for ($i = 0; $i < $form_state['step']; $i++) {

    // set the type of each previous form item as a hidden. Only last step will be shown.
    $type = ($i == ($form_state['step']-1)) ? 'textfield' : 'hidden';

    // get the default value of step.
    $default_value = isset($form_state['storage'][$i]) ?  $form_state['storage'][$i] : '';

    $form['steps_fieldset']['step'][$i] = array(
      '#type' => $type,
      '#title' => t('Step') . ' ' . ($i+1),
      '#required' => FALSE,
      '#default_value' => $default_value,
    );
  }

  // The next step button.
  if ($form_state['step'] != $form_state['steps_number']) {
    $form['steps_fieldset']['actions']['add_step'] = array(
      '#type' => 'submit',
      '#weight' => '1',
      '#value' => t('Next step'),
      '#submit' => array('steps_form_add_one'),
      '#ajax' => array(
        'callback' => 'steps_form_callback',
        'wrapper' => 'steps-fieldset-wrapper',
      ),
    );
  }

  // The previous step button.
  if ($form_state['step'] > 1) {
    $form['steps_fieldset']['actions']['remove_step'] = array(
      '#type' => 'submit',
      '#weight' => '0',
      '#value' => t('Previous step'),
      '#submit' => array('steps_form_remove_one'),
      '#ajax' => array(
        'callback' => 'steps_form_callback',
        'wrapper' => 'steps-fieldset-wrapper',
      ),
    );
  }

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

  $form['#attached']['js'] = array(
    array(
      'type'  => 'file',
      'data' => drupal_get_path('module', 'MY_MODULE') . '/js/ajax_preloader.js',
    ),
  );
  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with all values in it.
 */
function steps_form_callback($form, $form_state) {

  $commands = array();
  // return the form
  $commands[] = ajax_command_html('#steps-fieldset-wrapper', render($form['steps_fieldset']));
  // add your custom ajax command
  $commands[] = array(
    'command' => 'myPreloaderExample',
    // define some custom variables if you need to
    'someValue' => 'some value',
  );

  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * - save the form value, so the user will be able to preview all previously provided values without loosing them.
 * - increments the step counter.
 * - rebuild the form.
 */
function steps_form_add_one($form, &$form_state) {

  $form_state['storage'][$form_state['step']-1] = $form_state['input']['steps_fieldset']['step'][$form_state['step']-1];
  if ($form_state['step'] < $form_state['steps_number']) {
    $form_state['step']++;
  }
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the step counter and causes a form rebuild.
 */
function steps_form_remove_one($form, &$form_state) {
  if ($form_state['step'] > 1) {
    $form_state['step']--;
  }
  $form_state['rebuild'] = TRUE;
}

/**
 * Final submit handler.
 *
 * Reports what values were finally set.
 */
function steps_form_submit($form, &$form_state) {
  $output = t('All my values: @steps',
    array('@steps' => implode(', ', $form_state['values']['steps_fieldset']['step'])) );
  drupal_set_message($output);
}

```

**Results**
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Looking for a header menu, with drop-down block that list all submenus
I'm looking for a module that can help me to make a menu like this one :

http://www.airbus.com/

I would like a dropdown block, that fit page width to list my submenu, and add content like image infront of menu etc

Is it possible? I'm new on drupal I've tried superfish but it's not the style I want...

# Answer
There are many modules you can use

Tb Mega menu

> TB Mega Menu allows you to create a mega menu with an innovative back-end user interface and synchronized with Drupal core menu.

Om Maxi menu

> "Maximize your main navigation by adding text, images, videos, slideshow, tabs, menu blocks, user info ..."
> 0 votes

---
Tags: routes, navigation
---


# Question
Title: On account creation, the message is not displayed
I try to register in my site; after a successful registration, I get redirected to the home page, but the following message is not displayed.

> Thank you for applying for an account. Your account is currently pending approval by the site administrator.
>
> In the meantime, a welcome message with further instructions has been sent to your e-mail address.

The standard core mail functionality is used, and no hook or rule is used for that registration.

Why doesn't the message appear?

I tried changing theme, but the message is still not appearing. Furthermore:

* The `$message` variable is available in the template file
* I am not using the Boost module; I am using the Mime Mail module to get HTML emails

How do i customize the message in some hooks?

# Answer
A workaround would be to manually create message in `hook_user_insert`, with code like:

```
function mymodule_user_insert(&$edit, $account, $category) {
  drupal_set_message(t('Account created, wait for approval.'), 'status');
}

```

Alternative place is `hook_entity_insert`:

```
function mymodule_entity_insert($entity, $type) {
  if ($type == 'user') {
    drupal_set_message(t('Account created, wait for approval.'), 'status');
  }
}

```

Problem is - it is possible that the same error will hide this one too. Benefit: it's easier to experiment with small custom hook, than to debug core.
> 1 votes

---
Tags: 7, users, emails
---


title: how to resolve ajax call once issue

text:
# Question
Title: how to resolve ajax call once issue
**Drupal code**

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

    drupal_add_js(drupal_get_path('module', 'form_example') . '/js/test.js');

    $form['price_form'] = array(
        '#type' => 'fieldset',
        '#title' => t('Add Item'),
    );

    $form['price_form']['item'] = array(
        '#type' => 'textfield',
        '#title' => 'Item Name?',
        '#size' => 10,
        '#maxlength' => 25,
        '#required' => TRUE,
        '#ajax' => array(
            // #ajax has two required keys: callback and wrapper.
            // 'callback' is a function that will be called when this element changes.
            'callback' => 'form_example_simplest_callback',
            'wrapper' => 'listDiv',
            'effect' => 'fade',
        ),
    );

    $form['price_form']['textfields'] = array(
        '#prefix' => '<div id="listDiv">',
        '#suffix' => '</div>',
        '#markup' => '',
    );

    $form['price_form']['price'] = array(
        '#type' => 'textfield',
        '#title' => 'Item Price?',
        '#size' => 10,
        '#maxlength' => 10,
        '#required' => TRUE,
    );

    $form['price_form']['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
    );
    if (!empty($form_state['values']['item'])) {
        $result = db_query("SELECT * FROM {item} where item_name='" . $form_state['values']['item'] . "'");
        if ($result->rowCount() != 0) {
            $form['price_form']['textfields'] = array(
                '#markup' => 'Already exist',
            );
        } else {
            $form['price_form']['textfields'] = array(
                '#markup' => 'New Item',
            );
        }
    }

    return $form;
}

function form_example_simplest_callback($form, $form_state)
{
    return $form['price_form']['textfields'];
}

```

On blur of item textfield,I am showing status of item whether item\_name exist in database or not.But It is showing perfectly for first time.

As it replaces a form name with 'form\_name-2' after first ajax callback,it is not working afterwards.

How can I resolve this issue?

Thanks in advance

# Answer
> 3 votes
The problem is that you set your wrapper div in `$form['price_form']['textfields']`, but in the AJAX callback you are replacing it with the `$form['textfields']` that does not have it defined. To be safe, keep these guidelines:

1. Never use the same identifier at 2 different depths of an form array, as it leads to mistakes. Be sure to set `'#tree' => TRUE` if you need to use identifier twice, to avoid conflicts.
2. In AJAX callback always return the same element you set `'#prefix' => '<div id="...">` on.
3. Be sure to only define each element once. If you are using

```
$form['price_form']['textfields'] = array(
  '#prefix' => '<div id="listDiv">',
  '#suffix' => '</div>',
  '#markup' => '',
);

```

to define element, don't reset it with `$form['price_form']['textfields'] = array(` later in code. Using `array()` creates new *empty* array effectively deleting everything set earlier. Write directly to it's members like this:

```
$form['price_form']['textfields']['#markup'] = t('Already exist');

```

Of course they are not set in stone, but don't break them unless you know why and what you're doing. In your case, you have `'textfields'` twice, you are setting wrapper on one and returning another. That's why it only works once. Second time there is no element FAPI's AJAX is supposed to replace.

---
Tags: ajax
---


title: Exposing sort breaks order

text:
# Question
Title: Exposing sort breaks order
In my view I am exposing two sort options in the following order: Date \> Newest First Title \> A-Z

When both sort options are exposed it will correctly display the nodes sorted by date but will randomly sort the nodes by title. So for example titles starting with a R will appear for nodes which have titles starting with a D. When I turn off exposing the Title sort it will display correctly. First sorted by date and correctly sorted from A to Z. But I do need to expose the Title sort. So what am I missing? Or is it just a bug?

**My Views settings**

**Sort settings date field**

**Sort settings title field**

# Answer
It's not a bug. Node creation date is stored with hours, minutes and seconds. If you are sorting by creation time, only nodes created in the very same second will ever use secondary sort criteria - Unless you will set granularity:
> 0 votes

---
Tags: views
---


# Question
Title: Hook into update/install process callback (Update manager) - providing a custom message after installing a module from URL
After installing a module from a given URL (on `admin/modules/install`), I can see the following messages:

So it outputs 3 links in the "Next steps" list, but **I would like to hook into the update callback process, extend this list, and provide another link** which points to a callback page defined by my own module, where I can enable the module immediately. I don't need help for the latter, only for **the way to hook into the process of altering/extending the messages** in the result.
After hooking into to the process of generating the output (hooking into the callback process), I will need to know the module's machine name.

This is what the expected result would look like:

OR

OR

**What would be the appropriate way to provide custom messages in the update callback?**

The *"Installation was completed successfully."* text is defined by `update_authorize_install_batch_finished()` in `modules/update/update.authorize.inc` (and gets into `$_SESSION['authorize_results']['page_message']` as an array), and the `"Next steps"` list is provided by `ModuleUpdater::postInstallTasks` in `modules/system/system.updater.inc`.

# Answer
I think the easiest way would be to extend the `ModuleUpdater` class to provide your own `postInstallTasks()` implementation:

```
class MyModuleUpdater extends ModuleUpdater {

  /**
   * Overrides ModuleUpdater::postInstallTasks().
   */
  public function postInstallTasks() {
    return array(
      l(t('Enable @module module', array('@module' => $this->title)), 'admin/modules/enable/' . $this->name),
      l(t('Install another module'), 'admin/modules/install'),
      l(t('Enable newly added modules'), 'admin/modules'),
      l(t('Administration pages'), 'admin'),
    );
  }

}

```

And then implement `hook_updater_info_alter()` to let Drupal know you want to use that class instead of the default:

```
function MYMODULE_updater_info_alter(&$updaters) {
  $updaters['module']['class'] = 'MyModuleUpdater';
}

```

You'll also need to add this to your module's .info file so the new class can be autoloaded:

```
files[] = path/to/MyModuleUpdater.php

```

Once you clear the caches the change should take effect.
> 1 votes

---
Tags: updating, installation
---


title: Preprocess a views template

text:
# Question
Title: Preprocess a views template
I Have a template in my `cart_template` module called `views-view-table--commerce-cart-form.tpl`. Is there a way to create a preprocess function for that template.

What I have tried : `hook_preprocess(&variables, $hook)`, but doing `dpm($hook)` display a lot of weird names like : block, page, views\_view ... etc. which doesn't indicate when the function gets called for my template.

# Answer
> 4 votes
In general, every .tpl.php file has an equivalent preprocess function for it. And, in general, the preprocess function and template files have the same name (in the Drupal sense).

The function you want is `template_preprocess_views_view_table()`. You can place this in a module, or in your theme. Just name it accordingly.

Look at the default preprocess function for how the `$view` gets pulled out and/or `dpm($variables['view'])`. You will likely need to examine it to limit the function to just the view/display you need.

You can also try implementing `MYMODULE_preprocess_views_view_table__commerce_cart_form()` to limit to just that instantiation, but I don't recall if the Views module will do this.

The Theme Developer module can also help out tracking down what preprocess functions get called for each .tpl.php file.

---
Tags: views, commerce, theming
---


title: Views exposed date filters

text:
# Question
Title: Views exposed date filters
Can anyone tell me how I can use 2 Views exposed filters to filter nodes published between the two selected dates?

# Answer
Use the Date Views module that comes shipped with Date. Add a filter to your view using the Date: Date option.

Now you can use the "In Between" option to either select between two specific dates, or relative dates (within the past 30 days of right now). Make sure to check "Expose this filter to views".
> 4 votes

# Answer
You can add 'Content revision: Updated date' filter and another filter (not exposed) which is 'published' - true.
> 0 votes

---
Tags: 7, datetime, views
---


# Question
Title: how to call/using geofield in a custom module
I\`m trying to use the geofield module, and load it with google maps widget in one my custom forms.

Yet i can't find any way to use the form api to display this field.

```
$form['geofield'] = array(
'#title' => 'geofield',
'#type' => 'geofield',
);

```

Any suggestion is welcome, i don't mind reading some docs.

# Answer
> 2 votes
Geofield module is rather complex module which adds a lat/long fieldset and so many other stuff such as adding new fields, validation, etc.

Anyway, you can create a latitude and longitude input field using the `#type => 'geofield_latlon'`.

```
$form['geofield'] = array(
  '#title' => 'geofield',
  '#type' => 'geofield_latlon',
);

```

Note that this will return a generic longitude latitude form. NOT a Google Maps choose-location field. See geofield.elements.inc for more information on how this element is validated and themed.

**Update**: I forgot to mention that the above element is available in the 7.x-2.x branch.

---
Tags: forms, location
---


title: How to unset a field in views?

text:
# Question
Title: How to unset a field in views?
How can I unset a view field based on value of some other field in the same view ? I cant use views php module ? Is there any other option for it?

# Answer
use hook\_view\_pre\_render and in this, you need to check for that value in if condition...
> 2 votes

---
Tags: 7, views
---


title: Reusing a node form in a separate page

text:
# Question
Title: Reusing a node form in a separate page
I have a module, and I want to have a page defined in hook\_menu, that shows the add form for a specific content type, with some modifications to the form.

So far it's working, and even saving the new node, but only with the default values I'm setting in the code, i.e. it's not picking up anything the user types into the form. I checked and `$form_state['input']` contains the inputted values, but `$form_state['values']` doesn't, so the new node gets saved wrong.

Here's the relevant code:

```
function mymodule_menu() {
  return array(
    'admin/content/myadd/%' => array(
      'title' => 'my custom add page',
      'page callback' => 'mymodule_node_add',
      'page arguments' => array(3),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
    ),
  );
}

function mymodule_node_add() {
  module_load_include('inc', 'node', 'node.pages');

  //I'm doing a print here instead of returning because I'm calling this page
  //in an AJAX popup, so I don't want the whole page to output, only the form.
  print render(drupal_get_form('mymodule_node_add_form'));
}

function mymodule_node_add_form($form, &$form_state) {
  if (!isset($form_state['node']) {
    global $user;
    $node = (object) array(
      'uid' => $user->uid,
      'type' => 'mycontenttype',
      'language' => LANGUAGE_NONE,
    );

    //this is setting a default value
    $node->myfield = array(LANGUAGE_NONE => array(array('value' => arg(3))));

    $form_state['build_info']['args'] = array($node);

    $form = drupal_build_form('mycontenttype_node_form', $form_state);
    $form['actions']['submit']['#submit'][0] = 'mymodule_node_add_form_submit';
    //there's a lot more customization of the form here, like adding fields, etc.
  }

  return $form;
}

function mymodule_node_add_form_submit($form, &$form_state) {
  //here's where $form_state['input'] is correct but $form_state['values'] isn't.

  $node = node_form_submit_build_node($form, $form_state);
  node_save($node);
  $form_state['values']['nid'] = $node->nid;
  $form_state['nid'] = $node->nid;
  $form_state['redirect'] = 'some/other/page';
}

```

So, am I doing something wrong here? Should I be concerned about form ids being wrong? (my form's id is `mymodule_node_add_form`, but the actual form might output `mycontenttype_node_form`), would this affect me?

# Answer
```
function mymodule_node_add() {
 module_load_include('inc', 'node', 'node.pages');

  //I'm doing a print here instead of returning because I'm calling this page
  //in an AJAX popup, so I don't want the whole page to output, only the form.
  $form = node_add($node_type);//You need to pass content type here. THat's it.
  print render(drupal_get_form('mymodule_node_add_form'));
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: What privileges should a MySQL user have?
When I am creating a user for my Drupal in cPanel, it asks me to check all privileges. What privileges should be enabled, to make Drupal work correctly?

Currently, my user has all privileges except *Drop permission*.

# Answer
> 3 votes
For development you'll need essentially everything - including drop. Once you go live, drop is generally not needed.

That said, if you're allowing delete - for instance - then drop isn't much more drastic. If someone owns your server, deleting all the rows from your tables is pretty much as bad as dropping a table - either way, the only good fallback is proper backups.

Setup your database user to only be allowed to connect from the host Drupal is running on. And make sure if that host has ssh allowed, you're using keys, and not just username/password, and you should be pretty good.

# Answer
> 2 votes
Drupal 7 needs this permissions for work correctly: SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES, CREATE TEMPORARY TABLES

# Answer
> 1 votes
There are really two issues here.

One is the requirements that core Drupal needs. The other is requirements that non-core modules need.

You can determine what core Drupal needs, but the non-core modules can be a little tougher.

Since I may not know what I may need in the future, or what a client may install once they get the keys to the site, I will give a localhost-only user all permissions except for **GRANT**.

---
Tags: 7, database
---


title: Required database permissions

text:
# Question
Title: Required database permissions
I have to make a new install for Drupal 7 and i need to request the database space on Oracle DB to the DB guy, who wants to know exactly which permissions should have the drupal account that will handle the database.

I have read a lot do documentation, and everywhere is just said that the account for the database should have full privileges. I have told this to the DB guy and he refused that statement, arguing for example that Drupal will not need the "drop database" privilege, as an example.

So my question is: where can I find the exact minimum list of database privileges that Drupal needs to work properly?

# Answer
> 6 votes
There's no official documentation for Oracle (I don't think), but INSTALL.mysql.txt states you need the following permissions for MySQL in Drupal 7:

```
SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER

```

I came across an INSTALL.oracle.txt on http://drupalcode.org, but I can't vouch for it's accuracy. It says to run the following with regards to permissions:

```
grant dba, create any trigger, drop any table, select any table, select any sequence, create user to drupal identified by drupal;
grant connect, resource to drupal with admin option;
alter user drupal default tablespace users temporary tablespace temp;

```

Show both of those files to your DBA, it should be enough for him to go on.

# Answer
> 1 votes
Drupal 7 needs more permissions for work correctly if you are using modules like Views, the correct list is:

SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, LOCK TABLES, CREATE TEMPORARY TABLES

---
Tags: 7, users, database
---


# Question
Title: Form Alter: How to check if a node has a Field Type
My module provides a field. In `hook_form_alter()` I need to change only those nodes that have this field set up. (I can't operate use `hook_field_form_alter()` because it does operates changes for other things than my own field.)

How can check if my field belongs to the node?
Is there an easy function to check if the field type exists in `$form`?

Otherwise, if I need to look at `$form` the problem is that I can't know the machine name used for the field by the admin/drupal as it looks like something like `$form['my_field_namedbyuser']`.

# Answer
If you are searching for specific field then see the code below

```
 function hook_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'form_id_name') {
        $abc = array();
        foreach ( $form_state['field'] as $key => $value ) {
            $abc[$key] = $key;
        };
}
    }

```

From this $abc variable you will get all the field name and then you can check from this array to see if the field you want exists or not using any of the php functions.
For e.g. you can use `array_key_exists('field_name', $abc);`
> 3 votes

# Answer
I have found this other solution as well if this can help someone:

* Set up a new variable in $form\_state of hook\_mymodule\_field\_widget\_mywidget\_form\_alter
* Check for this variable in mymodule\_form\_alter

```
function mymodule_field_widget_mywidget_form_alter(&$element, &$form_state, $context){
$form_state['IsMyField']['#value'] = TRUE;
}

function mymodule_form_alter(&$form, $form_state, $form_id)
if ($form_state['IsMyField']['#value']  == TRUE ) {
    //My CODE HERE
}

```
> 1 votes

---
Tags: forms
---


title: Can I use the Twig template engine?

text:
# Question
Title: Can I use the Twig template engine?
I do a lot of Django development and I like their templating language. Twig, the new templating engine in Drupal 8, looks very much like it.

How can I use Twig in Drupal 7 or even Drupal 6?

# Answer
Yes, you can, here is an article about my own experience with it, working with Bootstrap http://makina-corpus.com/blog/metier/2015/develop-with-twig-in-drupal-7

So http://www.drupal.org/project/tfd7 is the way to go if you want to write template files with Twig syntax, it must be moved to `theme/engines`. Note that development is now happening at https://github.com/TFD7/TFD7 and documentation is at http://tfd7.rocks.

Don't be confused with the project https://drupal.org/project/twig, unfortunately, it is only an input filter because modules cannot provide theme engines in Drupal 7 (due to license reasons it seems).
> 13 votes

---
Tags: 7, theming
---


# Question
Title: Watchdog errors with location = http://default/index.php
Looking through recent log messages, I've got a number of errors with no referrer listed, and showing location as being `http://default/index.php` (instead of `http://mysite.com/some/page`). They all seem to be triggered by "Anonymous" from localhost (127.0.0.1). Example screenshots are below.

Anyone know what kind of sense I should make of these entries?

Example screenshots:

Here's one where location is not `http://default`, but `http://localhost`... again, why?

# Answer
`http://default` is the site uri drush will use if no one is provided.

To provide a site uri you can pass options `-l` or `--uri` to drush: `drush -l http://example.com cron`.

Otherwise you can define and use an alias. See drush example for reference. In a scratch:

File /etc/drush/aliases.drushrc.php:

```
<?php

$aliases['sitename'] = array (
  'root' => '/var/www/sitename',
  'uri' => 'http://example.com',
);

```

So the command to run is `drush @sitename cron`.
> 1 votes

# Answer
The first error seems to be due to a failing operation with the Backup & Migrate module. This module is probably configured to make a backup of your database on a scheduled (CRON) interval. As the error message suggests, increasing PHP's max\_execution\_time setting may help.

The second error you're seeing is due to a missing 'type' column in the file\_managed database table. This field is usually added by the Media and/or File Entity modules. You likely updated these modules' code, but didn't run updates. Try running your update.php, or if that fails, disable, uninstall, and re-install the Media and File Entity modules.
> 3 votes

# Answer
I would guess that your server is not set up for virtual hosting. If it receives an unqualified http request, it will go to the default, finding, in this case, index.php in your webroot. Since it is a direct request, there will be no referer. There is no DNS lookup necessary for local tasks. These messages are probably being kicked out by a cron or batch job.

I would not be concerned. But you certainly should address the missing column in the PDO exception.
> 2 votes

---
Tags: 7, log-messages
---


# Question
Title: Manage displays of Product:image field directly in Product Display?
I have a "Product Display" node showing a "Product" (powered by the Drupal Commerce module).

I have installed the Display Suite module, and created a new view mode for the "Product Display" content type.

The problem is that this new mode is associated with the default view mode of "Product," and I see no way to change this.

What I need is to create a new mode for "Product" and get the view mode of "Product Display" associated with this new one.

Is there anyway to do it?

# Answer
> 3 votes
Go to the Manage Display tab of your product entity and enable the same "View Mode" you use at "Product Display". Do it in the "Custom display settings" fieldset.

Then set up image style for the Image field. And see changes at the "Product display" page

# Answer
> 1 votes
Found a solution to this...it's undocumented and really tricky. In you Product Display content type, add a display mode with a custom machine name `my_custom_display`. Now go to your Commerce Product, and add a new display mode and name it `node_my_custom_display`. When you prepend the `node_` it matches up to the other other display and will allow you to chang the field setting from the Product Display content type display mode.

**Quick Summary**

Product View Content Type Display Mode name: `my_custom_dispaly`

Commerce Product Display Mode name: `node_my_custom_display`

# Answer
> 0 votes
Since "Product" is implemented as an entity in Drupal, you should be able to do something similar to the example provided here to create a new View Mode for it: http://mearra.com/blogs/juha-niemi/drupal-7-custom-node-view-modes.

---
Tags: commerce, display-suite
---


title: Custom menu as admin menu

text:
# Question
Title: Custom menu as admin menu
Is there a module that take a custom menu and show it like Admin menu?

I want to create my custom menu and then display it like admin menu (only for some roles).

I've tried some modules but:

* Admin menu does not allow to select which menu should be displayed, and however I want to display default menu for Administrator and a custom menu for "editors" and other custom roles
* Superfish or Nice menus does not allow to place the menu in top of page, like Admin menu does

Another solution could be a module that place a block in top of page, fixed, so I could use a "simple" superfish menu, but I have not find something like this.

The main question is that I can't use the "default" management menu, but a custom menu.

# Answer
> 11 votes
You want Admin menu source. It allows you to configure each role with a menu as the source for admin\_menu.

# Answer
> 3 votes
Webmaster menu generates a toolbar (aka dropdown menu) from a custom menu. Visible only to selected roles.

> This module makes it quick to place a custom menu as a toolbar.
>
> One use-case is creating an administration menu for the webmaster(s) of a site (a "webmaster" here means: the person actually working with the site - creating content etc). Common tasks vary from site to site, hence it is useful to be able to structure the webmaster menu to reflect the daily needs of the webmaster.

# Answer
> 2 votes
You can use Block Class Styles module:

1. Create a menu block using Menu block, Superfish, Nice menus or similar.
2. In Block Class Styles define style with:

```
position: fixed;
top: 0;
z-index: 999;
width: auto;

```
3. Select that style for a block with your menu.

Same can be done with Block Class, if you are willing to provide CSS properties for fixed menu class in your theme or custom module CSS file.

Note: Admin Menu module sets width as `auto`, but it might require some adjusting with menus rendered by other modules.

---
Tags: routes
---


title: Payment form with Internationalization

text:
# Question
Title: Payment form with Internationalization
I have a simple form which should be able to accept payment via Paypal. The form(site) will support multiple languages and depending on the language, it should change the currency appropriately after applying forex conversion.

I don't want to use drupal commerce since it's too bulky for my requirements. I was thinking if possible what set of modules be used to accomplish this, e.g. webform, paypal webform, which internationalization/localization plugins and so on?

# Answer
The Webform Paypal module sends the user to Paypal to complete a payment whenever they submit a webform containing the component on your site.

> * This module does not directly integrate with Paypal's APIs.
> * This module allows a site user to generate a Paypal 'Buy Now', 'Add to Cart' or 'Donate' button and replace their form's submit button with that button.
> * You can manually keep track of the payment status on individual submissions.
> 1 votes

---
Tags: commerce, i18n-l10n
---


title: drupal image upload programmaticaly

text:
# Question
Title: drupal image upload programmaticaly
i am using drupal 7 . and i am trying to upload image progrmatically .. here is my code

```
$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);
print_r($file); exit

```

and here is my output

```
stdClass Object
(
    [fid] => 4
    [uri] => public://druplicon.png
    [filename] => druplicon.png
    [filemime] => image/png
    [uid] => 1
    [status] => 1
    [timestamp] => 1378142542
    [filesize] => 0
)

```

now here filesize is 0 . as file doesnot contain any data. i am working on local m/c. here is no issue of permission. Does anybody tell me how to solve this

Thanks

# Answer
> 2 votes
The ability for `file_get_contents()` to fetch contents from an HTTP server depends on the `allow_url_fopen` parameter in `php.ini`

If it's not set, `$image` will be false and saving this leads to an empty file.

You may use Drupal's `system_retrieve_file()` instead. It's a wrapper on top of `drupal_http_request()` that comes with its own HTTP client implementation.

Example:

```
$file = system_retrieve_file('http://drupal.org/files/issues/druplicon_2.png',
                             'public://druplicon.png', false,  FILE_EXISTS_REPLACE);

```

# Answer
> 0 votes
```
$image_uri = system_retrieve_file('http://ipsumimage.appspot.com/140x100.png');
$image = image_load($image_uri);
drupal_set_message('<pre>' . print_r($image, true) . '</pre>');

```

**result**

```
stdClass Object
(
    [source] => public://140x100.png
    [info] => Array
        (
            [width] => 140
            [height] => 100
            [extension] => png
            [mime_type] => image/png
            [file_size] => 2534
        )

    [toolkit] => gd
    [resource] => Resource id #443
)

```

**Do not use use drupal.org images for testing.**

If you will use drupal.org path, then you can get the following errors:

**using http protocol**

```
HTTP error -5 occurred when trying to fetch http://drupal.org/files/issues/druplicon_2.png

```

**using https protocol**

```
HTTP error 0 occurred when trying to fetch https://drupal.org/files/issues/druplicon_2.png.

```

---
Tags: 7
---


# Question
Title: Combine views sort criteria in exposed form
Drupal 7, views 3.6.

I have a view with 2 sort criteria: date and category. The sort is exposed in a form block.
Currently the user only has the choice to select 1 sort criteria, ie: sort by date or sort by category.

Is there a way to have the combination of these 2 criteria exposed, ie: sort by date asc, and by category desc ?

Thanks for your input,
Jerome

# Answer
> 1 votes
Use Better Exposed Filters module:

> The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.

# Answer
> 0 votes
Use Grouped filters for combining 2 exposed criteria.

In views exposed form :

Select Filter Type to Grouped filters and then it will display Grouped filter form then u can select which filter u required between 2 exposed filters.

---
Tags: views
---


# Question
Title: drupal commerce customize node product list
I'm trying to modify the theme file "node--product--type--product--list.tpl.php" to customize the layout.

I'm having a little trouble doing it,

can someone please point out, how I can access easily to each field ?

I would need the fields : title, price, images, link to the product.

# Answer
> 0 votes
As I see from your question you need to access the field info of a product. You can do it at `template.php` file. Just do it in the **preprocess** function based on the TPL file where you are going to use after you get it and put it in some variable. I will give example here for THEME\_preprocess\_node().

```
function THEME_preprocess_node(&$vars){
  if ($node = menu_get_object()){
    if($node->type == 'PRODUCT_display'){
      $product_id = $node->field_PRODUCT_reference[LANGUAGE_NONE][0]['product_id'];//here mention your own product reference field name.
      $product = commerce_product_load($product_id);//After this you will have all the product info in $product variable, even fields.
      $author = $product->field_book_author[LANGUAGE_NONE][0]['value'];
      $vars['author'] = $author;
}

```

After this you will have `$author` variable in your all `node.tpl.php`, use it in the way you want. You can even modify info at `template.php` file itself if you want. I hope it helps, otherwise you can comment for more help :)

---
Tags: commerce
---


# Question
Title: use EntityFieldQuery to find user based on profile field value
I have a field within the user's profile set with their payroll. What I'm trying to achieve within my module is find the uid, based on the value of a payroll field.

I've tried a few things, but I can't get it to work. What I'm currently trying is this, but it returns unknown field of user

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'user')
  ->fieldCondition('user', 'field_user_payroll', $payroll, '=');

$result = $query->execute();
$account = user_load($result);

$wrapper = entity_metadata_wrapper('user', $account);
$mimemail = $wrapper->mimemail->raw();

watchdog('Photo Import', "Mimemail: %mimemail",
  array('%mimemail' => $mimemail), WATCHDOG_INFO);

```

Any help would be really appreciated. It's driving me crazy!

# Answer
> 5 votes
```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_user_payroll', 'value', $payroll, '=');
$results = $query->execute();

$users = user_load_multiple(array_keys($results['user']));
foreach($users as $user) {
    $wrapper = entity_metadata_wrapper('user', $account);
    $mimemail = $wrapper->mimemail->raw();

    watchdog('Photo Import', "Mimemail: %mimemail", array('%mimemail' => $mimemail), WATCHDOG_INFO);
}

```

as per EntityFieldQuery::fieldCondition(), EntityFieldQuery doc

......

---
Tags: database
---


title: Contextual filter - day of week in url

text:
# Question
Title: Contextual filter - day of week in url
I'm looking for a way to only show elements related to a specific day in the week. Let's assume that the url to the view is: /program/schedule. What I would like is that when you go to: /program/schedule/monday, only the info related to the monday is displayed.

Now I already figured out the contextual filters and that I can limit the valid values to: monday, tuesday, wednesday, et cetera. This is not the problem. The problem that I'm having is that it seems that my date time field needs to have an input of a specific date like 20130902.

I also need to point out that I am able to format my date time field to only show as a day of the week (with date formatting), but this does not seem to impact the contextual filter.

Is there a way to achieve this? Maybe with hooks or something custom?

# Answer
> 0 votes
Views Day of Week provides a simple filter plugin for Views 3 to enable filtering content that should be visible based on the current day of the week.

> Example: With this module you can select that some content should be visible only on Mondays, some on Tuesdays and Thursdays and some only on Fridays.

---
Tags: views
---


title: Load theme tpl after form submit

text:
# Question
Title: Load theme tpl after form submit
From a custom module in Drupal 7 I am trying to load a template after I submit and process my form.

I can load the theme fine from a page callback:

```
function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'arguments' => array(),
    ),
  );
  return $themes;
}

function mymodule_menu() {
  $items = array();
  $items['reports/performance'] = array(
    'title' => 'My Module Performance Report',
    'page callback' => '_mymodule_report',
    'access arguments' => array('mymodule_client'),
  );
  return $items;
}

function _mymodule_report() {
  return theme('mymodule_report');
}

```

All of that works fine (e.g I can go to www.mysite.com/reports/performance and my tpl loads.). The problem is when i submit a form, after I process the form I want to pass the form data to the template, and load the same template page.

I modified the hook\_theme like this:

```
function mymodule_theme() {
  $themes = array(
    'mymodule_report' => array(
      'template' => 'themes/mymodule_report',
      'variables' => array('parameters' => NULL),
    )
  );
  return $themes;
}

```

And in my submit handler for my form after I gathered all my form values into an object ($submission), I added this at the end:

```
 return theme('mymodule_report', array('parameters' => $submission));

```

All that happens is my form reloads...what am I missing?

# Answer
So I found a solution that works...of course if there's another or better way, I'd love to know.

I added this to my form:

```
  if (!empty($form_state['nnjob_mtbf']['mtbf_results'])) {
    $form['result'] = array(
      '#markup' => $form_state['nnjob_mtbf']['mtbf_results'],
    );
  }

```

And then to my form submit handler:

```
  $form_state['nnjob_mtbf']['mtbf_results'] = theme('nnreport_client_perf_report', array('parameters' => $submission));
  $form_state['rebuild']=TRUE;

```

And voila, template loads like a champ.
> 1 votes

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


# Question
Title: How do I hide /sites/default/files from URLs?
I want to upload files to their normal directory under /sites/default/files/. So let's assume I have example.pdf uploaded to sites/sites/default/files/manuals/example.pdf.

I want the links to files look like http://example.com/manuals/example.pdf. I think it's simpler and looks more professional.

How can I achieve it with Drupal?

# Answer
> 6 votes
File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').

> * Customizable File Alias field using Node tokens. Support for:
>     + Drupal core Upload module.
>     + FileField module.
>     + ImageField module.
>     + Image module.
>     + Comment Upload module.
> * Support for Private and Public file systems.
> * Support for Views output (Fields and Nodes).
> * Support for FileField Paths Retroactive and Active Updating.

---
Tags: files, uri
---


title: Export View results to CSV

text:
# Question
Title: Export View results to CSV
I have a listing view with filters and a button to export the results to a CSV file. How can I send the view's arguments to my export callback after a user applies some filters?

# Answer
Have you looked at Views Data Export. I've wired in a view to export on button click. You just build or modify a FAPI form to contain a button and give it the url of the view you want to output as csv.

In your case you'd pass the selected arguments into the view. You could use FAPI and Javascript to properly build the url and button action.
> 2 votes

---
Tags: 7
---


# Question
Title: How to filter the values of an array in drupal
In drupal we have check\_plain function to filter the unwanted codes from a text, I have an array which I am storing directly, in that case, I need to check each value before storing, is there a function to which we can pass the array and it should filter and reset the array.

Ex - I have a form where users can add as many names as they want using (multiple textfield) the name of the textfield is - guarantors\[\]

So I have an array where all the userinput is there, inorder to filter, I need to filter each value of array using foreach.

is there a function or way, so that I can directly pass the array to a function and it should return me an array with safe values, i.e each values should be parsed using check\_plain function.

I think an expample may help you answer better, here is my example array.

```
Array
(
[0] => Array
    (
        [keyword] => lucidus
        [color] => #00ff00
    )

[1] => Array
    (
        [keyword] => commoveo
        [color] => #998899
    )

[2] => Array
    (
        [keyword] => dolus
        [color] => #ff0099
    )

)

```

NOTE :: keyword and color are user input values. And those needs to be filtered, it is and can be a multidimensional array.

Many Thanks

# Answer
This is an old question, but there didn't seem to be a decent answer yet...

There is no out-of-the-box solution but it's easy to write a function that recursively walks the array and applies a filter function to the keys and values.

```
<?php
function clean_array($array, $filter = 'check_plain') {
  $clean = array();
  foreach ($array as $key => $val) {
    if (is_array($val)) {
      $clean[$filter($key)] = clean_array($val, $filter);
    }
    else {
      $clean[$filter($key)] = $filter($val);
    }
  }
  return $clean;
}
?>

```

This also gives you the flexibility to use filter\_xss or check\_markup instead.

Hope that helps.
> 1 votes

# Answer
You can do it using PHP function array\_filter .

Find the example below

```
<?php
  function myfunction($v)  {
    $os = array("Dog", "Cat");
    if (in_array($v, $os)) {
      return true;
    }
    return false;
  }
  $a=array(0=>"Dog",1=>"Cat",2=>"Horse");
  print_r(array_filter($a,"myfunction"));
?>

```

// Above example will return an array with Dog & Cat as values !
> 0 votes

# Answer
I think array map is what you are looking for. This function takes a callback and an array as arguments, returns an array of all the processed values.

Code example, ripped out of php.net man page:

```
<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

```

Content of $b will be : Array ( \[0\] =\> 1 \[1\] =\> 8 \[2\] =\> 27 \[3\] =\> 64 \[4\] =\> 125 )

Hope this helps.
> 0 votes

---
Tags: 7
---


# Question
Title: How to allow user's of a certain role to change the node creation date
I want to allow some users (a role) to change the node creation date (ideally on the node's form).

* I could add permission 'administer nodes' to this role but it's too strong
* I could create a new field for this date, but i want to keep the drupal submitted informations on the top of the node

If someone have any idea, thanks

# Answer
> 13 votes
You want Override Node Options module.

> The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.

In addition you may be interested in Date Popup Authored to use a datepicker on that field.

---
Tags: 7
---


# Question
Title: Setting a Variable in PHP for use in rules
I have a variable I've defined via rules using 'Add a variable' called 'minimum\_reached'. This is available to me for use in custom PHP code.

```
if($total >= $minimum_fund){
   $minimum_reached = 'yes';
   dpm($minimum_reached, 'min reached');
}

```

Once this is set to 'yes', the next action fires which Sets a data value of the current node's 'minimum reached' field to yes (depending on that above outcome). The variable is being set as the dpm works, but it's not being carried across to the next action. How do you define this variable in PHP for use later on? Thanks.

# Answer
> 3 votes
The Rules module doesn't seem to provide this feature.

I also tried using a rule set with a variable, but the variable was reset between each action. I tried adding `return $minimum_reached` at the end of each rule executing PHP code, but it didn't help.

The only way seems to use drupal\_static(), if you are using Drupal 7 (e.g. with `drupal_static('mimimum_reached', 'default value used when the variable is not set')`), or a global PHP variable, if you are using Drupal 6.

# Answer
> 0 votes
While it's not supported via the Rules module's UI, you can (theoretically) add variables to your evaluation structure by declaring a custom action. See https://drupal.org/node/878972

I'm working to get past the theoretical part, using a variable provided by one custom action in another custom action. :)

---
Tags: rules
---


title: Node export to POT for translation

text:
# Question
Title: Node export to POT for translation
I think I'm missing something pretty basic here.

I'd like to be able to export all node content as POT files to send along with the other POT files for translation.

I have i18n installed, and a handful of dependencies and "Translation template extractor".

I am able to export nearly everything on the site (menus, taxonomy, strings from modules, etc) but I do not see an option to export "nodes" or "node content".

Is there a way to do that?

# Answer
> 7 votes
No, there isn't.

I maintain the Translation Management Tool project, that offers a way to export nodes and other translatable content as XLIFF. There is no POT export option but it should be possible write an export format for that.

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


# Question
Title: how to create a view of entities and nodes
I need to create a view which displays both entity type data and node data. Is this possible? I know how to create a view of either entities or nodes, but not together.

# Answer
> 1 votes
Node are entities. Likely a Node View has access to node-specific properties while an Entity View only has access to fields and generic properties (or properties exposed through the Entity API).

If you can link your entities to nodes using a relation that is exposed as a relationship in a Node/Entity View, you should be able to have view results consisting of data from both a entities and nodes.

---
Tags: views, entities
---


# Question
Title: How to insert values into Global custom text field of views programmatically?
How can I programmatically insert values into Global custom text field from the views. I have tried using the $views variable from the hook\_views\_pre\_render(&$views) and my\_theme\_name\_process\_function(&$vars) but was unsucessful in getting the value ? When I try for a simple field I can insert html into the markup programmatically.

```
$view = view Object
(
    [db_table] => views_view
    [base_table] => node
    [base_field] => nid
    [name] =>view_name
    [vid] => 3
    [description] =>
    [tag] => default
    [human_name] => view_name
    [core] => 7
    [api_version] =>
    [disabled] =>
    [editing] =>
    [args] => Array
    (
        )

    [use_ajax] =>
    [result] => Array

  [result] => Array
        (
            [0] => stdClass Object
                   [field_field_final_ort] => Array
                            (
                                [0] => Array
                                    (
                                        [rendered] => Array
                                            (
                                                     ['#markup'] => YES

```

I want to similarly change the value of GLOBAL custom text field using views object but there is not such array for global custom text field.
What is the way for changing it?

My code was

```
function my_themename_process_views_view_field(&$vars) {

  if ($vars['view']->name == 'view_name') {
foreach( $vars['view']->result as $key => $value) {
$value->field_name[0]['rendered']['#markup'] = '';
}

```

}

I want to apply this similar code for global custom text field but there is no suxh available inside result array

How can I alter values for **each row of global custom text field value** ? The answer given below gives same values for each row .

# Answer
> 14 votes
You should be able to do that with hook\_views\_pre\_render(). Please try the following code:

```
function YOUR_THEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'YOUR_VIEW_NAME':
      //  override the global custom text field value
      $view->field['nothing']->options['alter']['text'] = 'My custom text';
    break;
  }
}

```

If the global custom text value need to be different for each view result, you can configure it using replacement patterns.

In order to programmatically insert values into Global custom text field, You can use template\_preprocess\_views\_view\_fields()

```
function YOUR_THEME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // The global custom text content
    $vars['fields']['nothing']->content = 'Some global custom text content';

    // change the global custom text content depend on result (node id)
    if ($vars['row']->nid == 10) $vars['fields']['nothing']->content = 'CHANGED';
  }
}

```

---
Tags: 7, views
---


# Question
Title: Node image instead of pointer icon in openlayers map
Does anyone know a way to change the pointer icons to node images?

Like the image below

I really like to have a little preview image from the node instead of hundreds of same looking pointers.

Any ideas?

# Answer
output the image's URL in your view which supplies data to your map. create a new openlayer style, and for the marker graphic, give it your field name enclosed in ${}.

eg. add field\_image to your view, set it to output 'url to file' then add a new style and tell it the marker graphic url is ${field\_image} and select an image style (eg. thumbnail)

use this new marker style on your overlay and you'll see the image show up as a marker icon.
> 0 votes

---
Tags: javascript
---


title: Preview different then output in views

text:
# Question
Title: Preview different then output in views
I'm a newbie in drupal. So I have this view which Im saving as a block and the way it displays in the preview of the view and on the page is different. Any ideas?

If you have any questions about my configuration just ask I didn't know what to include :)

# Answer
> 1 votes
This displays data after all the filters, arguments, etc are applied. It's kind of like the raw output. You're theming will be displayed when the actual page is loaded with the block enabled for that page.

# Answer
> 0 votes
It's hard to tell from only this amount of information, because modules and themes can significantly (or completely) alter the appearance of your output, which can cause surprises and anger and facepalms (see my example), but **one reason (out of the many)** for Views preview differing from the output ***can* be** \- on a multilingual site - that **you have already translated your views pages and fields via** **i18nviews** (Internationalization Views).

I'll write down my case, maybe it spares some time for anyone else suffering from a ridiculously trivial, but not too "eye-catching" problem.
I rewrote the output of a field like this:

And I didn't understand why my fields appear well in the preview area, get the divs, the classes, etc., but I see a result which is totally different, no divs, no extra classes. As it turned out, the source of the problem is that I watched the page in another language (not the same as I watched when inspecting the preview results), and unfortunately the field has formerly been ***translated*** via i18nviews (with which most of the Views fields can be translated) like this:

This way it didn't get the appropriate divs and classes.
I had to copy the exact same markup of *"Rewrite the output of this field"*, save the translation, problem solved.
But I had to spend half an hour to find out the reasons. This may sound silly, but situations like this can occur while developing. If it saved some time for anyone, it was worth writing it down.

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


# Question
Title: Create a dynamic user registration form using Profiles
So, I need to create a user registration form for a website that has numerous types of users that are distinctly different from one another. I've already found the profiles module, and I'm using that. But I want to streamline the user registration process.

We don't want to create a large form that pushes everyone through the same questions, even if that question isn't applicable to that user. Nor do we want to compromise and only not ask certain questions that are important to that particular type of user.

I'd also prefer the form to be dynamically updated, rather than a multi-step form.

How can I do this?

# Answer
> 1 votes
Bascially, we create an Ajax callback on the form element used to update the form, and we create an additional form element which is simply a container to display the the relevant profile form.

I used the Profile 2 Registration Path module to add the Profiles Forms to the User Registration form. I then use `hide();` and `show();` to display them if appropriate.

The Devel module was also invaluable doing this.

```
function rego_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'user_register_form'){
        dpm($form);

        //First, hide all the other profiles
        hide($form['profile_designer']);

        //User selects what type of profile is most appropriate
        $form['profile_main']['field_profile_type']['und']['#ajax'] = array(
            'callback' => 'rego_update_profile_type',
            'wrapper' => 'profiles_container',
        );

        //Create a container to the relevant profile
        $form['profiles_container'] = array(
            '#prefix' => '<div id="profiles_container">',
            '#suffix' => '</div>',
            '#weight' => '500',
        );
    }
}

//Callback
function rego_update_profile_type($form, $form_state){
    // Switch based on the user input
    switch($form_state['values']['profile_main']...['tid']){
    case '82':
        $form['profiles_container'] = $form['profile_designer'];
        break;
        // --Other cases here --
    }
    //Put back the div id so that the container can be updated again
    $form['profiles_container']['#prefix'] = '<div id="profiles_container">';
    $form['profiles_container']['#suffix'] = '</div>';

    show($form['profiles_container']);
    return $form['profiles_container'];
}

```

---
Tags: forms, ajax, users
---


# Question
Title: How to modify image field in field_attach_preprocess_alter
I have an image field called `field_grid_image` on a custom node type "event". I want to populate this field when not available but I don't want to use a default image. I want to add a default image based on the node's taxonomy. I have written the following code to load the image from node's taxonomy field but it doesn't show up in the final output.

```
function custom_event_field_attach_preprocess_alter(&$variables, $context) {
    if($context['entity_type'] == "node" && $context['entity']->type == "event" && sizeof($context['entity']->field_grid_image) == 0){
        $tid = $context['entity']->field_event_type['und'][0]['tid'];
        $taxonomy_term = taxonomy_term_load($tid);

        $values = field_get_items('taxonomy_term', $taxonomy_term, 'field_generic_image');
        $variables['field_grid_image']['und'][0] = $values[0];

        dpm ($values);
        dpm( $variables);
    }
}

```

When I print $variables I see the field populated from the taxonomy as follows.

Any ideas why the image is not rendered in the final output?

Thanks,

# Answer
> 1 votes
I've figured out the problem. I should have used `field_view_value` to render the field and add it to `$variables['content']` instead of editing the field directly.

The below code works as expected now.

```
function custom_event_field_attach_preprocess_alter(&$variables, $context) {
    if($context['entity_type'] == "node" && $context['entity']->type == "event" && sizeof($context['entity']->field_grid_image) == 0){
        $tid = $context['entity']->field_event_type['und'][0]['tid'];
        $taxonomy_term = taxonomy_term_load($tid);

        $values = field_get_items('taxonomy_term', $taxonomy_term, 'field_generic_image');
        $node = $variables['node'];
        $output = field_view_value('node', $node, 'field_grid_image', $values[0], array(
            'type' => 'image',
            'settings' => array(
            'image_style' => 'gridimage',
            'image_link' => 'content',
            ),
        ));

        $variables['content']['group_image_text']['field_grid_image'] = $output;
    }
}

```

---
Tags: 7, entities
---


# Question
Title: Should I create a new Form or use form alter?
I'm very new to Drupal. I've been handed over a Drupal 7 project. In the project, there's a form to create a new record into database. However it's using `hook_form_alter` instead of creating from scratch. The form is called as `node/add/<something>` as a page. Similar to first few steps of this tutorial.

I'm not sure however if this is the correct Drupal way, or should I just rewrite it into a block, as I want to have it shown on .... at least two pages?

Any suggestions?

# Answer
> 3 votes
The distinction is simple:

* If you need to add some fields to an existing form, and keep all of it's original functionality (or at least most of it), use `hook_form_alter`.
* If you need to create a totally new experience, put it under different path and create form from scratch, like shown in Examples for developers
* If you feel you need totally new form under already occupied path, think again as it might cripple existing functionality.Feel free to ask more specific question then.

Then, if you want a form at 2 pages, you have 2 choices:

* If form will be the only significant element on these pages, make it a page (or pages) with `hook_menu`
* If there are supposed to be other forms, submitted independently, wrap it into a block.

---
Tags: 7, forms
---


# Question
Title: PHP code to display block based on list (text) field
Drupal 7. I'm trying to display a block using the "Pages on which this PHP code returns TRUE" feature. The field is a single value list (text) named **field\_display\_block** so all I want to do is determine if field\_display\_block is set to "1".

I'm sure there are a couple of ways to do this. Any help on this would be greatly appreciated.

Thanks

Les Z

# Answer
With the following script you can check the value and return true. I've added my comments before each line.

```
// First check if the current page is a node
if ($node = menu_get_object()) {
 // Then, check if it is your content type
 if ($node->type == 'your_content_type') {
   // Get the value of your field
   $display_block = field_get_items('node', $node, 'field_display_block');
   // If the field's value is equal to 1, then return true
   if ($display_block[0]['value'] == '1') {
     return TRUE;
   }
  }
}

```
> 3 votes

---
Tags: entities, blocks
---