# Question
Title: Map generated from custom address fields
I have a seemingly simple problem, but I've been stuck with it for some time now.

I have a big database of nodes of one content type. There are addresses there made of text fields: one field for street, one for city etc. Province is a predefined taxonomy. I'd like to use 4 of these fields, including province, to get a string that can be geocoded as lat/lon for a map.

I also need these fields to be useable in Views (e.g. as filters like a province filter, as tokens etc.). It is doable in GMaps + Location (Views module recoginzes each locative entry as a separate field), but GMaps is seemingly an obsolete module, and it forces me to use predefined provinces which is not cool.

Also, I need to display a small map when a user displays one of the nodes, and the other for the home page with all the locations marked and ready to get filtered out by exposed filters.

I thought maybe geocoded Field Collection is an option for me, but the separate elements of such a field are strangely not visible in Views module as filtering/sorting criteria. I also tried the Computed Field, but there is a bug which prevents its text output from being geocoded. ( http://drupal.org/node/1679926 -- bug desc.)

Am I missing something? Are there any other simple ways to get a map made of custom fields as address elements?

Regards!

# Answer
> 2 votes
You could use the Geofield and the Geocoder modules. The fist module allows to store geographic data in a field; the second one to extract the geographic data from another field, including an image field.

When you add a new field to an entity (for example, a node), you need to select *Geofield* as field type, and leave *Geocode from another field* as widget.

>

Clicking on the *Save* button, you will be then asked to change the field settings (which just allow to change the storage backend). After clicking on the *Save field settings* button, you can choose from which field the geographic data are extracted, including an image field.

>

The Geocoder module once allowed to select multiple fields from which the geographic data would be extracted, but that was a bug, reported in Geocode from field allows multiple selections and fixed. If you are reading blog articles or tutorials that suggests you can select multiple fields from which the geographic data are extracted, they are all referring to older module versions.

# Answer
> 1 votes
Based on the issue you mentioned I assume it is Drupal 7. So the first thing I would do is move the address from each elements to Address field. Address is fully compatible with tokens as well as views and will give you support for all the countries and states and you do not have to work it on your own using taxonomies.

To do this you can have a look at Migrate and Migrate Extras.

Once you are done with this you can have a look at you can use the geocoder, geofield and openlayers to get the desired output.

But it is definitely some work.

# Answer
> 1 votes
This may not answer your entire question, but may help you get to the answer. Here's how I added simple maps based on the address in a node:

1. Used the Address Field module, which has a very clunky interface but supports international addresses. (Fields change dynamically based on which country the user selects.)
2. Used Views to display my nodes, but you could also use custom fields via Display Suite or other solutions.
3. Used the following code (as a rewritten field in Views) to create and embed a map of the address on each node. (I converted all \> and \<'s to curly brackets so it would display, see unmodified code at http://pastebin.com/gR9Hxn9a. The square brackets are referring to other fields in Views.)

`{a href="http://maps.google.com/?q=[field_location_address-premise]+[field_location_address-sub_premise]+[field_location_address-thoroughfare]+[field_location_address-locality]+[field_location_address-dependent_locality]+[field_location_address-postal_code]+[field_location_address-administrative_area]+[field_location_address-sub_administrative_area]+[field_location_address-country]" target="_blank"}
 {img src="http://maps.googleapis.com/maps/api/staticmap?markers=[field_location_address-premise]+[field_location_address-sub_premise]+[field_location_address-thoroughfare]+[field_location_address-locality]+[field_location_address-dependent_locality]+[field_location_address-postal_code]+[field_location_address-administrative_area]+[field_location_address-sub_administrative_area]+[field_location_address-country]&zoom=7&size=200x150" class="locationmap" /}
 {br /}
 [field_location_address_1]{/a}`

# Answer
> 0 votes
You could DSM out the fields in the template (node or view) and use the field values, and build up a map using just an embed code with your address, and manually attach those values into an iframe embed inside your template file. Just an idea.

---
Tags: 7, views, entities, tokens, google-maps
---


# Question
Title: How to check if is anonymous user's first visit to site when using varnish
If one has a Drupal 7 site which uses varnish for caching, is there some method which would enable one to serve a different version of front-page if it is first time the anonymous user has visited the site?

As I understand it, varnish caching will not work if a session variable is used. Is there some way of doing this using client side cookies?

# Answer
The varnish caching will not work if you use cookies : http://systemsarchitect.net/2013/07/08/reading-php-session-from-varnish-cache/
> 0 votes

---
Tags: caching, proxies, cookies, users
---


title: Feed Import from multiple pages

text:
# Question
Title: Feed Import from multiple pages
Make Feed Importer go to given URL which has a list of thumbnails and links to their pages and make it check/open each of those links and scrape content from there into unique nodes importing its titles and images and so on and so on?

Is this possible or does the content has to be listed in one single page to scrape it?

I've done it with just scraping from one page or .xml feed, but how do I tell my feed to check that one page for links and go to those links and scrape content from each and every link?

# Answer
> 0 votes
Use `hook_feeds_after_save``( $source, $entity, $item, $entity_id)` for parsing for links the document and execute command after the importing of each feed.

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


# Question
Title: Displaying parent nodes with child nodes - nested views, hard coding, or other approach?
I have a parent content type which is categorized with a taxonomy term. Then there are child nodes to the parent. When someone clicks on a category, I want them to see a table basically. It would be of the form:

> Parent1 Description
>
> > Child1 Description
> >
> > Child2 Description
>
> Parent2 etc

Seems out of the box I can't get Views to behave that way, so I was thinking I would have one view that is for the Parents, and another for children of a parent, and then somehow (via Display Suite for instance) have the page display the views one after another. Though I suspect that way of thinking is counter to what drupal is all about, so I am really trying to harnass the power of drupal to make that happen, as opposed to writing a custom module (though in the end I think such a custom module would be easier than Views, but I want to max out my understanding of Views before I go that route).

That said, how would you go about creating the Views and then controlling the display in Display Suite?

EDIT: So I figured out the SQL query that would return the results how I want them. Basically something like this

```
SELECT n.title, d.field_description_value, n.nid, l.field_lesson_target_id from drupal_node n

JOIN drupal_field_data_field_description AS d ON d.entity_id = n.nid

JOIN drupal_taxonomy_index AS t ON t.nid = n.nid

LEFT JOIN drupal_field_data_field_lesson AS l ON l.entity_id = n.nid

ORDER BY COALESCE(l.field_lesson_target_id, n.nid), l.field_lesson_target_id, n.nid

```

I made sqlfiddle

So I guess it comes down to whether Views is able to produce such queries.

# Answer
> 0 votes
Per the creator, the answer is in the comments with some additional documentation here: http://drupaleasy.com/blogs/ultimike/2009/02/displaying-hierarchical-content

---
Tags: views, display-suite
---


# Question
Title: Is the mail_logger module safe for production?
I'm having intermittent problems with emails that are silently failing on a production environment. I'm troubleshooting with the `mail_logger` module, and it would be extremely helpful on production.

However, for some reason I feel that this is a 'development/debugging' module and not something recommended for production. Are my fears unfounded?

# Answer
> 2 votes
No, it doesn't enable any developer backdoor features (e.g. arbitrary PHP execution, code/stack dumps, etc.) if that's your concern.

For the most part, its code base is Views integration & an admin interface wrapped around its core function; intercepting outgoing mail through `hook_mail_alter()` and storing in the `mail_logger` table.

I'd say the only concern there is privacy for your users.

---
Tags: emails
---


title: Remove/Rename Home tab Drupal 7

text:
# Question
Title: Remove/Rename Home tab Drupal 7
I was wondering if it is possible to either remove or rename the "Home" tab Drupal puts in by default. The site is being used as a store/shopping cart and for it's purposes does not need a convention "Home" tab.

# Answer
> 0 votes
Go to /admin/structure/menu/manage/main-menu and it can be deleted from there.

# Answer
> 0 votes
this worked for me in drupal 6 got to

Home » Administer » Site configuration

tick this "Hide the breadcrumb if the breadcrumb only contains the link to the front page".

# Answer
> 0 votes
FYI drupal 8: Home » Administration » Structure » Menus and then select List Links, to change the name

---
Tags: routes
---


title: Highlight Field in Views

text:
# Question
Title: Highlight Field in Views
I just created a Views table with a few columns. I would like to create a rule that enables Views to highlight certain fields if information is missing/blank. What would be the best way to do this?

# Answer
> 1 votes
In your view's settings, click on the field that might be empty and open up `NO RESULTS BEHAVIOUR`. Uncheck everything in the dropdown (perhaps leave `Count the number 0 as empty` depending on your use case) then add text like this in the `No results text`

```
<div class="empty"></div>

```

---
Tags: views
---


# Question
Title: Need to be able to disable taxonomy term, but maintain legacy
Need to be able to disable taxonomy term, but maintain legacy. Attempting to populate a drop down with taxonomy term, but have a required to disable a specific term, but still maintain the data.

Another way to describe what i'm trying to do. Is not allow a user to select a specific term in the drop down.

# Answer
Depends where you wish to add the term. If you need to add it to a Node creation page, you could always, instead of adding the field as a `term reference`, add it as an `entity reference`, select `Taxonomy Term` as target, select the correct bundle, and in `ENTITY SELECTION`, `select Views: Filter by an entity reference view`.

In order to do that you will beforehand need to create a view on the taxonomy terms that you wish to display and hide (ie filter out those terms that should not be displayed), then add this view to the dialog that will appear when you select `Views: Filter by an entity reference view`
> 0 votes

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


# Question
Title: How to prevent child element to move when parent dropdown?
I have a `div` with `height:20px` with hover. When you put the cursor on it, a menu bar appears, this menu bar have `height:50px`.

After that i have a second `div` which is juste a yellow pannel with `margin-top: 50px` (so it's 50px from the parent who is the first div (that has : height : 20px)).

Now when the hover effect happend, the second div (the yellow pannel) moves down with the droping down effect.

How to make the second div do not have a margin top with the direct first div (his parent) ?

Thank you

# Answer
> 1 votes
In css you need to give your menu bar div an absolute position.

For Example: `.menubar { position: absolute; }` so that it overlays everything, so it won't affect anything else.

Then adjusted if needed

Example: `.menubar { position: absolute; top: 0px; left: 20px; }`

Also you will need to increase the yellow div from 50px to 70px

`.yellow { margin-top: 70px; }`

---
Tags: theming
---


title: What is hook_menu_alter used for?

text:
# Question
Title: What is hook_menu_alter used for?
In simple terms, what is hook\_menu\_alter for? I understand callbacks in general, but I'm not quite sure if this method is misnamed in a sense, as I see it used in the context of permissions rather than menus. I'm probably just confused.

# Answer
> 4 votes
I think that your confusion comes from the fact that Drupal 6 and 7 mixes menu and routing. One set of hooks for both purposes, and here you have problems. If this hook was named `hook_route_alter()`, using it to alter permissions to some routes would be obvious, right? So that's what modules do, using the name they got. Personally I agree it's not most lucky naming, but once you remember that in this context, basically, **menu == routing**, it all becomes much more intuitive.

# Answer
> 3 votes
**Change theme of particular page/menu:**

There we have used `hook_custom_theme()` hook to change theme on particular page. Instead of this we can also use `hook_menu_alter()` as another way to achieve same feature.

```
/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Change 'node/add/page' page to admin theme (Assume by default node/add page uses default theme)
  $items ['node/add/page']['theme callback'] = variable_get('admin_theme');
}

```

**Change title of page/menu:**

Menu provides page titles. If we are in ‘node/add/page’ then we see page title as ‘Create Basic page’ but what if we need custom title like ‘Add page’. We can achive this using below custom module.

```
/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Change 'node/add/page' title to 'Add page'
  $items ['node/add/page']['title'] = 'Add Page';
}

```

**Customize accessing a page/menu:**

For many pages/menus we restrict access to different users or on conditions. Let’s say we want restrict ‘user/register’ page in particular times.. I mean no registration will be done in 12AM - 06AM.

```
/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Restrict 'user/register' page in 12AM-05AM
  $items ['user/register']['access callback'] = '_MY_MODULE_time_access';
}

    /*
     * Access callback function to restrict user registration in particular timings
     */
    function custom_module_time_access(){
      // Get current time hour like 0,1,2,3....23
      $current_time_hour = date('G');

      // if current time is between 0 & 5 then return false
      if($current_time_hour >= 0 && $current_time_hour <= 5 ){
        return false;
      }
      return TRUE;
    }

```

**Create duplicate page/menu:**

We can also use hook\_menu\_alter() hook if we want to create a duplicate page, a page with same functionality but with different url. Let’s say we want a url ‘add/page’ which acts same as of ‘node/add/page’.

```
/*
 * Implements hook_menu_alter().
 */
function custom_module_menu_alter(&$items){
  // Copy ‘node/add/page’ page to ‘add/page’
  $items ['add/page'] = $items ['node/add/page'];
}

```

# Answer
> -1 votes
With hook\_menu\_alter you can manipulate $items: Associative array of menu router definitions returned from hook\_menu(), you can add or remove items or manipulate menu item properties : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7

---
Tags: hooks
---


# Question
Title: Why is my custom webform submit handler not submitting?
I've looked at a number of posts, but none of them have quite the same issue as I am. I've added two custom submit buttons to a webform (in addition to the default one created by the admin page.) My custom validate function and submit function are being called, but the default submit function is not - i.e. the error logging I've put in my custom function gets printed, but the form is NOT actually submitted. Any ideas?

```
function create_vector_user_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'webform_client_form_24': // free trial webform
    $form['submit']['64_bit_btn'] = array(
      '#name' => 'op',
      //'#button_type' => 'submit',
      '#type'   => 'submit',
      '#value' => t('DOWNLOAD 64-BIT TRIAL'),
      '#executes_submit_callback' => TRUE,
    );

    $form['#validate'][] = 'create_vector_user_free_trial_form_validate';
    $form['#submit'][] = 'create_vector_user_free_trial_form_submit';
    $form['actions']['submit']['#submit'][] = 'create_vector_user_free_trial_form_submit';
    break;
  }
}

function create_vector_user_free_trial_form_validate($form, &$form_state) {
// this function runs correctly

}

    function create_vector_user_free_trial_form_submit($form_id, &$form_state) {
    error_log("submit!");
    if (strtoupper($form_state['clicked_button']['#value']) == 'DOWNLOAD 64-BIT TRIAL') {
        error_log("submitted 64");
    }
    else if(strtoupper($form_state['clicked_button']['#value']) == 'EMAIL ME A LINK') {
        error_log("submitted email");
      $to = $form_state['values']['submitted']['email'];
      $params = array();
      $params['version'] = $form_state['values']['submitted']['download_type'];
      $key = 'homepage';

      drupal_mail('create_vector_user', $key, $to, language_default(), $params);
    }

    else {
        error_log("submitted default 32");
    }

  error_log("test end");

}

```

**ETA:** I've also tried this in my `form_alter` function based on this article about custom validation:

```
$form['#validate'][] = 'create_vector_user_free_trial_form_validate';
// $form['#submit'][] = 'create_vector_user_free_trial_form_submit';
$first = array_shift($form['#submit']);
array_unshift($form['#submit'], $first,'create_vector_user_free_trial_form_submit');

```

//$form\['actions'\]\['submit'\]\['#submit'\]\[\] = 'create\_vector\_user\_free\_trial\_form\_submit';

# Answer
> 2 votes
I found the problem.

One of the features of webform is the ability of have multi-page forms, and the way how webform determine if it is in the "final" page is checking if the submit button has the value "Submit" and if that is not the case then it thinks to there is another page to evaluate before to submit the last function.

You can see this in the file webform.module in the line 3174:

```
 // Check for a multi-page form that is not yet complete.
 $submit_op = !empty($form['actions']['submit']['#value']) ?
 $form['actions']['submit']['#value'] : t('Submit');
 $draft_op = !empty($form['actions']['draft']['#value']) ?
 $form['actions']['draft']['#value'] : t('Save Draft');
if (!in_array($form_state['values']['op'], array($submit_op,
$draft_op, '__AUTOSAVE__'))) {

```

In the case of your example `$form_state['values']['op']` doesn't exists and even if it exists it wouldn't has the value 'Submit' so it will try to handle your form as a multipage form and It will not execute the last part of the function.

What I did to make your example work was only add the this in your submit function `$form_state['values']['op'] = 'Submit';` and that's it.

It feels like a hack but that is the way how webform work :(

Below the example if you want to compare it with your code:

```
<?php

/**
 * Implements hook_form_alter().
 */
function test1_form_alter(&$form, &$form_state, $form_id)
{
    switch ($form_id) {
        case 'webform_client_form_5':
            $form['64_bit_btn'] = array(
                '#name' => 'op',
                '#type' => 'submit',
                '#value' => t('DOWNLOAD 64-BIT TRIAL'),
            );
            $form['#validate'][] = 'create_vector_user_free_trial_form_validate';
            array_unshift($form['#submit'], 'create_vector_user_free_trial_form_submit');
            break;
    }
}

function create_vector_user_free_trial_form_validate($form, &$form_state) {
    // this function runs correctly
}

function create_vector_user_free_trial_form_submit($form_id, &$form_state) {
     // add your code here
    $form_state['values']['op'] = 'Submit';
}

```

(please note to my module is called test1 you need change this with the name of your module)

---
Tags: webforms, forms
---


# Question
Title: How To add user name and profile picture to Superfish menu
I am using Superfish module to obtain drop down menus. I would like to have one *parent* menu link as a *username* and *user image*, then *child* menu links will be under it when hovered over.

Example of this is airbnb.com when logged in.

I do not know much PHP and do most of my work with CSS and already created modules.

# Answer
I found a somewhat unnecessarily complex, but working, answer.

1. Install Menu Views module.
2. Create a View User List Block and add a relationship *User:Profile*.
3. Add a contextual filter *user:uid* and set *Provide default value* as *User ID from logged in user*.
4. Add 2 fields, *User: Picture* and *User: Name*
5. Change Access to *Role* and choose all roles that should see this View.
6. Add CSS classes and style

Note: At this time a issue exists with Menu Views and requires a fix found here.
> 1 votes

---
Tags: users, navigation
---


# Question
Title: Is there a way to export ALL translations into a single .PO file?
To translate my website, I need to export translations one by one per group type.

This gets to be confusing as some fields share core terms ect...

Is there a way to do a consolidated ONE .po file for all translations?

# Answer
Each entry in .po file has only two strings;

```
msgid untranslated-string
msgstr translated-string

```

Thus, by it's very nature it can only keep two languages: original and one translation. So no, there is no way to do it because format does not support that. For details, see documentation.
> 2 votes

---
Tags: i18n-l10n
---


# Question
Title: Difference between $form_state['values'] and $form_state['input']
Can someone please tell me the difference between these two variables?

```
$form_state['values']
$form_state['input']

```

Optionally some example of action they are used with. I'm wondering especially about using with ajax in drupal form. Which of these should I use in ajax callback to get input values from the form?

# Answer
> 28 votes
The crucial difference here is that in most cases you should be using $form\_state\['values'\]; since the data on the $form\_state\['input'\] array is raw and unvalidated.

$form\_state\['input'\] is useful for multi-step forms, assuming you are familiar with how to safely handle raw input.... See form\_builder for more information...

# Answer
> 1 votes
Unless you know what you are doing, you `$form_state['values']` it is the processed form values. `$form_state['input']` is the raw data. See the code for form\_builder: https://api.drupal.org/api....

# Answer
> 0 votes
`$form_state['values']` should be uses in most of the cases as `$form_state['input']` hold the raw and invalidated value. Also in `$form_state['values']` default values are passed when submission of form fails, but in case of `$form_state['input']` NULL is passed.

# Answer
> 0 votes
In 99.9% of cases, `$form_state['values']` and `$form_state['input']` are identical.

But -- beware of a portion of the 1%, particularly when using the **date\_popup** field, as it's input is stored in 'input', but NOT in the 'values' array.

# Answer
> -5 votes
In the drupal\_form\_submit function, you can see the following code :

```
// Populate $form_state['input'] with the submitted values before retrieving
// the form, to be consistent with what drupal_build_form() does for
// non-programmatic submissions (form builder functions may expect it to be
// there).
$form_state['input'] = $form_state['values'];

```

So it is exactly the same.

---
Tags: forms
---


# Question
Title: How do I display a field from a referenced user?
I have a content type A with a reference to a user and I would like to show a specific field from that user in nodes of that content type.

How can I achieve this?

# Answer
> 2 votes
You might achieve this with Views, by creating a view for nodes of that content type, and then adding a "relationship" to the user. The user fields will then become available for you to display.

You can find an introductory tutorial to start using Relationships with Views in "How relationships work in Views and how to add a referencing entity relationship".

# Answer
> 1 votes
Make a display mode for user which only contains one field:

admin/structure/display-modes/view/add/user

Then format the entity reference field in your node with that view mode, and you only have that specific field in your node display.

---
Tags: 8
---


title: How to add custom html inside form

text:
# Question
Title: How to add custom html inside form
I need to put some custom html tags and code inside the form elements am creating using form api . I defined a fieldset and need to come the html under this fieldset , code sample :

```
  $general_wb_vars = array(
        'wb_debug'=>array('type'=>'select','values'=>'ERR,OFF','default_value'=>'OFF','label'=>'Debug','description'=>''),
        'wb_cache'=>array('type'=>'radio','values'=>'Yes,No','default_value'=>'No','label'=>'Cache','description'=>''),
        'wb_ip'=>array('type'=>'textfield','values'=>'','default_value'=>'192.168.1.1','label'=>'IP','description'=>'')
        );
        $numofrepeat = 4;
        if($form_id=='my-form-id'){
                $form['fieldsetm'] = array('#type' => 'fieldset',
                                         '#title' => t('Weblogic configurations'),
                                         '#weight' => 10,
                                );

                for($i=1;$i<=$numofrepeat;$i++){
                foreach($general_wb_vars as $id => $setts){
                   $form['fieldsetm']['field_p_'.$id.'['.$i.'][value]'] = array('#type' => $setts['type'],
                                        '#title' => t($setts['label']),
                                        '#default_value' => $setts['default_value'],
                                        '#description' => t($setts['description']),
                                        '#attributes' => array('id'=>$id.$i),

                                  );
                                if($setts['type']=='select'){
                                        $form['fieldsetm']['field_p_'.$id.'['.$i.'][value]']['#options'] = explode(',',$setts['values']);                                      }
                                if($setts['type']=='radio')
                                        $form['filedsetm']['field_p_'.$id.'['.$i.'][value]']['#values'] = explode(',',$setts['values']);
                                        $form['fieldsetm']['some_markup'] = array(
                                           '#type' => 'item',
                                           '#markup' => '---------------------------------------------------------------------',
                                         );
                                }
                }

```

# Answer
> 1 votes
You're looking at Drupal 7 form api reference perhaps. For drupal 6 according to the form api you just need to put your HTML string in `#value` as the default D6 `#type` is `markup`

---
Tags: 6, forms
---


# Question
Title: How to assign role(s) for a new user based on node_field?
I am in a process of finishing a workflow. I have done the most things with rules. To my surprise I found a feature is missing in this great module ...

I have created a content type called "my\_cont\_type". A content of this content type will be created only once by admin. A link will be provided for the admin to go and change the option whenever he wants.

It has a field called "`my_field`". It is a list box type where user can select multiple options. The options are "Role1" , "Role2", and "Role3".

On creating this content or after created admin can go and edit the same. After edited the same from that time the new user who all registering or created they have to come under the corresponding role selected in that node. I have those three roles already in my application.

For example:

* When Role1 and Role2 is selected the new user has to register with these roles1&2 enabled.
* When Role1 and Role3 is selected the new user has to register with these roles1&3 enabled.
* When Role3 is selected the new user has to register with only roles3 enabled.

Can I accomplish this using the Rules module?

I tried but I doesn't find any attributes regarding node or content type in condition when using the "After new user saved" event.

# Answer
> 0 votes
Yes this should be possible using the Rules module.

When trying to do so, make sure to add a Rules condition `Entity has field` (related to your `my_field` field). That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

---
Tags: rules, users
---


# Question
Title: What's the difference between Page manager and Panels?
I'm writing this question, because I see confusion all over the Drupal community about "what is Page manager", and "what is Panels".

# Answer
> 49 votes
**Ctools**

In Ctools, there is a sub-module called "Page manager". This module, at it's core, is a graphical user interface to hook\_menu. It allows you to either create new paths in the system, or take over some of the ones provided by Core.

**Page manager**

Once Page manager manages a path for you, it can do several different things with it. Out of the box, it can provide redirects for you. One common use case for this, is to deny access to nodes that lack proper theming because they are not meant to be viewed on their own, such as "Fact boxes" or "Image nodes". Another is to redirect from a term view to a Solr search of the same term.

One of the main benefits of Page manager, is that it introduces a way of dealing with "Context", not to be confused with the module Context. The kicker here, is that Panes, which are "slightly smarter blocks", can *declare their dependencies* to the system, and them have the actual arguments (called Contexts) passed in *dependency injection*-style.

For those unfamiliar with DI, but familiar with Drupal, this, for example, allows you to never need to use menu\_get\_object again to get "That one and only node referenced from the menu path". What if there's more than one node in the path? Or if you really want to base the block on a node from an entity reference? This becomes a non-issue with Page manager, making *all* blocks (panes) much more flexible and re-usable.

**Panels**

The most common use case however, is to hand over the *layout*, and *rendering* of the path, to Panels. Panels provides tools to define layouts, either in code or directly in the browser, and the lets you place content directly in the browser.

**Conclusion**

Both of these modules are very powerful, and relatively poorly documented, which has lead a lot of people to be frustrated about them. Understanding how to use them is however well worth it if you are building a larger site, especially since their approach to handling "pages", as well as layout, looks like they are going into Drupal 8 core, courtesy of EclipseGC's SCOTCH initiative. Relevant sandbox project

**Further reading**

Examples of other interesting things one can do with these tools:

1. If Context is used as a *sectioning* tool, Panels can work in tandem with it and be used as a layout tool.
2. Panels can interact with Display suite to provide it with a nice drag-and-drop UI.
3. Page manager and Contextual Administration can help building in "Context" sensitive menues and other helpful things for site admins/editors.

# Answer
> 1 votes
In Drupal 7, Page Manager was the foundation of the Panels module.

"Learn Page manager" is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. Here is a summary of the entire set of videos about this topic (quote from the link above):

> * Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
> * The screencast series is targeted at experienced Drupal developers.
> * Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
> * Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
> * Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
> * Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
> * Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about the Panels module.

# The future of Page Manager

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

> It supports the creation of new pages, and allows placing blocks within that page.
>
> Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
>
> Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
>
> It utilizes the core `Conditions`, `Context`, and `Blocks` APIs to accomplish this.

---
Tags: panels, chaos-tool-suite
---


# Question
Title: Commerce partial payment : pay deposit at checkout and full settlement later
In a Travel Booking website, how can I configure checkout so that customers **pay only a n% deposit** of the order total at checkout (off-site payment ATOS solution) ?

If the order is created :

* less than 30 days before departure, customer pay 100% of order total at checkout.
* between 30 and 90 days before, they pay 30% at checkout.
* more than 90 days before, they pay 10% at checkout.

Full settlement must be paid before travel departure (reminder emails)...

There are few contrib modules about deposit or partial payment :

* I had a look at Commerce deposit sandbox but it seems to be a per product solution, while I need a global cart approach.
* I began to hack Commerce Partial Payment for my own need. The module alters `checkout_form_alter` and provides a textfield where the customer can input a deposit value just before payment, so I pre-calculated deposit amount as per my rules above, filled the field with it, and hide it.

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * Alters whichever commerce checkout page includes the commerce_payment
 * checkout pane and adds the amount element to the payment details.
 */
function commerce_partial_payment_form_commerce_checkout_form_alter(&$form, &$form_state, $form_id) {

  $panes = commerce_checkout_panes(array('pane_id' => 'commerce_payment'));
  $checkout_page = $panes['commerce_payment']['page'];
  if ($form_id != "commerce_checkout_form_$checkout_page" || !commerce_partial_payment_access($form_state['order'])) {
    return;
  }

  //setting up my own deposit value
  $deposit = vts_commerce_deposit();

  // If a values has already been set then use it as the value for the amount.
  // Otherwise, default it to the balance of the order.
  $default = NULL;

  if ($deposit > 0) {
     $default = $deposit ;
  }
  elseif (isset($form_state['values']['commerce_payment']['payment_details']['amount'])) {
    $default = $form_state['values']['commerce_payment']['payment_details']['amount'];
  }
  else {
    $balance = commerce_payment_order_balance($form_state['order']);
    $default = commerce_currency_amount_to_decimal($balance['amount'], $balance['currency_code']);
  }

  // Add the amount to the payment details form.
  $form['commerce_payment']['payment_details']['amount'] = array(
    '#type' => 'hidden',
    //'#title' => t('Amount'),
    '#weight' => -10,
    '#required' => TRUE,
    '#default_value' => $default,
  );
}

```

But I got stuck there because that value, passed to `$form['commerce_payment']['payment_details']['amount']`, is not the one sent to the remote payment server (so that AFAIK, this module can't work)...

I also tried to set any other parts of `checkout_form_alter` ( `$form` and `$form_state`) where the order amount was repeated with `$deposit`, this NEVER changes the value set for payment at next step...

## Question(s)

Using the above solution, at what point of checkout / which form can I alter the amount to be paid, replacing order total by deposit value ?

Indeed, I couldn't find how to *separate* the order total from the amount to pay... with correct data along the process : order total / paid deposit / balance order to pay later.

If there is a more D7 commerce way to implement this deposit issue, with rules or whatever, I'll be glad to learn it.

# Answer
I got it working the following way.

In order to get Commerce Deposit work with the *deposit calculation you like to* instead of a *customer deposit input*, patch it as following :

```
function commerce_partial_payment_form_commerce_checkout_form_alter(&$form, &$form_state, $form_id) {
  //... line 93
  $acompte = MODULENAME_deposit_calculation($form_state['order']) /100;
    if (!is_null($acompte) && $acompte > 0) {
      $default = $acompte;
    }
  //... line 109 Add the amount to the payment details form,in a hidden field.
  $form['commerce_payment']['payment_details']['amount'] = array(
    '#type' => 'hidden',
  //...
}

function commerce_partial_payment_checkout_validate($form, &$form_state, $checkout_pane, $order) {
  //... line 261
  $amount['amount'] = MODULENAME_deposit_calculation($order)  /100;
  //...
}

function commerce_partial_payment_checkout_submit($form, &$form_state, $checkout_pane, $order) {
  //...line 317
  if ($pane_values['payment_methods']) {
    $amount = MODULENAME_deposit_calculation($order) /100;
    $order->data['atos']['request']['amount'] = $amount;
    if (!empty( $amount)){
      $amount['amount'] = $amount;
  //...
}

```

As the sandbox doesn't properly *send the deposit amount to off site payment*, we need to hook the payment method :

In a METHOD\_PAYMENT.api.php file

```
function hook_METHOD_PAYMENT_request_alter(&$settings) {
  //no example
}

```

Now send to off site payment the deposit amount instead of order total :

```
function commerce_partial_payment_PAYMENT_METHOD_request_alter(&$settings) {
  $order = commerce_order_load($settings['order_id']);
  $deposit = MODULENAME_deposit_calculation($order);
  $settings['amount'] = $deposit;
}

```

Last, *add a price component deposit* below Total to inform the customer what he's going to pay.

```
function commerce_partial_payment_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  //Add a deposit line to price components
  $deposit= MODULENAME_deposit_calculation($entity);

  $components['deposit'] = array(
      'title' => t('Deposit'),
      'price' => array(
        'amount' => $deposit,
        'currency_code' => $components['commerce_price_formatted_amount']['price']['currency_code'],
        'data' => '',
      ),
    'weight' => '200',
  );
}

```
> 5 votes

# Answer
I think that alter the form at checkout is not the place that interests your payment method ; only the total amount in the actual order is taken in account, imo.

So what you have to do is alter it at checkout form submit, either with custom module or rules.

The data taken in account is `$order->commerce_order_total['und'][0]['amount']`
> 0 votes

---
Tags: commerce, rules, bookings
---


# Question
Title: How to setup event registration and paypal payment?
We have events and we take registrations for them. Entity Registration module is installed for that purpose and it's working great. Now, since those events are paid events, we want to implement *PayPal payment* method as well.

The problem is we need to **combine** the registration process and the paypal payment into one process. That said, user should click the button *Register & pay* and that should do 2 things:

1. Register the user for the event (this is already working as a part of Entity Reg module)
2. Redirect the user to *PayPal payment gateway*

Any suggestions on how to achieve this?

# Answer
You should use Registration Commerce module. This module acts as a integration point between entity registration and drupal commerce enabling you to implement paid registration using entity register. Also use Commerce paypal for paypal integration with drupal commerce.
> 0 votes

# Answer
I think the Commerce Paypal IPN Rules integration module should fit your requirements. Here is a quote about it (from the module's project page):

> ... comes to give modular capabilities for Paypal IPN handling.
>
> Combined with Drupal Commerce, Rules and the Paypal payment method, using this module you will be able to change your site workflow and logic.
>
> As an example, while the "Commerce subscription products PayPal" integrates with the IPN to start/stop user subscription, but depends on specific user fields and content types, in this module you will be able to achieve the same, but for your own selected fields, content types, etc.
> -1 votes

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: How to enable spell check functionality of Apache Solr using contrib modules?
Apache Solr is designed to provide inline spell checking which basically makes suggestions if it thinks you have misspelt a word. I am trying to work out what is the most simplest way of implementing this. I have not been able to find any specific contributed modules which provide this functionality.

Is it possible to set this up with contrib modules or must one set it up directly in Solr configuration?

# Answer
Use search api spellcheck module for this https://www.drupal.org/project/search\_api\_spellcheck
> 0 votes

---
Tags: search
---


# Question
Title: Contextual filters in Views - Filter by taxonomy
I have a View with contextual filters. I filter by **Content Has Taxonomy ID**. The problem is that the website is multilanguage, and the name of the taxonomy may change, have commas, non-common characters (cyrillic, for example), be too long and could be, in fact, different from the friendly URL.

My idea (which I have used in other projects) is to have the URL in this way:

www.example.com/en/products/sport-shoes

or

www.example.com/ru/продукты/спортивная-обувь

and from the URL, retrieve the parameters with

```
$url_arr = explode("/", $_SERVER['REQUEST_URI']);

```

In this case, **$url\_arr\[2\]** would contain the taxonomy description(sport-shoes or спортивная-обувь in Russian), which is what I look for. The taxonomy name could be completely different, for example: "Sport shoes, complements, and other wearables".

Then I make a query to the database with **db\_query()** searching by description field ( or better use a **EntityFieldQuery**), get the ID (the product will be associated to both taxonomy terms and I only need one), and pass the ID to the contextual filter, instead of letting the module **Views** to guess the ID from the URL (Term name converted to Term ID).

Is this procedure (which works) too convoluted? Is there a simpler and elegant way of doing this?

# Answer
> 1 votes
Retrieving the term ID by name has one considerable downside: If term names change, links may become invalid.

A safer option would be the use of aliases. For each of your terms, generate a URL alias per language that points to the internal view path (containing the term IDs). That way your view won't require custom logic to retrieve the term ID.

You could then expand on that approach and use e.g. the Redirect module to keep track of alias changes.

If you still want to stick to your approach, keep in mind that Drupal provides various functions to deal with paths and arguments. In your case, that one-liner can be simplified to:

```
$url_arr = arg();

```

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


# Question
Title: Event "After cloning a node" by node clone module is not working
I am trying to use the event "After cloning a node" provided by Node clone module for Rules integration but its not working.Do any one came across this issue before?

I have created the issue as a bug in issue queue of node clone module.

Any pointers on this?

# Answer
Your issue seems to be confirmed by some other users also now.

Comment #9 of that issue contains a patch that might possibly solve it.

Another possible solution (patch) is included in comment #8 of that issue, proposed by the module maintainer. With a comment like "*Not sure about the use case ...*"

The issue is currently in status "**Needs review**", so maybe you might (still) have an appropriate use case to get that issue in RTBC status?
> 1 votes

---
Tags: 7, rules
---


title: reorder fields on user profile page

text:
# Question
Title: reorder fields on user profile page
I can't find any solution to reorder some fields on user profil pages (like user/%/edit). At first I see User photo and language options. But in field options I have set another fields to be applied to the first position.

I have no possibility to move some fields to wished position. Have you any advice, how to do it? Thank you very much. Peter.

# Answer
You need to go to "Admin \> Configuration \> People \> Account Settings \> Manage display". You will be able to reorder the fields from there. If you want to remove some of them from the display, you can select "Hidden" from the menu in the "Format" column.

**EDIT:** The profile picture, however, is managed separately by Drupal, not as a field. If you want to be able to manage it, a workaround might be to disable the default Drupal profile picture (Admin \> Configuration \> People \> Accounts \> Personalization) and to create a new Image field to display the picture, which you can treat as any other regular field. There are even some modules that create the field for you, like user picture field.
> 1 votes

# Answer
1. Navigate to the Content types page **(Administer \> Structure \> Content types)**.
2. In the table, locate the row that contains your content type and click the manage fields link.
3. Locate the field you want to re-order, and drag the four-headed arrow icon up or down.
4. Click **Save**.

When users create an Article, they will now see the Image field displayed immediately after the Title field:

**OR**

You can do it by editing `user-profile.tpl.php`

and arrange fields as your requirement like:

```
 <?php
 print render($user_profile['field_age']);
?>

```
> 0 votes

---
Tags: forms, users
---


# Question
Title: Taxonomy term reference field only from top level terms of a vocabulary
I have a multilevel taxonomy term vocabulary

1. Degrees and
i. Specializations

I'd like to use it in two content types. In one case only the top level terms should appear for users, while in other case users can choose only from the 2nd level (this one can be solved by Hierarchical Select module).

Is there any extension of taxonomy form elements that can limit the level that users can choose from?

# Answer
> 5 votes
If you replace your taxonomy term reference field with an Entity reference field you will be able to use the Reference field option limit module to restrict the available options for dependant fields. If you need to apply further restrictions you can also generate your options lists via special entity reference views.

Note however that by switching the field type to entity reference you will no longer be able to use taxonomy term specific fields and filters for those fields in views.

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


# Question
Title: How to hide horizontal tabs on page load?
I have installed the field group module for horizontal tabs, so I can put several nodes in a tab via *rendered node*.

The question is simple:

How can I hide these tabs on page load? I want to show the links but only when the user clicks on it, the tab shows up.

Thank you for your collaboration.

Gael

# Answer
> 1 votes
Following @Janpan suggestion, I have hidden the tab content and then added a click function, so I have shown the rendered node inside the div.

here the code:

```
 $("fieldset").hide();
                $(".tab a").click(function(){
                    $("fieldset").slideDown({
                        direction: "up"
                        }, 300);
                });

```

---
Tags: nodes, entities
---


# Question
Title: Why does my Drush post_make hook not run from bash script?
I have written a drush extension that runs some post\_make operations.

It's all good when I run `$ drush make` normally.

I have also written a bash script, which with some arguments, perfoms also drush site-install and other file structure stuff. The problem is when I execute this script and bash runs my drush make, my extension and post\_hook is not running.

I know it's more of a bash permissions/ownership thing or something, than a drush issue, but does anyone have an idea?

My extension lives in ~/.drush/extension.

I'm using drush 5.9 and this is the actual script.

# Answer
> 1 votes
Do you run the script as the same user that you run the `drush make` directly as? Or do you perhaps run the script from `cron`? Check to make sure that your $HOME environment variable is pointing to the expected directory; if $HOME is not set, then Drush will not find your commandfiles.

---
Tags: drush
---


# Question
Title: Go to Checkout Complete without checkout payment
I created a field **field\_cel\_ck\_scholar**. It's a boolean. I created this field in a customer profile type. My customer profile type is added in a pane in my checkout.

When this field is equal TRUE, I want by pass the checkout/%/payment's page and to redirect the checkout/%/complete's page.

It's possible ?

I try to use Rules like so:

```
{ "rules_by_pass" : {
"LABEL" : "by pass",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout", "commerce_rules_extra" ],
"ON" : { "commerce_rules_extra_process_checkout_page" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "site:current-cart-order" ],
      "field" : "field_cel_ck_scholar"
    }
  }
],
"DO" : [
  { "commerce_checkout_complete" : { "commerce_order" : [ "site:current-cart-order" ] } }
]
}
}

```

It doesn't work, why?

# Answer
> 0 votes
Seems like you're trying to create a Rules condition like so:

> if field `field_cel_ck_scholar`=TRUE

whereas you have such field added in your 'customer profile type'.

Looking at the rule you create so far, your Rules condition seems incomplete:

* you already do have the `entity_has_field`, that's OK, and actually one (out of 2) ways to be able to create such condition like "if field `field_cel_ck_scholar`=TRUE".
* your Rules condition seems to be missing the actual *Data comparison* condition, in which you actually specify that "if field `field_cel_ck_scholar`=TRUE".

So try adding such Data Comparison condition, and check if that solves your issue. Not sure if it will be the **only** reason why "It doesn't work", but for sure **a** reason why it cannot work.

PS: refer to my answer to the question about How to specify a Rules condition related to select list values? for a similar (though not duplicate) question, which includes some more details (and background info) about such `entity_has_field`.

---
Tags: entities, rules, commerce
---


title: Recent log messages

text:
# Question
Title: Recent log messages
Is there a way to view more than just the "recent" log messages in Drupal 7?

I need to look further back for a customer, but the "recent" is only showing messages for today.

Is it possible to search a date range or something?

Any help with this would be greatly appreciated!

Thank You!! Nicole

# Answer
> 2 votes
Drupal only stores a limited number of log entries, determined by the *"Database log messages to keep"* setting located at Administration \> Configuration \> Development.

However, most web servers keep a so called "access log", a file containing an entry for each URL that was requested.

In some cases and configurations the information (e.g. who created a user) can be inferred from the access log.

# Answer
> 2 votes
If you're referring to the logs at `/admin/reports/dblog` \- what you see is all that is available.

Depending on your server configuration, you can likely find some more info in your php error logs, the location and the amount of data the error log stores varies based on the server configuration.

# Answer
> 1 votes
To view more than the Recent log messages at `admin/reports/dblog` you need to use the error log or/and the access log of the webserver.

I'm not sure if in your case is Apache, NGINX or if you are using a webhosting service, some of them have an option to check this logs.

In the future, if you want to keep more messages at `admin/reports/dblog`, you can adjust that at `admin/config/development/logging` and increase the amount on the "Database log messages to keep" option. **Careful** with this option, a value like "1000000" could have a negative impact on the website performance.

If you don't have a shared hosting environment and you have ssh access to the webserver, I think the **best option** is to enable the syslog module. This module logs events by sending messages to the logging facility of your web server's operating system (syslog).

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


# Question
Title: How to add autocomplete filter to a views based on webform results?
I have a views that lists webform results. There are some fields such as **name, e-mail address, city** etc comes from webform submission.

I want an **exposed filter** to filter the views based on city. This can be done and a search input appears at the top of the views but there is a problem: you should enter the full city name and then submit. **There is no autocomplete or select list feature.**

There is a module called Views Autocomplete Filters for this purpose but doesn't work with webform results data.

There was a sandbox project called Webform Selectable Filters before but doesn't exist now.

## So, how to add an autocomplete exposed filter to a view that is based on webform results data?

# Answer
> 1 votes
I did this in my custom module :

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

  if($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if($view->name == 'your_view_name') {
     $form['data']['#autocomplete_path'] = 'example/autocomplete';
   }
  }
}

```

**'#autocomplete\_path' =\> 'example/autocomplete'** defines an autocomplete callback for our textfield.

When user types something into our textfield, Drupal sends a request via this url to send data you input and to receive suggestions via json if there are any.

To make Drupal aware of this path, let’s add it to the menu system(hook\_menu):

```
$items['example/autocomplete'] = array(
  'page callback' => '_module_name_autocomplete',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
);

```

Now we need to create a \_module\_name\_autocomplete function which will look for a suggestion and return it to the user.

```
function _module_name_autocomplete($string) {

  $matches = array();
  // Some fantasy DB table which holds cities
  $return = db_select('webform_submitted_data', 'w')
  ->fields('w')
  ->condition('w.cid', 'your_component_id', '=')
  ->condition('w.data', '%' . db_like($string) . '%', 'LIKE')
  ->execute();

  // add matches to $matches
  foreach ($return as $row) {
   $matches[$row->data] = check_plain($row->data);
  }

 // return for JS
 drupal_json_output($matches);
}

```

---
Tags: 7, views, webforms
---


# Question
Title: How to remove wrapper when rendering page region?
```
 $sidebar_second = render($page['sidebar_second']); print $sidebar_second;

```

generate by default

```
 <div class="region region-sidebar-second sidebar">
     <div class="region-inner clearfix">   </div>
 </div>

```

How can i remove these wrappers ?

# Answer
Add a copy, or edit the existing copy, of the core (or your theme/sub-theme's) region.tpl.php file, to your active theme. You can change the wrapping markup to whatever you like in there.

Clear the cache, and you're done.
> 4 votes

---
Tags: 7, theming
---


title: Redirect user to same page on login

text:
# Question
Title: Redirect user to same page on login
I know there are a couple modules other there that handle login redirects like Login Destination, LoginToboggan, Login Redirect and Rules. However, they all seem to only allow strict URLs. I would like users to be redirected to the same page they logged in on. The default behaviour of Drupal appears to redirect users to the previous page on login.

Since I am using a login modal, redirecting people to the previous page doesn't work well.

How can I redirect users to their current page when using a login modal that handles the login through AJAX? I would appreciate a solution that could be placed in template.php maybe using hook\_user\_login()

# Answer
Take a look at the implementation in `user_login_block()`, particularly this line:

```
$form['#action'] = url(current_path(), array('query' => drupal_get_destination(), 'external' => FALSE));

```

This will add the `destination` parameter to the URL, which takes precedence over any other arguments passed to `drupal_goto()` (like `$form_state['redirect']`).
Depending on how you create your modal, the easiest way would therefore be to simply append the `destination` argument for the current page to the form action.
> 1 votes

---
Tags: 7, users, redirection, authentication-authorization
---


# Question
Title: How to specify the order of Javascript calls?
I have a call to `drupal_add_js()` in `hook_block_view_alter()` and another one in `template_preprocess_page()`.

I need that the order in which the Javascript is printed in the screen of the browser is just as written. What is the preference in which the content is loaded in the page? Can it be controlled?

# Answer
If you want to enforce the order of your scripts, declare them as libraries via hook\_library() and list one as dependency for the other.
> 5 votes

---
Tags: 7, javascript
---


# Question
Title: How to make a new field type visible to the Rules module?
I have installed the Examples for Developers module, and enabled the Field Example submodule. It creates a new field type called `field_example_rgb`.

I've added this field to a new content type. I'm trying to set and/or display the value of the field using Rules \- to no avail. Rules does not "see" the field in the node.

I've tried adding a file called field\_example.rules.inc that implements hook\_rules\_data\_info(), still without luck. Can someone please help me figure out how to make the field visible to Rules?

This is the code of the hook\_rules\_data\_info()

```
   function field_example_rules_data_info() {
  return array(
    'field_example_rgb' => array (
      'label' => t('example color rgb'),
      'wrap' => TRUE,
      'property info' => array(
        'rgb' => array(
            'type' => 'text',
            'label' => 'RGB',
        ),
    ),
    ),
  );
}

```

# Answer
> 0 votes
Just add the `property_type` key to the array you already have, like so:

```
'property_type' => 'text',

```

With that added line, the Entity API knows how to handle that field.

For a more complex field, such as fields with more than one database column, it is not enough to simply declare the property type. You need to specify further callbacks that may alter the generated property info. To do so, you need to use the key `property_callbacks` to add a custom callback function that will provide the extra metadata required. For example:

```
'property_type' => 'field_example_rgb',
'property_callbacks' => array('field_example_rgb_property_info_callback'),

```

**Source**: Describe field properties to make custom fields work with Entity Metadata Wrappers, which includes some more info about this topic also.

---
Tags: entities, rules
---


# Question
Title: Add bulk products drupal commerce: Warning: Invalid argument supplied for foreach() en form_type_checkboxes_value() line 2337 form.inc
I am workin on a commerce site and every product has many attributes and there are many combinations for each display. I am using Commerce Bulk Product Creation so I can add products quicly. The problem is that when I try to add many products in one shoot using this module I have a white screen and The warnng is: Warning: Invalid argument supplied for foreach() in form\_type\_checkboxes\_value() (lne 2337 de xxx/includes/form.inc). Any help would be great.

# Answer
The problem was because I am creating too many products at once. Not supported by the database or the hosting. It colapses and the foreach sends the warning. The result was a white screen.
> 0 votes

---
Tags: commerce
---


title: Illegal choice has been detected

text:
# Question
Title: Illegal choice has been detected
I've been trying to develop this PhoneGap app to create a node of a specific type on a Drupal server. I got services installed, created endpoints and all. However when I tried, I got '`406: Not acceptable. Illegal operation detected`'. When I look at recent logs, I see a '`Not allowed value x`' and additional `Illegal offset type in isset or empty` for all my dropdowns. Any ideas how come?

**My HTML**

```
<div id="appHolder">
    <div id="topHolder">
        <div id="logoHolder">
            <img id="logo" src="img/logo.png" />
        </div>
        <div id="titleHolder">Başvuru yap</div>
    </div>
    <div id="contentHolder" class="apply">
        <label for="profilepicture">Profil fotoğrafı</label>
        <input type="file" id="profilepicture" name="field_oyuncu_fotografi_value" />
        <div id="canvasparent">
            <img id="picture" />
            <canvas width="400" height="300" id="canvas"></canvas>
        </div>
        <input type="text" id="name" placeholder="Adı & Soyadı" required name="title" />
        <input type="number" id="tckn" placeholder="TC Kimlik No" required name="field_tc_kimlik_no_value" />
        <select id="sgk" required name="field_sgk_durumu_value">
            <option selected disabled style="display:none">- SGK durumu -</option>
            <option value="devam_ediyor">Devam ediyor</option>
            <option value="emekli">Emekli</option>
        </select>
        <input type="tel" id="tel" placeholder="Telefon" required name="field_telefon_value" />
        <input type="tel" id="tel2" placeholder="Telefon 2" required name="field_telefon2_value" />
        <div class="description">Size ulaşamadığımız durumda ulaşabileceğimiz bir yakınınız</div>
        <input type="text" id="address" placeholder="Adres" required name="field_adres_value" />
        <select id="city" required name="field_yasadigi_sehir_value">
            <option selected disabled style="display:none;">- Yaşadığı şehir -</option>
            <option value="01">Adana</option>
            <option value="02">Adıyaman</option>
            <option value="03">Afyon</option>
            <option value="04">Ağrı</option>
            <option value="05">Amasya</option>
            <option value="06">Ankara</option>
            <option value="07">Antalya</option>
            <option value="08">Artvin</option>
            <option value="09">Aydın</option>
            <option value="10">Balıkesir</option>
            <option value="11">Bilecik</option>
            <option value="12">Bingöl</option>
            <option value="13">Bitlis</option>
            <option value="14">Bolu</option>
            <option value="15">Burdur</option>
            <option value="16">Bursa</option>
            <option value="17">Çanakkale</option>
            <option value="18">Çankırı</option>
            <option value="19">Çorum</option>
            <option value="20">Denizli</option>
            <option value="21">Diyarbakır</option>
            <option value="22">Edirne</option>
            <option value="23">Elazığ</option>
            <option value="24">Erzincan</option>
            <option value="25">Erzurum</option>
            <option value="26">Eskişehir</option>
            <option value="27">Gaziantep</option>
            <option value="28">Giresun</option>
            <option value="29">Gümüşhane</option>
            <option value="30">Hakkari</option>
            <option value="31">Hatay</option>
            <option value="32">Isparta</option>
            <option value="33">Mersin</option>
            <option value="34">İstanbul</option>
            <option value="35">İzmir</option>
            <option value="36">Kars</option>
            <option value="37">Kastamonu</option>
            <option value="38">Kayseri</option>
            <option value="39">Kırklareli</option>
            <option value="40">Kırşehir</option>
            <option value="41">Kocaeli</option>
            <option value="42">Konya</option>
            <option value="43">Kütahya</option>
            <option value="44">Malatya</option>
            <option value="45">Manisa</option>
            <option value="46">K.Maraş</option>
            <option value="47">Mardin</option>
            <option value="48">Muğla</option>
            <option value="49">Muş</option>
            <option value="50">Nevşehir</option>
            <option value="51">Niğde</option>
            <option value="52">Ordu</option>
            <option value="53">Rize</option>
            <option value="54">Sakarya</option>
            <option value="55">Samsun</option>
            <option value="56">Siirt</option>
            <option value="57">Sinop</option>
            <option value="58">Sivas</option>
            <option value="59">Tekirdağ</option>
            <option value="60">Tokat</option>
            <option value="61">Trabzon</option>
            <option value="62">Tunceli</option>
            <option value="63">Şanlıurfa</option>
            <option value="64">Uşak</option>
            <option value="65">Van</option>
            <option value="66">Yozgat</option>
            <option value="67">Zonguldak</option>
            <option value="68">Aksaray</option>
            <option value="69">Bayburt</option>
            <option value="70">Karaman</option>
            <option value="71">Kırıkkale</option>
            <option value="72">Batman</option>
            <option value="73">Şırnak</option>
            <option value="74">Bartın</option>
            <option value="75">Ardahan</option>
            <option value="76">Iğdır</option>
            <option value="77">Yalova</option>
            <option value="78">Karabük</option>
            <option value="79">Kilis</option>
            <option value="80">Osmaniye</option>
        </select>
        <input id="email" type="email" placeholder="E-posta" required name="field_e_posta_value" />
        <select id="gender" required name="field_cinsiyet_value">
            <option selected disabled style="display:none;">- Cinsiyet -</option>
            <option value="bay">Bay</option>
            <option value="bayan">Bayan</option>
        </select>
        <fieldset>
            <legend>Kategorisi</legend>
            <input type="checkbox" id="oyuncu" name="field_kategorisi_value" value="oyuncu">Oyuncu
            <br>
            <input type="checkbox" id="cocuk_oyuncu" name="field_kategorisi_value" value="cocuk_oyuncu">Çocuk oyuncu
            <br>
            <input type="checkbox" id="yardimci_oyuncu" name="field_kategorisi_value" value="yardimci_oyuncu">Yardımcı oyuncu
            <br>
            <input type="checkbox" id="stand_hostesi" name="field_kategorisi_value" value="stand_hostesi">Stand hostesi
            <br>
            <input type="checkbox" id="yesilcam" name="field_kategorisi_value" value="yesilcam">Yeşilçam
            <br>
        </fieldset>
        <label for="dob">Doğum Tarihi</label>
        <input type="date" id="dob" required name="field_dogum_tarihi_value" />
        <select id="height" required name="field_boy_value">
            <option selected disabled style="display:none;">- Boy -</option>
            <option value="150">1.50 - 1.60</option>
            <option value="160">1.61 - 1.70</option>
            <option value="170">1.71 - 1.80</option>
            <option value="180">1.81 - 1.90</option>
            <option value="190">1.91 - 2.00</option>
            <option value="200">2.01 - 2.10</option>
        </select>
        <select id="weight" required name="field_kilo_value">
            <option selected disabled style="display:none;">- Kilo -</option>
            <option value="45">40 - 50</option>
            <option value="55">51 - 60</option>
            <option value="65">61 - 70</option>
            <option value="75">71 - 80</option>
            <option value="85">81 - 90</option>
            <option value="95">91 - 100</option>
            <option value="105">101 - 110</option>
        </select>
        <select id="eyecolour" required name="field_goz_rengi_value" class="chosen-processed">
            <option selected disabled style="display:none;">- Göz rengi -</option>
            <option value="akahve">Açık kahve</option>
            <option value="kkahve">Koyu kahve</option>
            <option value="siyah">Siyah</option>
            <option value="mavi">Mavi</option>
            <option value="yesil">Yeşil</option>
            <option value="ela">Ela</option>
            <option value="gri">Gri</option>
        </select>
        <select id="skincolour" required name="field_ten_rengi_value" class="chosen-processed">
            <option selected disabled style="display:none;">- Ten rengi -</option>
            <option value="esmer">Esmer</option>
            <option value="beyaz">Beyaz</option>
            <option value="siyahi">Siyahi</option>
            <option value="bugday">Buğday</option>
        </select>
        <select id="shoesize" required name="field_ayak_no_value" class="chosen-processed">
            <option selected disabled style="display:none;">- Ayak no -</option>
            <option value="35">35</option>
            <option value="36">36</option>
            <option value="37">37</option>
            <option value="38">38</option>
            <option value="39">39</option>
            <option value="40">40</option>
            <option value="41">41</option>
            <option value="42">42</option>
            <option value="43">43</option>
            <option value="44">44</option>
            <option value="45">45</option>
            <option value="46">46</option>
            <option value="47">47</option>
            <option value="48">48</option>
            <option value="49">49</option>
            <option value="50">50</option>
        </select>
        <select id="education" required name="field_egitim_duzeyi_value" class="chosen-processed">
            <option selected disabled style="display:none;">- Eğitim düzeyi -</option>
            <option value="İlkokul">İlkokul</option>
            <option value="Ortaokul">Ortaokul</option>
            <option value="Lise">Lise</option>
            <option value="Önlisans">Önlisans</option>
            <option value="Lisans">Lisans</option>
            <option value="Yüksek_lisans">Yüksek lisans</option>
            <option value="Doktora">Doktora</option>
        </select>
        <textarea id="training" placeholder="Oyunculuk eğitimleri" rows="3" name="field_oyunculuk_egitimleri_value"></textarea>
        <div class="description">Virgül ile ayırabilirsiniz</div>
        <input type="text" id="languages" placeholder="Diller" required name="field_diller_value" />
        <div class="description">Virgül ile ayırabilirsiniz</div>
        <input type="text" id="skills" placeholder="Beceriler" />
        <div class="description">Virgül ile ayırabilirsiniz</div>
        <input type="text" id="personal" placeholder="Kişisel" required name="field_kisisel_value" />
        <div class="description">Oyuncu hakkında biyografi niteliğinde bilgi</div>
        <legend>Yeni bir fotoğraf ekleyin</legend>
        <input type="file" id="images" />
        <input type="button" id="upload" value="Yükle" required/>
        <table id="prods">
            <tr class="prods">
                <td>
                    <input type="text" class="title" name="field_diskografi_value" placeholder="Yapım adı">
                </td>
                <td>
                    <select id="prodtype" name="field_diskografi[und][0][value]">
                        <option selected disabled style="style:none;">- Yapım türü -</option>
                        <option value="dizi">Dizi</option>
                        <option value="film">Film</option>
                        <option value="klip">Klip</option>
                        <option value="reklam">Reklam</option>
                    </select>
                </td>
                <td>
                    <select id="prodyear" name="field_diskografi[und][0][value]">
                        <option selected disabled style="style:none;">- Yapım yılı -</option>
                        <option value="2015">2015</option>
                        <option value="2014">2014</option>
                        <option value="2013">2013</option>
                        <option value="2012">2012</option>
                        <option value="2011">2011</option>
                        <option value="2010">2010</option>
                        <option value="2009">2009</option>
                        <option value="2008">2008</option>
                        <option value="2007">2007</option>
                        <option value="2006">2006</option>
                        <option value="2005">2005</option>
                        <option value="2004">2004</option>
                        <option value="2003">2003</option>
                        <option value="2002">2002</option>
                        <option value="2001">2001</option>
                        <option value="2000">2000</option>
                        <option value="1999">1999</option>
                        <option value="1998">1998</option>
                        <option value="1997">1997</option>
                        <option value="1996">1996</option>
                        <option value="1995">1995</option>
                        <option value="1994">1994</option>
                        <option value="1993">1993</option>
                        <option value="1992">1992</option>
                        <option value="1991">1991</option>
                        <option value="1990">1990</option>
                        <option value="1989">1989</option>
                        <option value="1988">1988</option>
                        <option value="1987">1987</option>
                        <option value="1986">1986</option>
                        <option value="1985">1985</option>
                        <option value="1984">1984</option>
                        <option value="1983">1983</option>
                        <option value="1982">1982</option>
                        <option value="1981">1981</option>
                        <option value="1980">1980</option>
                        <option value="1979">1979</option>
                        <option value="1978">1978</option>
                        <option value="1977">1977</option>
                        <option value="1976">1976</option>
                        <option value="1975">1975</option>
                        <option value="1974">1974</option>
                        <option value="1973">1973</option>
                        <option value="1972">1972</option>
                        <option value="1971">1971</option>
                        <option value="1970">1970</option>
                        <option value="1969">1969</option>
                        <option value="1968">1968</option>
                        <option value="1967">1967</option>
                        <option value="1966">1966</option>
                        <option value="1965">1965</option>
                        <option value="1964">1964</option>
                        <option value="1963">1963</option>
                        <option value="1962">1962</option>
                        <option value="1961">1961</option>
                        <option value="1960">1960</option>
                    </select>
                </td>
            </tr>
        </table>
        <button id="addmoreprods">Başka bir öğe ekle</button>
        <label>Yer Aldığı Yapımlar</label>
        <label for="videos">Videolar</label>
        <table id="videos">
            <tr class="videos">
                <td>
                    <fieldset>
                        <input type="text" class="videolink" placeholder="Video linki (Youtube, Vimeo)" />
                        <input type="text" class="videodesc" placeholder="Açıklama" />
                        <div class="description">Açıklama alanı aynı zamanda başlık olarak kullanılacaktır.</div>
                        <button id="addmorevideos">Başka bir öğe ekle</button>
                    </fieldset>
                </td>
            </tr>
        </table>
        <input type="checkbox" id="privacy" value="0">
        <label for="privacy">Sayın üyemiz, başvuru formunda yer alan bilgiler, üçüncü şahıslar tarafından görüntülenmeyecektir. Lütfen <a href="inst.html" data-transition="pop" id="inst">başvuru talimatını</a> okuyunuz.</label> <a id="apply" data-role="button" class="hidden">Kaydol</a>

    </div>
    <div id="navHolder">
        <div id="homeHolder">
            <img id="homeBtn" src="img/homeBtn.png" />
        </div>
        <div id="loginHolder">
            <p></p>
        </div>
        <div id="notificationHolder">
            <div id="notification"></div>
            <img id="notificationBtn" src="img/notificationBtn.png" />
        </div>
    </div>
</div>
</div>

```

**My Javascript**

```
$(function () {
    $("#profilepicture").on("change", function (e) {
        var ctx = $("#canvas")[0].getContext('2d');
        var img = new Image;
        img.src = URL.createObjectURL(e.target.files[0]);
        img.onload = function () {
            ctx.drawImage(img, 10, 10, 300, 300);
            $("img").attr("src", img.src);
        }
    });
    $("#addmoreprods").on("click", function () {
        var tr = $(".prods").first().clone();
        tr.find('input').val('');
        $("#prods").append(tr);
    });
    $("#addmorevideos").on("click", function () {
        var tr = $(".videos").first().clone();
        tr.find('input').val('');
        $("#videos").append(tr);
    });
    /*$("#tel").mask("999 999-9999");
    $("#tel2").mask("999 999-9999");*/
    $("#privacy").on("change", function () {
        $("#submit").toggleClass("hidden");
    });
    $("a#inst").on('tap', function (event) {
        window.open('inst.html');
        event.stopPropagation();
    });
    $("#apply").on("click", function () {
        $.ajax({
            url: 'http://www.rejicast.com/services/user/token.json',
            type: 'post',
            dataType: 'json',
            success: function (token) {
                $.ajax({
                    url: 'http://www.rejicast.com/services/create.json',
                    type: 'post',
                    beforeSend: function (r) {
                        r.setRequestHeader("X-CSRF-Token", token.token);
                    },
                    data: 'node[type]=oyuncu&node[status]=0&node[title]=' + encodeURIComponent($("#name").val()) + '&node[language]=und&node[field_tc_kimlik_no][und][0][value]=' + encodeURIComponent($("#tckn").val()) + '&node[field_sgk_durumu][und][0][value]=' + encodeURIComponent($("#sgk option:selected").val()) + '&node[field_telefon][und][0][value]=' + encodeURIComponent($("#tel").val()) + '&node[field_telefon_2][und][0][value]=' + encodeURIComponent($("#tel2").val()) + '&node[field_adres][und][0][value]=' + encodeURIComponent($("#address").val()) + '&node[field_yasadigi_sehir][und][0][value]=' + encodeURIComponent($("#city option:selected").val()) + '&node[field_kategorisi][und][0][value]=' + encodeURIComponent($("input[name='kategori']:checked").val()) + '&node[field_dogum_tarihi][und][0][value]=' + encodeURIComponent($("#dob").val()) + '&node[field_boy][und][0][value]=' + encodeURIComponent($("select#height option:checked").val()) + '&node[field_kilo][und][0][value]=' + encodeURIComponent($("select#weight option:checked").val()) + '&node[field_goz_rengi][und][0][value]=' + encodeURIComponent($("select#eyecolour option:checked").val()) + '&node[field_ten_rengi][und][0][value]=' + encodeURIComponent($("select#skincolour option:checked").val()) + '&node[field_ayak_no][und][0][value]=' + encodeURIComponent($("select#shoesize option:checked").val()) + '&node[field_egitim_duzeyi][und][0][value]=' + encodeURIComponent($("select#education option:checked").val()) + '&node[field_oyunculuk_egitimleri][und][0][value]=' + encodeURIComponent($("#training").val()) + '&node[field_diller][und][0][value]=' + encodeURIComponent($("#languages").val()) + '&node[field_beceriler][und][0][value]=' + encodeURIComponent($("#skills").val()) + '&node[field_kisisel][und][0][value]=' + encodeURIComponent($("#personal").val()) + '&node[field_videolar[und][0][video_url]]=' + encodeURIComponent($(".videolink").val()) + '&node[field_videolar][und][0][description]=' + encodeURIComponent($(".videodesc").val()) + '&node[field_okudum_anladim][und][0][value]=' + encodeURIComponent($(".privacy").is(':checked') ? 1 : 0),
                    success: function () {
                        window.location.href = "thanks.html";
                        /*
               $mobile.changePage("thanks.html", "slideup");
               */
                    },
                    error: function (xhr, status, message) {
                        console.log(message);
                        navigator.notification.alert("Kaydınızı oluşturamadık, daha sonra tekrar deneyin.");
                    }
                });
            }
        });
    });
});

```

UPDATE: This answer says I must build my form with Form API. Since I can't use it in my PG app, is that a fact?

UPDATE: One of the errors say "Non-allowed value in *Yaşadığı şehir* field. Based on your comment, please see a screenshot of allowed values of that field. Is that not correct?

# Answer
> 0 votes
List fields can sometimes be a pain. Hopefully one day I'll work out why and update this, but in the meantime try addressing the field like this:

```
node[field_yasadigi_sehir][und][value]

```

---
Tags: javascript
---


# Question
Title: Pathauto unable to bulk update contents alias with AJAX error
In some way I have imported a legacy large database schema to Drupal's database schema. Everything works fine and the imported contents is working fine as nodes.

However, when I try to perform Bulk Update for aliases via `admin/config/search/path/update_bulk`, *using module*, I got the following error message after about 4825 items :

```
An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /drupal/batch?render=overlay&id=1074&op=do StatusText: Service unavailable (with message) ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7844 of /xxxxx/drupal/includes/common.inc).

```

The following is a screen shot:

Clicking on the link titled **Please continue to the error Page** just send me to the bulk Update page with error message:

`An error occurred while processing pathauto_bulk_update_batch_process with arguments : pathauto_bulk_update_batch_process`

I could not able to find more detailed debug info and I don't know what's the matter?

Last version of Pathauto is used.

# Answer
I have just find the cause of the issue. It is just two records of `node` table among about 13K records has no `type` field value.

To solve it, using PHPMyAdmin I have filled them with the machine name of an available content type. in my case it is `archieve`
> 0 votes

---
Tags: 7, path-aliases
---


title: views argument to header

text:
# Question
Title: views argument to header
I have a Search view that uses the Filter: Search terms.

I've tried using `<?php print arg(0); ?>` in the header, but that only returns the view url (search).

How do I get the value of the query key */search?keys=term* to be able to use it as a token in a Global: Text area in the Header?

My header title would be something like : Results for \[search term\]

# Answer
$\_GET\['keys'\] should give you the term value.
> 2 votes

---
Tags: views, search
---


# Question
Title: Why are these filters producing different results?
I'm working on a view, and I'm trying to apply a global filter (based on a field known as `School Year`). I've set up the contextual filter and I've added the block used to set the filter, but after setup, I receive completely different results - they have very few similarities, and the contextual filter narrows the view down to about 20% of the expected results.

On the other hand, when I do a standard Views filter using `School Year` (this time, determined locally), it gives all the expected results.

Basically, my confusion stems from this: if I'm trying to use the same data, stored either globally in a block or locally in a standard filter, why does that give me different results? How can I fix that? What might I be missing?

**EDIT:** Despite my answer below this seems to only be working on one of my views - but even though I replicated the steps on another view, it provides the same unexpected behavior, so it only applies to half the views I need it to work on.

# Answer
I actually figured it out - as it turned out, I missed a small but important detail. The original (local) filter included a relationship to a content type within the view, which was providing the correct results. When I went back to edit it, I'd noticed that when I created the contextual filter, I hadn't provided the relationship to the filter. Upon adding the relationship, everything worked out the way I'd intended - getting all the expected results. I still don't know why I was getting that unexpected behavior, though.
> -1 votes

---
Tags: views
---


# Question
Title: How do you update a data blob column by searching and replacing a string using drush?
How would one do the following in drush? I want to change some data in one of the users table for one of my users. The thing I want to change is in the data blob column with all the punctuation's and what not. I can copy the data blob out, edit, it and then paste it back in, but was wondering how can this be done via drush with a search and replace?

# Answer
> 1 votes
You can use the following MySQL statement in the drush SQL console:

```
drush sqlq "update users set data = replace(data, 'string_here', replacement_string') where uid = 1"

```

---
Tags: drush, database
---


# Question
Title: How to add a send email action link in views using the same VBO send email action
Views Bulk Operations (VBO) has a send email action that sends you to an email form. How can I add a views field to a list of users that creates a link to the same action form that VBO uses to send email, but for just that user row and then pre-populate the recipient field? I believe VBO uses the system\_send\_email\_action\_form.

# Answer
In order to do this with VBO you'll need modify the `system_send_email_action_form` form (to default its recipient) and add some custom JS (to create click events that automatically submit the VBO form).

An easier alternative here is to use the Views Send module which does nearly the same thing with a slight UI difference; there's a **Send Email** button at the bottom of the view as opposed to a send email link for each row.
> 0 votes

---
Tags: emails, views
---


title: Chosen module not working in drupal 7

text:
# Question
Title: Chosen module not working in drupal 7
i used to Chosen 7.x-2.x-dev module and then installed. In config/user-interface/chosen is the default. But it is not working. Can anyone tell me why and how to handle not.

# Answer
> 2 votes
I am using Chosen 7.x-2.0-beta4. In **Home » Administration » Configuration » User interface » Chosen** add your selct fields id in **Apply Chosen to the following elements** fields as **select#your-field-id**.

Another method is select **Apply** option in your **Select fields edit form**

Hope this will help you.

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


# Question
Title: How do I make node_gallery image thumbnails retain original proportions?
When I upload an image to a Drupal 7 node\_gallery gallery, a thumbnail is automatically generated. This is good.

However, the thumbnail is also *cropped* to a square size. This is bad. (But note that the full-sized image is not cropped.)

I want **the thumbnail to retain the original image proportions** (often 2:3 or 3:4), the same as the full-sized image (just smaller), rather than being cropped to a 1:1 format.

How can I do that? Google was distinctly unhelpful in this case, showing me results only for old versions of Drupal, and even then those solutions were mostly for other problems.

# Answer
> 2 votes
Never used this module, but try checking `/admin/config/media/image-styles` perhaps the module has an image style. If so, all you have to do is edit it and change it to your liking.

**Side Note:** You can also get there by clicking configuration, then under media click on Image Styles.

As you wrote in a comment:

> Editing the node\_gallery\_thumbnail style to replace the "Scale and crop" effect with a "Scale" with the same numbers for width and height did the trick.

---
Tags: 7, media
---


# Question
Title: Set default image when file not found (404)
I have many images but when one of them is missing it displays an empty `<img>`. Is there a method or hook that can be used to display a default image instead this empty `<img>` tag?

# Answer
Install and configure ImageCache Defaults module.

> ImageCache Defaults detects file paths in broken images (404 errors) generated by ImageCache (D6) and Image (D7). ImageCache Defaults can either remove images with broken paths from your markup completely or replace them with a configurable default image.
> 2 votes

# Answer
How are you building your list of images? If possible, you could add this to your img tags:

```
<img src="non-existent.jpg" onerror="this.src = 'show-this-instead.png'">

```
> 1 votes

---
Tags: entities, media
---


# Question
Title: Go to previous page (not after form submit)
I have a function that is called by hook-menu item an is accesible from different subpages of the site. This function does not return any html, it just do some database inserts and should redirect user back where he came from.

Well, it could be easily done by adding url args as a parameters to this function and then use drupal\_goto() with those arguments. But I'm wondering if there is any drupal function for this. I was trying `drupal_goto(drupal_get_destination());` but it does nothing.

# Answer
> 2 votes
Create your link this way:

```
$link = l('Link title', 'your/menu/path', array('query' => drupal_get_destination));

```

This will add the `destination` argument to the link URL.

Then, at the end of your page callback, simply call:

```
drupal_goto();

```

---
Tags: redirection, routes
---


# Question
Title: How to serve 404s for non existent views paths with facets
Is it possible have non-existent views paths 404, but to allow facets and parameter searches?

Most of the answers to this question for base views, are either for Drupal 6, or use Mikeytown's excellent Views404 module.

However this isn't an option if you're using faceted search. Using Views404 will return 404s for all of your faceted pages.

Is there a general way to catch when views isn't hitting a facet or an allowed parameter?

# Answer
> 1 votes
The solution here was to alter the Views404 module.

The module works by running a single `hook_views_pre_view`. This function runs a series of tests and if none of them pass returns a 404.

I added in an extra set of tests which would pass on my facets and so avoid the 404.

This problem doesn't exist with all facets. The problem comes because I'm using Facet API Pretty Paths. It turns:

```
https://mysite/view?f[0]=host_entity_node%253Afacet_label%3Afacet_value

```

Into:

```
https://mysite/view/facet_label/facet_value

```

And while views404 will allow para-metered search, it won't allow folders unless they pass one of the tests.

I altered my facet pretty paths in the UI, so one of the labels was country and all the rest began with 'filter':

e.g.

* Country Facet: `Pretty path alias = country`
* Every other facet: `Pretty path alias = filter_x`

I then added the following code to views 404

```
$args_passed = 0;
foreach($args as $arg) {
  if($arg == 'country') {
    $args_passed++;
  } elseif(is_int(strpos($arg, 'filter'))) {
    $args_passed++;
  }
}

if($args_passed == (count($args)-1)/2) {
  return;
}

```

Facets always come in pairs, so it goes through every arg and looks for either country or filter. If if finds half of the url arguments are facet\_labels then that's a pretty strong indicator this is a genuine path and shouldn't throw a 404.

---
Tags: 7, views, search
---


# Question
Title: Is it normal that Organic Groups group creator is not automatically "Administrator member"?
I am getting my head around OG and its permissions. I have a user (not super-user uid=1) who can create OGs. Rather to my surprise, when I look at the OG members, the user who created the OG is there as a member but has not been given the "Administrator Member" role. Yet he seems to have full management rights on the Group rather like a local super-user. Does this mean that he should create an "Administrator" separately?

# Answer
I should have seen this myself. In fact the answer is in the slightly obscure "OG Settings" (Config \> Organic Groups \> OG Settings).

In this there is an option called "Group Manager default roles" which is applied to every OG content type. This allows you to "Select the role(s) a group manager will be granted upon creating a new group"

Problem sorted!
> 0 votes

---
Tags: organic-groups
---


title: saving any view clears all cache

text:
# Question
Title: saving any view clears all cache
I am working in drupal 6. I know that saving any node clears cache but is the same with views? I am experiencing this issue. I would like to know how to prevent it. Thank you.

# Answer
If we inspect views\_ui\_edit\_view\_form() we can see the following `#submit` handler being assigned:

```
  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#validate' => array('views_ui_edit_view_form_validate'),
    '#submit' => array('views_ui_edit_view_form_submit'),
  );

```

Drilling further down into views\_ui\_edit\_view\_form\_submit() it becomes clear which caches are affected by saving a view:

```
  // Make sure menu items get rebuilt as neces
  menu_rebuild();

  // Clear the views cache.
  cache_clear_all('*', 'cache_views');

  // Clear the page cache.
  cache_clear_all();

  // Remove this view from cache so we can edit it properly.
  views_object_cache_clear('view', $form_state['view']->name);

```

In summary, these are the caches that get cleared when a view gets saved:

* menu
* views
* block
* page

In addition, the menu rebuild triggers the following hooks:

* hook\_menu()
* hook\_menu\_alter()
> 2 votes

---
Tags: views, 6, caching
---