# Question
Title: How to display custom field using Views module at front end
I have created custom content type having below fields

```
Title, Description, Small Image, Large Image and Category

```

I am using **Views** module to display that content (only small image) in **Grid** format with 4 columns. Issue is that i don't find any option (Settings of my view) to display only custom field at front end. The only thing i can see is title is being displayed in grid format.

Does that mean **Views** module does not show custom fields created for a custom type content at front end?

****SOLVED****

Never mind guys. I got solution. Once you go to your view (created using views module) edit page then at the bottom of the page there is a section called Content having options to add custom fields in view.

# Answer
> 1 votes
Views has the option of adding a custom field.
You need to search for global custom text field in the views
You can add a **global custom text field** as custom text field and alter the value using `hook_views_pre_render(&$view)`

```
function YOUR_THEME_views_pre_render(&$view) {

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

```

Click on the add as shown in the Image

Then search for Global custom text field as shown in the Image

You will see global custom text field which is custom text for views and you can alter it using above code or u can alter by entering html text into configure option for the field as shown in the image below :

# Answer
> 1 votes
Not recommended but still as an option, you can use views\_php module it allows to add custom php fields in views, and if you just need custom text as custom field then @user13198 has already described it well enough.

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


title: What is boost used for?

text:
# Question
Title: What is boost used for?
When using Search API, editing an index and changing fields that get indexed, you can set the boost for some of the fields. What is this used for?

# Answer
Boost column allows you to "boost" search results based on certain criteria. You can boost an entity which will make it have higher relevance. The way results are displayed will be by ranking and setting Boost value will add additional ranking to the field.

Currently you can only Boost Full Text fields.
> 1 votes

---
Tags: search
---


# Question
Title: Is it safe to call field_view_field() for a field that isn't attached to the given node?
My page.tpl.php includes:

```
if ($node) {
    // field_suburb is a "text" field that doesn't exist on this node type
    $f = field_view_field('node', $node, 'field_suburb');
    print render($f);
}

```

This triggers:

> PHP Fatal error: Cannot access empty property in field/field.attach.inc

I added the following debug code in field.attach.inc ("if field name is null" block):

```
foreach ($languages as $langcode) {
    if ($field_name === null) {
        print $field_name === null ? "FIELD NAME IS NULL\n" : '';
        print $instance == null ? "INSTANCE IS NULL\n" : '';
        print "$entity_type $bundle\n";
        print_r($instances);
        print_r($options);
    }
    $grouped_items[$field_id][$langcode][$id] = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();
    // Group the instances and entities corresponding to the current field
    $grouped_instances[$field_id][$langcode][$id] = $instance;
    $grouped_entities[$field_id][$langcode][$id] = $entities[$id];
}

```

That code prints:

```
FIELD NAME IS NULL
INSTANCE IS NULL
ENTITY TYPE: node BUNDLE: news
Array
(
    [0] =>
)
Array
(
    [field_name] => field_suburb
    [language] =>
    [default] => 1
    [deleted] =>
)

```

This is easy enough to protect against - I can just check my node type before accessing the field - but surely field\_view\_field should just return null for a field that doesn't exist instead of having the entire site die?!?

Should it be safe to call field\_view\_field() - i.e. is this a bug? If it's not a bug, then what's the easiest way to check to see if my given node content type actually has the field I'm rendering? Checking the type against a list of known safe types isn't very flexible, and calling field\_get\_items() followed by field\_view\_value() seems redundant when field\_view\_field() is available.

Drupal version is 7.22.

# Answer
> 1 votes
Source code of this function looks as follows:

```
function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) {
  $output = array();

  if ($field = field_info_field($field_name)) {
  // Actual work on field, not needed here in this answer
  }

  return $output;
}

```

It means that if there is no field, empty array will be returned. That's all. Is it safe? Depends what are you doing with that array down the road. For example you cannot render empty arrays with `render()`, as it accepts only arrays representing Drupal's renderable elements.

Note that this is from the current, 7.23 version of Drupal.

---
Tags: entities
---


# Question
Title: Passing custom fields as parameters in a REST query
I am creating a REST Get request using Services 3.3 module on Drupal 7.15 which should get all the nodes filtered by a custom field field\_asset\_type

http://sharedrive/?q=rest/node&parameters\[field\_asset\_type\]=13

It returns following error Invalid query provided, double check that the fields and parameters you defined are correct and exist. SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'field\_asset\_type' in 'where clause'

Kindly tell me how to resolve this problem. The articles on the internet explains how to pass built-in fields which is working but I also need to pass custom fields.

Please help

# Answer
> 3 votes
The default functionality only works with node *properties*, not *fields*. Fortunately you can use the Services Entity API module to get what you need:

> Integration of Services and Entity API.
>
> You can define an endpoint via Services and publish any entity data relying in Entity API.
>
> This module allows to get entities by properties or fields and also paging and related entities that are defined properly.

---
Tags: services, 8
---


title: Drupal.t() and language code

text:
# Question
Title: Drupal.t() and language code
I want to write some JavaScript code for my project. I need to use `Drupal.t()`, but it seems that `Drupal.t()` only accepts English, and I don't want to write my JavaScript in English.

Is there any way to inform `Drupal.t()` that my string is not in English, just like `t()` that let you specify the language code.

# Answer
The string that you pass as first argument to `Drupal.t()` (as it happens with t()) needs to be in English, since the function translates a string from English to another language.

Differently from `t()`, which allows you to pass the language code for the language you want to translate the string, `Drupal.t()` doesn't have that possibility. Its arguments are the following:

* str
A string containing the English string to translate.
* args
An object of replacements pairs to make after translation. Incidence of any key in this array are replaced with the corresponding value. See Drupal.formatString().
* options
+ 'context' (defaults to the empty context): The context the source string belongs to.

### Reference
> 0 votes

# Answer
Nope, not really. Drupal is built from ground up in English and that's the way you need to build your modules too. Some parts of the code tries to enable you provide default texts in another languages, but it's a disaster if you decide to change default language later.

It is possible to built functionality like you need in a custom module, it is even possible someone did, but I don't know of any reliable solution.
> 0 votes

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


# Question
Title: How do I add a variable to $node from a module?
I would like to perform a lookup on $node-\>uid from a module, fetch a field from the user profile and then attach that field to $node for use in template files.

I can do this within a theme preprocess method, but my understanding is that adding data (and performing queries) the "Drupal Way" means doing it in a module.

I guess I'm asking what hook I want to target. (Please note that this module did not implement the content type I want to alter.)

# Answer
Try hook\_node\_load(). With this hook you can add info to a node.
> 0 votes

# Answer
> A possible solution can be
>
> * add a hidden field to your content type
> * use hook\_node\_presave to do your changes before node save process,get the node author uid, then get your field from that user profile.
> * Attach the field value to your node field
> * That'all
>
> Note : do not do node\_save() inside hook\_node\_presave(), it will make it not breaking recursion call.

keeping field value as hidden will not show the field on node but this will be available in views etc. so it will easier to extend further.
> 0 votes

# Answer
> Even the field is subjected to change you can use one more hook, something like below
>
> * After a user is updated , catch the update action using hook\_user\_update($edit,$account, $category) you will get the updated fields on user entity in the $edit array and an easy check can be made to see if twitter handle is updated or not, if updated get all nodes the edited user is author of with your content type check then udpate the node fields as well
>     + To udpate node fields preferably use, field\_attach\_presave() and field\_attach\_update(), something like below

```
// snippet as example.
      $node = node_load($node_id);
      $node->your_field_name[LANGUAGE][0]['value'] = UPDATED_VALUE;
      field_attach_presave('node', $node);
      field_attach_update('node', $node);

```
> 0 votes

---
Tags: 7, nodes, hooks
---


title: pass dynamic string

text:
# Question
Title: pass dynamic string
i create a function which save data to db . here is my code

```
function create_db_entry($table_name, $fields) {
  $str='';
  foreach($fields as $key=>$value) {

    $str.="'".$key."'=>"."'".$value."',";

  }

 if(db_insert($table_name)->fields(array($str))->execute()) {

  }else {
    drupal_json_output("there is some problem, please try again"); exit;

  }

}

```

and here is my

```
$str='token_id'=>'f3c7b8b04a283e16645f3e885cd73ebf','uid'=>'1',

```

Now if i use this

```
db_insert($table_name)->fields(array('token_id'=>'f3c7b8b04a283e16645f3e885cd73ebf','uid'=>'1',))->execute();

```

it works fine. i want to use $str.

Can anybvody tell me how to do this

Thanks

# Answer
> 3 votes
```
$str='token_id'=>'f3c7b8b04a283e16645f3e885cd73ebf','uid'=>'1',

```

Is not valid PHP. The `fields()` method takes an associative array, so that's what you need to pass to it:

```
$arr = array(
  'token_id'=>'f3c7b8b04a283e16645f3e885cd73ebf',
  'uid'=>'1'
);
...
db_insert($table_name)->fields($arr)->execute()

```

To build that dynamically:

```
$arr = array();
foreach($fields as $key => $value) {
  $arr[$key] = $value;
}

```

Although at that point you're just duplicating `$fields`, so you might as well pass that directly to the db query.

With the best will in the world, I question the point of even having that function as it doesn't really add anything. If you're looking for a wrapper function Drupal already has `drupal_write_record()`.

---
Tags: 7
---


# Question
Title: Simple jquery instructions attached on form is not executeing
I have a very simple js attached to a form, and I cannot see why it is not executing.

```
(function ($) {
    alert("test");
    $('#field-ai-event-date-unique-add-more-wrapper').hide();
    $('#field-ai-event-date-range-add-more-wrapper').hide();
})(jQuery);

```

The alert is popping up as expected, the jQuery instructions are not executed. They work fine in the console and hide the form elements as expected.

What is the problem here?

# Answer
> 2 votes
**jQuery 101**: If you want to manipulate an element in the DOM, the DOM needs to be ready first.

```
(function ($) {
  $(function() {
    $('#field-ai-event-date-unique-add-more-wrapper').hide();
    $('#field-ai-event-date-range-add-more-wrapper').hide();
  });
})(jQuery);

```

See jQuery.ready().

If you can convince yourself never to forget this small fact, life will be a lot easier :)

---
Tags: javascript
---


# Question
Title: D6/views - Multiple nodes in one slide grouped by taxonomy
I have the following taxonomy:

* food
    + **fruits**
        - *apples*
        - *pears*
        - *bananas*
    + **vegtables**
        - *tomatoes*
        - *carrot*
        - *cucumber*
    + **meat**
        - *chicken*
        - *beef*
        - *duck*

...and a view that brings all those items, currently as an html list grouped by taxonomy term. I use fields for each item.

I need to change my view in order to split them in slides (or pages with prev/next) so that each slide/page will hold **all** the items of a food subcategory (the whole group). Ideally with a slider but pagination will also suffice.

To be precise I'd like a similar result as in this question. But in my case I have the above taxonomy tree to help distinct nodes I need in each slide

Thanks in advance!

# Answer
> 0 votes
You might add an argument to your view.

The url of your view should looks like: "my\_site/my\_views\_url/11" (#11 is the tid of "fruits")

This url will list all terms depth to "fruits" (so apples, pears, bananas)

To add a depth in your argument term in the view follow the views UI :

# Answer
> 0 votes
I think you are looking for Taxonomy VTN module , but it subgroup with alphabets

> Taxonomy VTN module provides an index for vocabularies, terms and nodes just like those you find at the end of reference or technical books. It supports synonyms, terms, related terms, and parent/child relations.

or may be this module you are looking for, it have the alphabetical sort order for the vocabulary.

---
Tags: paging, views, javascript
---


title: Magento + Drupal SSO (Single Sign On)

text:
# Question
Title: Magento + Drupal SSO (Single Sign On)
We are looking to build a **new website** which would make use of 2 web applications: **Drupal and Magento**. **Drupal** will be used for **corporate website** while **Magento** will serve as a **web shop**. One of the **challenges** that I'm facing is the **single-sign-on (SSO)** part. I have done quite a lot of reading about this subject and haven't come across the "best way" to do this.

Do we keep a separate user database on both Magento and Drupal? (Taking into consideration that not every Drupal user will have access to the web shop.)

Should we use a central authentication server (CAS) instead?

**Currently I'm testing the following method:**

1. Installed the Drupal rules module
2. Configured that the user is redirected to a file sso.php after he/she logs in on Drupal
3. The sso.php file reads the information of the currently logged in user and optionally creates the Magento session for this user (if an account with a matching username/e-mail) exists

Does anyone have any previous experience in getting the SSO feature between Magento-Drupal? Any input would be appreciated!

Some more info:

* The website and web shop will run on the same domain. The web shop is located in a subfolder
* Preferably the SSO has to be done programatically without using the slow Magento API

# Answer
> 1 votes
Check out phpSimpleSAML. There's also a similar post here: https://stackoverflow.com/questions/7763999/magento-and-moodle-integration

Drupal can also support LDAP based logins but your sessions between both apps won't carry over so you will need a single sign on solution as mentioned above.

---
Tags: authentication-authorization
---


# Question
Title: How to make drush un-install modules without confirmation
I want to create a drush command that reinstall some modules. I've done something like this:

```
  $modules_to_uninstall = array("my_module1", "my_module2", "my_module3", "my_module4", "my_module5");
  foreach($modules_to_uninstall as $name){
    $args = array_merge(array('pm-uninstall') ,array($name));
    call_user_func_array('drush_invoke', $args);
  }

```

but, when I run the command in drush, it always asks me if I want to uninstall that module.

```
The following modules will be uninstalled: my_module1
Do you really want to continue? (y/n): y
my_module1 was successfully uninstalled.                                                                                [ok]
The following modules will be uninstalled: my_module2
Do you really want to continue? (y/n): y
my_module2 was successfully uninstalled.

```

\[ok\] The following modules will be uninstalled: my\_module2 Do you really want to continue? (y/n): y my\_module3 was successfully uninstalled. ....

```
$modules_to_uninstall = array("-y my_module1", "my_module2", "my_module3", "my_module4", "my_module5");
  foreach($modules_to_uninstall as $name){
    $args = array_merge(array('pm-uninstall') ,array($name));
    call_user_func_array('drush_invoke', $args);
  }

```

I've try those but it's useless.

Some suggestion?

# Answer
> 7 votes
Drush has a -y option, that accepts all questions with a yes. Use that.

# Answer
> 3 votes
For simple operations such as this, calling the drush script with the -y option, as suggested in the other answer, is the best option. If you have need to invoke Drush from php, the best API to use is `drush_invoke_process`.

```
$site = array('root' => '/path/to/drupal/root', 'uri' => 'mysite.com');
$modules_to_uninstall = array("my_module1", "my_module2", "my_module3", "my_module4", "my_module5");
$result = drush_invoke_process($site, 'pm-uninstall', $modules_to_uninstall, array('yes' => TRUE));

```

If you are already running the above code from within a bootstrapped site's environment (called via `drush @site php-eval ...` or `drush @site php-script ...`), then you may use '@self' for $site. Note that the --yes option is shown for illustrative purposes (how to pass options); --yes is the default mode for drush\_invoke\_process.

Using drush\_invoke\_process will allow you to run subcommands that do not prompt without auto-answering all questions in your script. By default, the code you call runs in 'integrate' mode, which means that the user will see all of the log messages, and error statuses from the subprocess will also be set in the calling process. To allow your script to handle errors itself, and make the subprocess run quietly, then disable integrate mode:

```
$result = drush_invoke_process($site, 'pm-uninstall', $modules_to_uninstall, array('yes' => TRUE), array('integrate' => FALSE));

```

Finally, if you *do* want your subprocess to prompt, you can either call drush\_invoke, as you show in your question (runs with all of the options and environment of the calling script), or use drush\_invoke\_process in 'interactive' mode to isolate the environment (pass in new options) of the subprocess.

```
$result = drush_invoke_process($site, 'pm-uninstall', $modules_to_uninstall, array(), array('interactive' => TRUE));

```

# Answer
> 0 votes
For script purposes, you can set the context in your script to answer yes.

```
drush_set_context('DRUSH_AFFIRMATIVE', TRUE);

```

This would be like running your script with the -y option.

---
Tags: drush
---


title: Views Relationship with profiles

text:
# Question
Title: Views Relationship with profiles
I am trying to create a view where I have the same taxonomy term for a node and profile to link the two together. Here is what I did:

I created a profile with a taxonomy(Current Company) with a value of: **company1**

I create a node with a taxonomy(Current Company) with a value of: **company1**

I created a user view and created a relationship to see all content. This works but I tried to create a filter where the **logged in user** profile (company1) = the value of the node taxonomy (company1).

So basically since the logged in user belongs to company1 he only see content related to company1.

I have been trying different combinations and cannot get this to work, I know it has to be possible.

Thanks

# Answer
I solved this problem by adding a **Contextual Filters** \> select **Current Company** \> select **Provide default value** \> then selected **Type - PHP Code** and added this:

```
global $user;
$user_fields = user_load($user->uid);
$profile = profile2_load_by_user($user_fields, 'main');

return $profile->field_my_company['und'][0]['tid'];

```
> 0 votes

# Answer
You can use relationship settings to add in the taxonomy, and then add a contextual filter on "user:uid" with taxonomy value fetched from currently looked-in user.

Have a look at this refrence: https://drupal.org/node/1111722#comment-4315620

Copied here in case that node goes away:

* Create a user view.

Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will give you exactly one user object in your view -- the logged in user.)

Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the "interest" term for the logged in user.

Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes marked with the interest term for the logged in user.

Either set the view to display node teasers, or select a number of fields to display.

Add a display as usual. Done!
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to add default text that clears on focus to a form in Drupal?
I would like to display a default text in a field of a views filter form. That default text would then be hidden "on focus", and would re-appear "on blur". So far I have tried to follow the instructions given here: How to add default text that clears on focus with jQuery to a search form text field in Drupal but with no success.

What I did:

**1.** Downloaded the Jquery files (https://github.com/mudge/jquery\_example/downloads), and copied them in my /sites/all/libraries/mudge-jquery directory

**2.** Added a helper.js file into that directory with that code

```
(function ($) {
  Drupal.behaviors.helper =  {
    attach: function(context, settings) {
      $('input#edit-title.form-text.beautytips-module-processed.bt-active').example('TEXT TO HELP');
    }
  };
})(jQuery);

```

**3.** Created a simple module with that code:

```
function helper_preprocess_page (&$vars) {
  // Let's add some js to page for the search box.
  $path = drupal_get_path('module', 'helper');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/jquery.example.min.js');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/helper.js');
}

```

Still nothing is displayed in my "input#edit-title.form-text.beautytips-module-processed.bt-active" field. What am I doing wrong here?

# Answer
What you want here is:-

a) hook\_form\_alter to change the form

b) #attached to add JS to the form

c) add clear-text to `['#attributes']['classes']` where necessary.

Then you can use this little JS.

```
 Drupal.behaviors.clearText = function(context) {
    var inputs = $('input.clear-text:not(.processed)');

    // Store the original values
    inputs.each(function() {
      $this = $(this);
      $this.data('default', $this.val());
    }).addClass('processed');

    // Set up inputs to clear on focus & reload default (if blank) on blur
    inputs
      .focus(function() {
        $this = $(this);
        if ( $this.val() == $this.data('default') ) {
          $this.val('');
        }
      })
      .blur(function() {
        $this = $(this);
        if ( $this.val() == '' ) {
          $this.val( $this.data('default') );
        }
      });
  }

```
> 2 votes

# Answer
i have used a little javascript to display default text which gets removed on focus. However in validation i have to check for null if the field is blank and as well as the default text.

```
 $form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => t('Be sure of your first name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
    'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}"
      , ),
       );

```
> 1 votes

# Answer
I think Compact Forms module will help you. Even if you won't use it as is - you can take js code from that module that will solve your issue.
> 0 votes

# Answer
I use the follow simple straight-forward code for my search fields and add it in my theme:

```
(function ($) {
  Drupal.behaviors.mysiteSearch = {
    attach: function() {
      // Apply the default text to the search block's text field.
      $('#block-search-form .form-text')
      // Add default text options on blur.
      .blur(function () {
        $(this).addClass('gray');
        $(this).attr('value', Drupal.t ('Search...'))
        // keep what's typed
        .keypress(function(){
          $(this).unbind('blur');
        })
        // clear on focus
        .focusin(function () {
          $(this).attr('value', '');
          $(this).removeClass('gray');
          $(this).unbind('focusin');
        });
      })
      // Trigger the blur event to set things up.
      .blur();
    }
  };
}(jQuery));

```

Just be sure to set a .gray css style.
> 0 votes

---
Tags: forms
---


title: Add focus to user login

text:
# Question
Title: Add focus to user login
I'm trying to add:

```
drupal_add_js('jQuery(document).ready(function () { jQuery("input#edit-name").focus(); });', 'inline');

```

to the user login page when the user is not logged in. This lack of login form focus is one of my worst web annoyances.

What would be the most efficient way to do this?

I can add the code to every page by adding it to my theme's js, but this is inefficient.

In the theme's template.php I can use `theme_preprocess_page()` and check for `$variables['logged_in']` but how do I test for only the /user page?

# Answer
> 1 votes
You can use the drupal\_match\_path() function:

```
$path = drupal_get_path_alias();
$pattern = 'user';

    if (drupal_match_path($path, $pattern)) {
      drupal_add_js('jQuery(document).ready(function () { jQuery("input#edit-name").focus(); });', 'inline');
    }

```

---
Tags: javascript, users
---


title: Boost don't generate CSS

text:
# Question
Title: Boost don't generate CSS
I have a major problem: the boost module is great but SOMETIMES i find some pagers without any CSS or JS like the image below:

# Answer
> 1 votes
https://drupal.org/project/advagg/ should solve this issue. Odds are the cached page is older than 30 days (limit of CSS/JS aggregates in D7 Core).

---
Tags: theming, caching
---


# Question
Title: OK to have multiple media queries for each content type's CSS?
Im making a responsive site and im using SASS. Im using the zen theme but any theme that outputted a body class based on the content type (of the page you are on) would be in the same situation.

I started creating media queries and trying to put my css code for all the different content type pages within each one. For this demo code there are 2 content types, but in reality sites are more complicated.

As a result my code soon become difficult to read and I lost the ability to put a break point exactly where I wanted it, eg content-type-A might need one a 700px, but content-type-B might need one at 750px.

```
@media all and (min-width: 960px) {
    body.content-type-a {
     // styles here
    }
    body.content-type-b {
        // Styles here
    }
}
@media all and (min-width: 500px) and (max-width: 959px) {
    body.content-type-a {
        // styles here
    }
    body.content-type-b {
        // Styles here
    }
}
@media all and (max-width: 499px) {
    body.content-type-a {
         // styles here
    }
    body.content-type-b {
        // Styles here
    }
}

```

So im thinking that this is a better way to organise media queries. Ive organised the css file by content type, and then put the media queries for that content type's page only. This means that for each page I know where to look for the code being used. It also makes it easy for me put breakpoints exactly where I want them.

```
// Content type A
@media all and (min-width: 960px) {
    body.content-type-a {
        // styles here
        }
}
@media all and (min-width: 500px) and (max-width: 959px) {
   body.content-type-a {
        // styles here
    }
}
@media all and (max-width: 499px) {
        body.content-type-a {
        // styles here
        }
}

// Content type B
@media all and (min-width: 960px) {
        body.content-type-b {
        // styles here
        }
}
@media all and (min-width: 650px) and (max-width: 959px) {
    body.content-type-b {
             // styles here
        }
}
@media all and (max-width: 649px) {
    body.content-type-b {
             // styles here
        }
}

```

This does mean that I will probably have multiple but separate media queries with the same breakpoint, is there any issue in this? This seems to me like a really logical way to work but no tutorial or screencast ive seen does things in this way. Are there issues I havnt considered? Does anyone work in this way?

# Answer
> 0 votes
First, I'll say that I'm not sure if I should even be answering this question. I don't think this is a Drupal specific question. You may get more/better answers from a forum dedicated to CSS.

Having said that:

There's no reason this shouldn't work. The CSS is valid, and if it helps you stay organized, I say go ahead.

I guess there could technically be concerns regarding the performance, but I highly doubt you'd ever be able to see/feel a difference.

---
Tags: theming
---


# Question
Title: Adding group manager email to "membership pending" text
When a user tries to join a private group in Drupal Commons she will see the following text:

> Your membership request is pending review by a group organizer.

We'd like to give the user the ability to email (or otherwise contact via form) the group manager. Is it possible to update this text to add an email (to authenticated users only of course)?

**Update:** It appears I may be able to accomplish this by hook\_preprocess\_field

```
function hook_preprocess_field(&$variables) {

  if ($variables['element']['#field_name'] == 'group_group') {
        $variables['element'][0]['#markup'] .= "Group Mgr Email Placeholder";
  }
}

```

Though after a drush cc all && drush cron, the page content remains the same. Am I using the wrong function?

**Update 2:** Well I now have a placeholder for email by using item instead of element. Next I'll move onto extracting the group managers and their emails to show to pending users.

```
$variables['items'][0]['#markup'] .= " [[ place holder for emails]]";

```

# Answer
Well it appears I can get all of the users in the group via the following:

```
mysql> select * from og_membership where gid=10 and entity_type = 'user';
+-----+----------------------------+------+-------------+-----+------------+-------+------------+--------------+----------+
| id  | type                       | etid | entity_type | gid | group_type | state | created    | field_name   | language |
+-----+----------------------------+------+-------------+-----+------------+-------+------------+--------------+----------+
|  14 | og_membership_type_default |    1 | user        |  10 | node       | 1     | 1376756212 | og_user_node | en       |
| 146 | og_membership_type_default |   41 | user        |  10 | node       | 2     | 1378317628 | og_user_node | en       |
+-----+----------------------------+------+-------------+-----+------------+-------+------------+--------------+----------+
2 rows in set (0.00 sec)

```

But if I start with the group role I'm interested in (administrator member)

```
mysql> select * from og_role where gid=10;
+-----+-----+------------+--------------+----------------------+
| rid | gid | group_type | group_bundle | name                 |
+-----+-----+------------+--------------+----------------------+
|  25 |  10 | node       | group        | non-member           |
|  26 |  10 | node       | group        | member               |
|  27 |  10 | node       | group        | administrator member |
+-----+-----+------------+--------------+----------------------+
3 rows in set (0.00 sec)

```

I can use it to find which users have that role:

```
mysql> select * from og_users_roles where gid=10 and rid=27;
+-----+-----+-----+------------+
| uid | rid | gid | group_type |
+-----+-----+-----+------------+
|   1 |  27 |  10 | node       |
+-----+-----+-----+------------+
1 row in set (0.00 sec)

```

Which gives me the chance to grab the email address of those users:

```
mysql> select mail from users where uid =1\G

```

Or to put it more closely together:

```
mysql> select mail from users where uid IN
(
  select uid
  from og_users_roles
  where gid=10 and rid=27
);
+----------------------+
| mail                 |
+----------------------+
| webmaster@mysite.edu |
+----------------------+

```

1 row in set (0.00 sec)

Putting it all together, I ended up with this

```
hook_preprocess_field(&$variables)
{

    if ($variables['element']['#field_name'] == 'group_group')
    {

      if (isset($variables['items'][0]['#markup']) && stristr($variables['items'][0]['#markup'], 'pending' )) {

        // prepare query lookup up email addresses of users with 'administer member' group roles
        $query = trim('
         select mail from users where uid IN (
            select uid from og_users_roles where gid=:gid and rid IN (
              select rid from og_role where gid=:gid and name=:adminrole
            )
          );
        ');
        $args = array(
          ':gid'=> $variables['element']['#object']->nid,
          ':adminrole'=>'administrator member'
        );

        // execute query. Assemble a list of clickable email addresses. Strip the
        // end comma.
        $result= db_query($query, $args)->fetchAll();
        foreach ($result as $record) {
          $grp_mgr_email = l($record->mail, 'mailto:'.$record->mail) . ', ';
        }
        $grp_mgr_email = preg_replace('/,$/', '.', $grp_mgr_email);

       // clear out the standard field and move to more noticable message
       drupal_set_message(t( strip_tags($variables['items'][0]['#markup']) . " Contact the group organizer(s): $grp_mgr_email"), 'status', FALSE);
       $variables['items'][0]['#markup'] = "";
      }
    }

}

```
> 0 votes

---
Tags: organic-groups, database, theming, 7
---


title: Theming a content type

text:
# Question
Title: Theming a content type
What's the best way to theme a content type? Is there an effective way? Can I just use my page template, resave it with a different name and do it that way?

# Answer
It depends on what you want/need. Not only for content types, for theming generally; my suggestions:

1. For little/cosmetic changes(font, color etc.) and basic layout settings you can use node-type-yourcontenttypename class and style with CSS.
2. For moderate+ structural and visual needs you can use Views, Context, Panels etc. alone or combined(and CSS of course).
3. For the things you can't achieve without dirtying your hands; you can create special template files for pages, nodes, block, views etc.
4. For the things you can't achieve with above ways; you can hack core, module, theme files. But this would be last and worst way to go.

You can do lot of things with 1, most of things with 1+2 and almost everything with 1+2+3.
> 1 votes

# Answer
The best way is to create a different template for each content type. For example, you would make a node--product.tpl.php template in your theme's template folder to theme all content with the "Product" content type. Once you flush your site's cache, all Product content will follow the new template, and all new Product nodes will follow it as well.
> 0 votes

# Answer
Visit this link- https://api.drupal.org/api/drupal/modules!node!node.tpl.php/7 . You can copy node.tpl.php into your theme folder and then modify the code to control the output.
> 0 votes

# Answer
There is couple ways/modules to do that:

If you dont want to code use Display Suite: https://drupal.org/project/ds (you can change fields markup, rearange them and put into regions)

OR

If you want only to change field markup us https://drupal.org/project/semantic\_fields , and them rearange code them in node--\[contenttypename\].tpl.php

OR (my personal favourite)

Turn on Devel module. Put dsm($node) in node--\[contenttypename\].tpl.php - you'll see the node object and can reach for raw field values. Print them with your markup around.
> 0 votes

# Answer
Using Display Suite is my preferred method. https://drupal.org/project/ds

You can create multiple view modes for each content type. For each one, you can control the layout, which fields to display, and the markup for those fields. You can then choose which view mode to use when displaying them in Views. All of the Display Suite configuration is exportable, so it works well with the Features module.
> 0 votes

---
Tags: theming
---


# Question
Title: Calendar Multiple URL's Output Specific Block/Menu Dead Links
Hi I've created a block that I only want to appear in the members area this includes a page where I use the Calendar Module, the problem I have is that I have listed the pages where the block should be outputted however with the calendar there are multiple url's for every view depending on month, so I can't feasibly output the block with all of these pages/url's which are possible through the calendar......

So is there a way to output this block specifically for every view output of the calendar, aside from listing all the url's in the block configuration page......

Also another issue the menu of the calendar isn't working, is there some setting I need to turn on in the admin area to get the menu to work........

http://www.cambrianvacation.co.uk/artbelow/?q=calendar-created/month

Regards

Ant

# Answer
> 0 votes
Block visibility settings accept wildcard characters. If the calendar URL's are of the form, say:

```
/calendar/april/....
/calendar/may/....

```

all you have to do is to enter `calendar/*` in the block visibility settings, and all the pages will be identified. (Adjust according to the actual path of your calendar.)

---
Tags: datetime
---


# Question
Title: How to render a Get Locations map programmatically?
I'm using Get Locations module and the `getlocations_fields` submodule. I have a content type where I created a "Getlocations Fields" field, this way I can select locations when adding/editing content. I have multiple nodes which contain locations.
Now **I would like to display one Get Locations map from given nodes (I have some node ids) *programmatically*.** (I know there's Views integration, but I have a complicated task.)

What is the appropriate way to do this? I haven't found the right method yet, I don't know how **Get Locations module's API** works.

---

Hmm, maybe inspecting "A map in your own module" (https://drupal.org/node/2061951) and `getlocations_fields_field_formatter_view()` in `getlocations_fields.module` is a good start.

OK, I created a block output as per *"A map in your own module"*. Now I need to collect the content of `$latlons` array. Do you know **how to retrieve these data from entities with Get Locations API**?

On `admin/config/services/getlocations`, you can configure different map markers for taxonomy terms if you "*Enable Markers for Terms (Select Vocabularies enabled in a Term reference field)*". I set a term reference field for my content type, and this way the NODE appears with the given marker. I would like to keep this behavior, "querying" the Get Locations field's data with markers for a given node, and display that appropriately. But I can't figure out how.

# Answer
As per **hutch**'s comment, and my experiments, I managed to solve it. I wrote it down here: https://drupal.org/node/2082137#comment-7832139.

I created a separate function for the task:

```
/**
 * Load a map from multiple node ids with the appropriate markers
 *
 * @param array $nids The node ids of the nodes you want to get displayed on the map.
 * @param array $getlocations_extra_settings Some extra settings you want to override the default values with.
 * @see https:// drupal.org/node/2082137
 * @todo Patch for getlocations_setlocations() to accept settings which override the defaults, or figure out an alternative solution.
 */
function getlocations_nodemap_multiple($nids = array(), $getlocations_extra_settings = array()) {

  $latlons = array();
  $minmaxes = array('minlat' => 0, 'minlon' => 0, 'maxlat' => 0, 'maxlon' => 0);
  $count_nids = 0;
  // override default settings
  $getlocations_settings = array_merge(getlocations_defaults(), $getlocations_extra_settings);
  $marker = $getlocations_settings['node_map_marker'];
  $typemarkers = getlocations_get_markertypes('node');

  foreach ($nids as $nid) {

    // maybe a less resource consuming method should be used
    // btw., what about entity_load()? (https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7)
    $node = node_load($nid);
    $locations = getlocations_load_locations($node->vid);

    if (isset($typemarkers[$node->type]) && $typemarkers[$node->type]) {
      $marker = $typemarkers[$node->type];
    }

    if (count($locations)) {
      // we should loop over them and dump bummers with no lat/lon
      foreach ($locations AS $key => $location) {
        $latlon = getlocations_latlon_check($location['latitude'] . ',' . $location['longitude']);
        if ($latlon) {
          $minmaxes = getlocations_do_minmaxes($count_nids, $location, $minmaxes);

          if (!isset($location['key'])) {
            $location['key'] = '';
          }
          else {
            if ($location['key'] == 'nid') {
              $location['lid'] = $nid;
            }
            elseif ($location['key'] == 'vid') {
              // not vid?
              $location['lid'] = $nid;
            }
          }

          // term markers
          $marker = getlocations_get_term_marker($nid, $marker);

          // per location marker
          if (isset($location['marker']) && ! empty($location['marker'])) {
            $marker = $location['marker'];
          }

          $count_nids++;

          $name = htmlspecialchars_decode($location['name'] ? strip_tags($location['name']) : strip_tags($node->title), ENT_QUOTES);
          $latlons[] = array($location['latitude'], $location['longitude'], $location['lid'], $name, $marker, $location['key']);
        }
      }
    }
  }

  if ($count_nids < 2 ) {
    $minmaxes = NULL;
  }
  return getlocations_setlocations($latlons, $minmaxes);
}

```

And now I can call it like this:

```
function testmodule_any_custom_page_callback_you_want_to_use($blabla) {

  $output = '';

  $nids_array = array(41, 45, 52, 73, 219); // of course, this array is generated

  $getlocations_extra_settings = array();
  $getlocations_extra_settings['extcontrol'] = 'testmodule';
  $getlocations_extra_settings['fullscreen'] = 1;
  $getlocations_extra_settings['streetview_show'] = 1;
  $getlocations_extra_settings['maptype'] = 'Map';
  $getlocations_extra_settings['visual_refresh'] = 1;

  $output = getlocations_nodemap_multiple($nids_array, $getlocations_extra_settings);

  return $output;

}

```

This solution currently has its limitations, because unfortunately the default settings are hardcoded to `getlocations_setlocations` (the values of `getlocations_defaults()` are currently hardcoded). I hope **hutch** will develop this part further. :)
> 0 votes

---
Tags: google-maps, location
---


title: Editors choose layout

text:
# Question
Title: Editors choose layout
I want to give editors the ability to take advantage of a grid system we have on our site. I can easily jump into a node and add this to the Body

```
<div class="grid-12 alpha omega">one column</div>
<div class="grid-6 alpha">content on the left</div>
<div class="grid-6 omega">content on the right</div>
<div class="grid-12 alpha omega">one column</div>
...

```

Editors aren't savvy enough with HTML and CSS to do this themselves, and that's fine, that's what wysiwyg editors are for, and why we use Drupal in the first place (mainly).

But, this is a system of layout that can be applied consistently on any node. I'd think it would be easy enough to allow editors to take advantage of it. **I'd love to let them create as many rows with as many columns as they want on any node without having to code it up themselves.**

I know I can create template files that will apply structured HTML to all nodes of a given type, or one node, or some subset of nodes. However, I don't want to make that choice for editors. And besides, you can't split up the body content of a node into rows and columns like that from a tpl.php file.

I've looked into Panels too, but from what I can tell that's just a GUI means of creating tpl.php files. Same problem.

This is very similar to the unanswered question Select Panel Node Layout on Node edit form. I'm using 7.

# Answer
My advice would be to use Field Collection.

1. Add a "collection field" and set it as "multiple values". Each value will be a row.
2. In that collection field, set one text field and one option field (like select list : text)
3. For that option field, the options will be the regions where the text will be displayed.
4. Create a Panel for the node, and in each region, place a view that displays the text, filtered by the option field that goes with that region.

EDIT: I just saw that you also wanted "as many columns as they want"... Then you'll have to play with your option field and set it to a numeric value, that you'll use in css or something like that. It will be quite more complicated, but feasible !
> 1 votes

# Answer
You're asking a chicken and egg problem. Nodes just hold data and no information about the theme (usually). You're describing mixing the two in the Body field of a node, in essence hard-coding the look (layout) of your "node" in the database.

Drupal in many respects fights this as the page content is 1 item and drupal7 cares nothing about whats around it. In D8 their is a UX initiative to make a nicer page layout creation system.

In D7 you may be interested in context\_layouts found in Context. See this youtube video on its usage.

I've done something similar (but not Grid aware) using Spaces, spaces\_node and Dashboard (spaces dashboard) in Drupal6 per node (I also used node\_block heavily). Every node/page could have their own unique layout using Spaces and its submodule of Dashboard; you can set any content to any block/region of the page as needed using a drag-and-drop overlay. Actually, the site I'm mentioning is UCSB SageCenter. Unless your logged in and editing a Space/Dashboard you dont really see anything in the source. I added a node field to pre-assign a known space for node pages on node creation. This site was hard.

Here's a video demo on spaces\_node -- its not supported anymore really.
> 2 votes

# Answer
I'd possibly use something like Context Entity Field in conjunction with Delta and Omega (which it looks like you're using). You could create a couple of delta templates for a user to choose from, and then put a Context entity field onto your nodes.

Then you set up a couple of Contexts to react based on the value of the Context entity field.

*For example:*

Contributor one adds some content, and wants to use a delta template you've called "Awesome 6 column layout". They set the value of their Context entity field to "Awesome 6 column layout". When they view their content, Context changes the delta template being used!
> 1 votes

# Answer
I think you should give Panels another shot. If you use the Clean Markup module, you can change the markup and classes of Panel panes and regions. allowing you to put grid classes on them.

If you also use Panelizer, you can change the Panels layout and markup on a per node basis.
> 0 votes

---
Tags: panels, theming
---


title: Adding a line of code to all pages

text:
# Question
Title: Adding a line of code to all pages
I have recently taken over the final stages of construction of 3 websites that were built in Drupal 7. I have never used drupal before and have run into a problem. My footer in one of the websites is not visible. This was due to the color style sheet not being pointed to in the page code. I copied the existing code into dreamweaver and resolved the issue, but cannot upload to the server as I cannot find the pages on the server, so i have no file i can replace.

The code looks like this:

@import url("themes/bartik/css/layoutb3ea.css?mry7g9");

@import url("themes/bartik/css/styleb3ea.css?mry7g9");

It needs to look tike this:

@import url("themes/bartik/css/layoutb3ea.css?mry7g9");

@import url("themes/bartik/css/styleb3ea.css?mry7g9");

@import url("sites/default/files/color/bartik-23dc1686/colors.css?m9ub8w");

You can see that the last line of code is missing. I am used to working in dreamweaver and I am not familiar with the how the file system works in Drupal.

How do I add that line in to all the pages?

# Answer
> 2 votes
You should familiarize yourself with Drupal theming. Check out the Theming Guide.

Basically, you want to edit the CSS in the theme that's currently being used on your site.

# Answer
> 0 votes
@dcmouyard is right. Also you can find YOURTHEMENAME.info and edit it. Find `stylesheets[all][] = css/SOMECSS.css` and add your stylesheet with path.

---
Tags: theming
---


# Question
Title: How to display text next to image drupal view?
I have created a view displaying unordered list of fields - image, Title, descriprion.

How do I get the title and description to display next to image, eg

```
 IMAGE | Title
         Description

```

# Answer
The simplest solution to your problem is, on right side in views there is a format option set it to Unformatted list, in settings do not select Add views row classes and Add striping (odd/even), first/last row classes.

Below that is Show:Fields | Settings , click settings and select Provide default field wrapper elements and then select the fields mentioned below it to be displayed inline, which in your case is image Title and description.

Also the Table Format is good option but it creates a lot of problem in CSS customization.
> 2 votes

# Answer
You can use Views Fieldset module ,it will allow you to container for set of fields in views (fieldset) and then you can have image in one fieldset(let say image\_fieldset) and other related fields in second fieldset(let say other\_fields\_field\_set)

```
//finally some css tweaks like
.say image_fieldset {
float:left;
}

```

css as per you need
> 1 votes

# Answer
A simple solution is to use a **Table Format** for the views display with 3 different fields without labels. It will never break!
> 0 votes

---
Tags: theming
---


title: Page hit count not visible on pages

text:
# Question
Title: Page hit count not visible on pages
I installed and configured statistics module and I am successful of obtaining reports. However, I wanted to view the page hit count on each page, which I am not getting. What I did: 1. Installed and configured statistics module 2.Enabled Access Log --\> discard access logs older than 3 days 3. Checked count content views 4. Administer statistics and view content access statistics permission only for the administrator 5.view content hits permission for all users (authenticated/administrator/anonymous). After all these, when I open a node or a page, I am not able to view anything related to reads or hits or page views. Please suggest me, what should I do?

# Answer
> 0 votes
I guess you need to enable Count content views in the same configuration page and don't need to enable access log.

---
Tags: 7, nodes
---


# Question
Title: How to mark calendar days between two dates?
I added two cck for start date and end date. I want to mark the dates on calendar.

If I select the start date and end date in single field by enabling requires `to date` option it works fine.

But I have a different date field for end date.How to do it?

# Answer
I did this with the same date field and enabled the to date option.
> -1 votes

---
Tags: 7, datetime
---


# Question
Title: Listing the terms of a Taxonomy Vocabulary in a Tree structure using Views
I am on drupal7. I am trying to list all the terms of a vocabulary in a view. However the Taxonomy vocabulary has multilevel categories and subcategories.

> Is there any module to Show the list in a view so that Initially **Parents** will be displayed, then when **hovered or clicked** on parent all its **child terms** are displayed, if **hovered** or **clicked** on child its **sub-child** are shown.

I want to display the list in the sidebar first or in the header part of the front page .

Example:

Similar to the style how categories in Flipkart are displayed.

Any help!

# Answer
Taxonomy menu module you are looking for and also you can integrate with views, See the demo here

> * Custom Menu per vocabulary
> * Uses the default taxonomy term path or custom paths
> * Integrate with Views
> * Integrate with Pathauto: use URL/path aliases
> * Does not interfere with other menu modules
> 2 votes

---
Tags: views, routes, taxonomy-terms
---


# Question
Title: How to include block using machine name?
I created a custom block that I want to include in my template file. But I don't want to include using block id. Is there any way to do it?

I enabled the box module so a machine name is added with each block. I want to add using machine name.

# Answer
If you want to export the block as part of a Feature (as per your comment above), then you can use the Features Extra module.

> Features Extra provides faux exportables (via Features) of several site-building components.
>
> \[...\]
>
> **Block**
>
> To export a block, install FE Block, edit your block, give it a "machine name," export it with Features. You can export block settings (region settings, visibility settings, ...) of any block, and the content of blocks created with the Block module from Drupal core. The D7 version supports the Block Class, i18n block and Block Cache Alter modules.
> 1 votes

# Answer
I dont think there are any machine names associated with a block. At least didnt saw it in the database. And by the way, why will you want to use the machine name when you already have an unique identifier like the "bid"/"delta" ??
> 1 votes

# Answer
The "Drupal way" is to never use blocks directly, as theme shouldn't need any blocks to exist. Simplest way is to create a region. Regions have machine names all right. Then put your block into it. Features can export block to region associations.
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to set image style for particular image in node creation or edit?
I want to add some **image style** to the particular image, preferably the first image for adding some badge like "**Agent Face Image**".

My idea is when creating the node, there is an option for check box. If the user selected the check box, a particular style need to be applied to that image only, if unchecked then vice-versa. I'm using Drupal 6.

**How can I achieve this?**

# Answer
> 3 votes
If you are asking "How can I theme the first image in a multi-value field differently from the remaining images in that field?" you can use a custom field template.

First, copy `content-field.tpl.php` from the CCK module (found in `modules/cck/theme/content-field.tpl.php`) to your theme's directory.

Then copy it to `content-field-field_NAME_OF_FIELD.tpl.php` eg something along the lines of `content-field-field_pictures.tpl.php`.

NOTE: You **must** have **both** `content-field.tpl.php` **and** `content-field-field_whatever.tpl.php` in the same directory in your theme or it won't work.

Inside, it looks basically like this:

```
<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>
    <div class="field-label"><?php print t($label) ?>: </div>
  <?php endif;?>
  <div class="field-items">
    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>: </div>
          <?php } ?>
          <?php print $item['view'] ?>
        </div>
      <?php $count++;
      endif;
    endforeach;?>
  </div>
</div>
<?php endif; ?>

```

and you will be wanting to change the `<?php print $item['view'] ?>` line in the middle.

Dull ax approach, this would do it:

```
<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>
    <div class="field-label"><?php print t($label) ?>: </div>
  <?php endif;?>
  <div class="field-items">
    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>: </div>
          <?php } ?>
          <?php
            if ($count==1) {
              $first=str_replace('100x100','228x228', $item['view']);
              print $first;
            } else {
              print $item['view'];
            }
          ?>
        </div>
      <?php $count++;
      endif;
    endforeach;?>
  </div>
</div>
<?php endif; ?>

```

where, if in your CCK configuration you have `100x100` as the imagecache style for this field as the default, it is changed to `228x228` for the first image.

Obviously, if 100x100 appears anywhere else this fails so I am sure something more eloquent could be created. But in either case, clear caches/theme registry and you should be on your way.

Also, I've left out any logic based upon toggling this on another field's value, but all the information is available in that template to do so.

# Answer
> 0 votes
It looks like you only want to backport Formatter Field to Drupal 6.

> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Looks exactly like your use case.

# Answer
> 0 votes
An easy way out, might be to have two image fields in the same content type. This way you can style these fields differently using different displays or views. The editor can decide not to use one or the other image field (or use both).

If you have one single image field and one multiple image field, you can use the single image field as a teaser image and/or a main image - and use the multiple image field to display a slide show or some sort of image gallery display.

If you need some "if this is empty then show this" logic, you might look into these discussions: https://drupal.org/node/206012, https://drupal.org/node/945268

# Answer
> 0 votes
As a work around

---
Tags: 6, media
---


# Question
Title: Query to include if condition in addField
How can I use the following SQL query with code that calls `db_select()`?

```
SELECT N_en.nid AS en_nid, IF(N_lan.translate = 1, 'Outdated', 'New') as lan_translated
  FROM node N_en
  LEFT JOIN node N_lan ON N_lan.tnid = N_en.nid

```

The following code does not work.

```
$query = db_select('node', 'N_en')->extend('PagerDefault');
$query->addField('N_en', 'nid', 'en_nid');
$query->addField('N_lan', 'translate', 'lan_translated');
$query->leftJoin('node', 'N_lan', 'N_en.nid=N_lan.tnid AND N_lan.language=:lang', array(':lang' => $userLan));

```

# Answer
You can add an expression:

```
...
$query->addExpression("IF(N_lan.translate = 1, 'Outdated', 'New')", 'lan_translated');
....

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: get the list of menu items that are valid possible parents for the given menu item using menu_parent_options()
I want to get the list of parents for a given menu item. As described at api.drupal.org https://api.drupal.org/api/drupal/modules%21menu%21menu.module/function/menu\_parent\_options/7 I tried but i am not able to get all the parent of a menu item. As the second argument $item to this function should be menu item i tried this code. For example

```
<?php
$menu_name = array('management' => 'Management');
var_dump(menu_parent_options($menu_name, menu_link_load(23)));
?>

```

I want to get the parent list of menu /admin/appearance/list which have mlid = 23. But this code give output

> array (size=1) 'management:0' =\> string '' (length=12)

but output should give /admin/ and /admin/appearance also in output in the form of

> menuname:mlid

# Answer
Try this and see if it helps

```
<?php
$menu_arr = menu_get_menus();
echo '<pre>';print_r((menu_parent_options($menu_arr, 23)));
?>

```
> 1 votes

---
Tags: routes
---


title: how to properly show MENU LOCAL TASK

text:
# Question
Title: how to properly show MENU LOCAL TASK
Hoping to get some advises from experts here regarding the Menu Local Task on user/uid/edit page. You see, I'm taking over a project at the brink of death. I have no idea why they hide all the local tasks tab.

I know that showing it on page.tpl.php is as simple as "print $tabs", however the fact that i am using splitting User/uid/edit pages into two (using EditProfile modules) complicates thing a bit.

My objective here is to show that local tasks (View/Edit Profile/Account Settings/Notification Settings) on templates/edit/edit-acct-settings.tpl.php page.

So far I could make that happen by this line on that template page.

```
if ($tabs = render(menu_local_tasks())): print $tabs; endif;

```

But, I'm sure there's a friendlier way to do this. Again, I have no idea how they made the tabs disappear.

And it came rendered as normal list, not tabs. And I dunno how to exactly theme it if it's the current page. Hoping he "Edit Profile" would go bold or something when I'm on Edit Profile page.

Any advise appreciated. TGIF!

# Answer
Managed to find my solution! This thread here is my saviour: Print primary and secondary tabs separately

**In templates/edit/edit-acct-settings.tpl.php page**

```
<?php if ($primary_local_tasks): ?>
<ul class="tabs primary"><?php print render($primary_local_tasks); ?></ul>
<?php endif; ?>

```

**In my\_theme/template.php**

```
function mythemename_preprocess_user_profile_form(&$vars) {

  $vars['primary_local_tasks'] = menu_primary_local_tasks();
  $vars['secondary_local_tasks'] = menu_secondary_local_tasks();
}

```

Hope this helps any other newbies who encounter same issue! Thanks all~
> 1 votes

---
Tags: 7, routes
---


title: What are all the directories for?

text:
# Question
Title: What are all the directories for?
Drupal 8 re-arranged all the directories and locations of modules/themes etc. Where do things go now?

# Answer
* **/core** contains all the files provided by core that doesn't have an explicit reason to be in the / directory.
* **/libraries** contains third-party libraries. It's not used by Drupal core, but it's commonly found in many sites.
* **/modules** is the directory into which all custom and contributed modules go.
This directory contains the **contrib** and **custom** sub-directories, which can be used to make easier to keep track of the modules.
* **/profiles** contains contributed and custom profiles.
* **/themes** contains contributed and custom (sub)themes.
* **/sites** is the directory used for running Drupal multi-site setups and it's used in the same way as in Drupal 7. Modules and themes in **/sites/all/modules** and **/sites/all/themes** will override the ones in the base **modules** and **themes** directories. Modules in **/sites/SITENAME/modules** and **/sites/SITENAME/themes** will override others for the given site.
* **/vendor** is the directory where Composer dependencies go, for example Symfony and Twig.

Details on the /core directory, primarily useful to know for new core hackers:

* **/core/assets** \- Various external libraries used by Core. jQuery, underscore, modernizer etc.
* **/core/misc** \- Frontend code that Drupal Core depends on.
* **/core/includes** \- Functionality that is to low level to be modular. Such as the module system itself.
* **/core/lib** \- Drupal Core classes.
* **/core/modules** \- Drupal Core modules.
* **/core/profiles** \- Drupal Core installation profiles. Minimal, Standard, Testing and Testing multilingual installation profiles by default.
* **/core/scripts** \- Various CLI scripts, mostly used by developers.
* **/core/tests** \- Drupal Core tests.
* **/core/themes** \- Drupal Core themes.
> 79 votes

---
Tags: 8
---


title: Disable lock_release_all

text:
# Question
Title: Disable lock_release_all
I am testing my module, using a custom SQLite database. It has minimal amount of tables, necessary for the module. I run this function.

```
function test_header(&$modules, &$path_var = null) {
  $file_path = dirname(__FILE__);
  $path = preg_replace('/sites.*/', "", $file_path);
  $path = substr_replace($path ,"",-1);
  $_SERVER['DOCUMENT_ROOT'] = $path;

  define('DRUPAL_ROOT', $path);

  if (!is_null($path_var)) {
    $path_var = $path;
  }

  error_reporting(E_ALL ^ E_NOTICE);
  $path .= DIRECTORY_SEPARATOR . 'includes'.  DIRECTORY_SEPARATOR . 'bootstrap.inc';
  require_once($path);
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

  foreach($modules as $value) {
    drupal_load('module', $value);
  }

  return $file_path;
}

```

I run it with modules that need to be loaded.

```
$modules = array("members");
$file_path = test_header($modules);

```

Then I load the SQLite database, using this function.

```
function set_db($db_name, $db_alias, $driver = 'sqlite') {
  $test_database = array(
    'database' => $db_name,
    'username' => 'user',
    'password' => '',
    'host' => 'localhost',
    'driver' => $driver,
  );

  Database::addConnectionInfo($db_alias, 'default', $test_database);
  db_set_active($db_alias);
}

```

For one of the modules it works correctly. But for another one it gives an error, when I change `DRUPAL_BOOTSTRAP_DATABASE` to `DRUPAL_BOOTSTRAP_FULL`.

> General error: 1 no such table: semaphore: DELETE FROM {semaphore} WHERE (value = :db\_condition\_placeholder\_0) ; Array(\[:db\_condition\_placeholder\_0\] =\> 8994220325229a65a473108.08075181)
> in lock\_release\_all()

Without `DRUPAL_BOOTSTRAP_FULL` it gives some cryptic error.

It seems that it runs this function in the end, and it doesn't find the semaphore table in the SQLite database.

How can I turn off this function and everything else unnecessary?

# Answer
The lock system is initialized during bootstrap (during the `DRUPAL_BOOTSTRAP_VARIABLES` phase, which follows the `DRUPAL_BOOTSTRAP_DATABASE` one) using the following code.

```
// Initialize the lock system.
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
lock_initialize();

```

You could:

* Bootstrap Drupal to the `DRUPAL_BOOTSTRAP_DATABASE` phase
* Change the value of the lock\_inc Drupal variable to make it point to an include file containing your implementation of the lock system, with functions that don't do anything
* Execute the rest of the code, including the one to raise the bootstrap level to the desired one

Since you are loading other modules, this resolves the problem with the lock database table, but it doesn't avoid that modules try to access a database table that normally exists on a Drupal installation, including the ones they install. If you need to execute a query (for example, a `SELECT`) on a database that is different from the default one you could use the following code.

```
Database::addConnectionInfo($db_alias, 'default', $test_database);
query = Database::getConnection('default', $db_alias)->select('table name', 'table alias');
// The rest of the code goes here.

```

The first two arguments for Database::addConnectionInfo() and Database::getConnection() are flipped: The first argument of `Database::addConnectionInfo()` becomes the second argument of `Database::getConnection()`, and the second argument of `Database::addConnectionInfo()` becomes the first argument of `Database::getConnection()`.
> 1 votes

---
Tags: 7, testing
---


title: Table drag and AHAH

text:
# Question
Title: Table drag and AHAH
I got a new content type in my own module for Drupal 6. I want the user to create lists with some entries. For this, I tried to build a draggable table with an AHAH button to add a new row to this table.

In `hook_form()`, I add some items with the following code.

```
$form['listsWrapper'] = array(
 '#weight' => 5,
 '#tree' => true,
 '#prefix' => '<div id="lists-wrapper">',
 '#suffix' => '</div>',
);

$form['listsWrapper']['tableItem'] = array(
 '#type' => 'item',
 '#value' => '',
);

$entries = array();
$entries[] = array( 'name' => 'TestName #1' );
$entries[] = array( 'name' => 'TestName #2' );
$entries[] = array( 'name' => 'TestName #3' );
$entries[] = array( 'name' => 'TestName #4' );

foreach ($entries as $key => $value) {
  $form['listsWrapper']['lists'][] = array(
   'entry' => array(
     '#type' => 'textfield',
     '#default_value' => $value['name'],
     '#maxlength' => 255,
    ),
    'weight' => array(
     '#type' => 'weight',
     // '#default_value' => $key,
     '#attributes' => array('class' => 'weight-group'),
    ),
    'parent' => array(
     '#type' => 'textfield',
     '#attributes' => array('class' => 'parent'),
     '#size' => 10
    ),
    'source' => array(
     '#type' => 'textfield',
     '#default_value' => $key,
     '#attributes' => array('class' => 'source'),
     '#size' => 10
    ),
  );
}

# ahah callback button
$form['listsWrapper']['more'] = array(
 '#type' => 'submit',
 '#value' => t('Eine weitere Liste / einen weiteren Listeneintrag hinzufügen'),
 '#weight' => 1,
 '#submit' => array(),
 '#ahah' => array(
  'path' => ahah_helper_path(array('listsWrapper')),
  'wrapper' => 'lists-wrapper',
  'method' => 'replace',
 ),
);

```

In the theme function for this form, I add a table drag behavior to these elements.

```
function theme_cm_node_form($form) {
  $output = '';

  if(isset($form['listsWrapper'])) {
    drupal_add_tabledrag('draggable-lists-table', 'match', 'parent', 'parent', 'parent', 'source', TRUE, 1);
    drupal_add_tabledrag('draggable-lists-table', 'order', 'sibling', 'weight-group', NULL, NULL, TRUE);

    $header = array(t('Listeneintrag'), t('Gewichtung'));
    $rows = array();
    $lists = array();
    $entries = array();

    foreach (element_children($form['listsWrapper']['lists']) as $key) {
      $element = &$form['listsWrapper']['lists'][$key];

      if ($element['parent']['#value'] == '') {
        //parent
        $i = 0;
        while(isset($lists[$element['weight']['#value']+$i])) $i++;
        $pos = $element['weight']['#value']+$i;

        $lists[$pos] = $key;

      }
      else {
        //entry
        $i = 0;
        while (isset($entries[ $element['parent']['#value'] ][ $element['weight']['#value']+$i ])) {
          $i++;
        }

        $pos = $element['weight']['#value']+$i;
        $entries[ $element['parent']['#value'] ][$pos] = $key;
      }
    }

    ksort($lists);

    foreach ($lists as $list) {
      $element = &$form['listsWrapper']['lists'][$list];
      $row = array();

      $row[] = drupal_render($element['entry']);
      $row[] = drupal_render($element['weight']) . drupal_render($element['parent']) . drupal_render($element['source']);
      $rows[] = array('data' => $row, 'class' => 'draggable');

      ksort($entries[$list]);
      foreach ($entries[$list] as $entry) {
        $elementEntry = &$form['listsWrapper']['lists'][$entry];
        $row = array();

        $row[] = theme('indentation', 1) . drupal_render($elementEntry['entry']);
        $row[] = drupal_render($elementEntry['weight']) . drupal_render($elementEntry['parent']) . drupal_render($elementEntry['source']);
        $rows[] = array('data' => $row, 'class' => 'draggable');
      }
    }

    if(!count($rows)) {
      $rows[] = array(array('data' => t('Derzeit sind noch keine Listeneinträge erstellt.'), 'colspan' => 2));
    }

    $form['listsWrapper']['tableItem']['#value'] = theme('table', $header, $rows, array('id' => 'draggable-lists-table'));
  }

  $output .= drupal_render($form);

  return $output;
}

```

Now I got something like this.

I can rearrange the rows and indent them (so they become a entry instead of a new list). My problem is that the theme function isn't called after my AHAH callback, so my form looks like this.

How can I invoke the theme function after my ahah callback? Do I have to invoke the JavaScript functions which will hide the weight field and so on again?

# Answer
> 1 votes
I bypassed my problem by using jQuery Nestable. I got a hidden form element and on every change in my Nestable list I put a json string in the hidden field. Much easier than using drupal tabledrag and ahah (also looks a bit better in the user front end). Here is what i got now:

Works fine for me.

---
Tags: ajax
---


# Question
Title: Handle permission based on both person and role?
I am using workflow module for a publishing website.

There are many people who have the role reviewer....The comapny want to enable that when you change state from 'in moderation' to 'in-review', we can assign the content to a reviewer through an autocomplete field. NOT ALL reviewers.

Workflow content permissions does a great job, for making it role based. So the author is no longer allowed to edit the article when it is 'in-review' state. Now I don't want to allow all reviewers to edit it 'in-review', only the one that has been selected.

Is there a module for this? If not, how should I be going about this.

P.S. -: I am barely a few weeks into Drupal, so go easy :-)

# Answer
> 0 votes
I suggest first to use the Rules module to fire an action on your workflow transition : from 'in moderation' to 'in-review'

Second try to use the Node access user reference module or the Nodeaccess module to use an API method inside your a custom PHP code or as a rule's action to grant the referenced user

---
Tags: users, workflows
---


title: How to disable the Superfish Accordion?

text:
# Question
Title: How to disable the Superfish Accordion?
Is it possible to disable the superfish accordion 'main menu' link at the smaller responsive sizes? Instead of clicking on 'main menu' to see the navigation, I would like the navigation to already be expanded without having to click on a link. The navigation should go from the horizontal menu directly to the vertical menu.

# Answer
In my superfish navigation block, under superfish settings, set the style of the superfish menu to none and under superfish plugins, disabled sf-Touchscreen.

In my main stylesheet I defined the menu style I wanted at the smaller size.
> 0 votes

---
Tags: 7, routes, navigation
---


# Question
Title: How to unlink the teaser title from the original content?
I have a page having list of teasers populated using views for a certain content type. Now, I want the title of the teaser not to be a link to the original content/node. I want the title in same format but not to be a link. Please help if anybody know how to do it. I am using Drupal 7.

# Answer
On the view you are using, simply click on the title field, and uncheck link field to original piece of content
> 1 votes

# Answer
You can make it by override the node.tpl just go node.tpl.php in your theme and change this lines

```
<?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?></a>
    </h2>
  <?php endif; ?>

```

To be

```
<?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
     <?php print $title; ?>
    </h2>
  <?php endif; ?>

```
> 1 votes

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


# Question
Title: How do I use $form_state to return data from the from submission handler to the form builder?
I am trying to populate a data based on `$form_state` right after submission. What I am trying to do is to populate a form that takes a keyword and passes it to a function that gets the result from another site.

I can use `$form_state['values']['keyword']` in `MYMODULE_form_submit()` but not in `MYMODULE_form_page()`.

How can I achieve this?

```
function MYMODULE_menu() {
  // Module settings.
  $items['MYMODULE'] = array(
    'title' => 'MYMODULE',
    'description' => 'MYMODULE',
    'page callback' => 'MYMODULE_form_page',
    'page arguments' => array('MYMODULE_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_form($form, &$form_submit){
  $form['kname'] = array(
    '#title' => t('What would you like to search:'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please insert the keyword you whish to search for.'),
  );

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

  return $form;
}

function MYMODULE_form_submit($form, &$form_state) {
  $keyword = $form_state['values']['kname'];
  $op = MYMODULE_simple_page($keyword);

  return $op;
}

function MYMODULE_form_page($op) {
  $build = array(
    'header_text' => array(
      '#type' => 'markup',
      '#markup' => '<p></p>',
    ),
    'example_form2' => drupal_get_form('MYMODULE_form'),
    array(
      '#type' => 'markup',
      '#markup' => '<p>'. $op .'</p>',
    ),
  );

  return $build;
}

function MYMODULE_simple_page($keyword) {
  // Query the external website.
  $data = drupal_http_request('API_ADRESS_JSON');

  // Decode JSON.
  $test = drupal_json_decode($data->data);
  $outitem = '';
  $output = '';
  // Loop through the array (converted from JSON) and view the list of the result as titles and images.
  if (isset($test)) {
    for ($i=0; $i<count($test['images']); $i++) {
      $imageName = $test['images'][$i]['title'];
      $variables = array(
        'path' => $test['images'][$i]['thumbnail_path'],
        'alt' => 'Test alt',
        'title' => 'Test title',
        'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
      );
      $img = theme('image', $variables);
      $outitem .= '<div class=image><p><strong>'. $imageName .'</strong></p> <br><p>'. $img .'</p> <br></div>';
    }
  }

  $output .= $outitem;

  return $output;
}

```

# Answer
The only functions that get `$form_state` are form builders, form validation handlers, and form submission handlers.

To say the truth, your code doesn't need to use `MYMODULE_form_page()`: You can simply use the form builder function.

```
function MYMODULE_menu() {
  // Module settings.
  $items['MYMODULE'] = array(
    'title' => 'MYMODULE',
    'description' => 'MYMODULE',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function MYMODULE_form($form, &$form_state) {
  $form['header_text' => array(
    '#markup' => '<p></p>',
  );

  $form['kname'] = array(
    '#title' => t('What would you like to search'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('Please insert the keyword you whish to search for.'),
  );

  if (isset($form_state['MYMODULE_result'])) {
    $form['footer_text'] = array(
      '#markup' => '<p>'. $form_state['MYMODULE_result'] .'</p>',
    );
  }

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

  return $form;
}

function MYMODULE_form_submit($form, &$form_state) {
  $keyword = $form_state['values']['kname'];
  $op = MYMODULE_simple_page($keyword);

  // Form submission handlers don't return any value.
  // If you need to return a value to the form builder, you should use the following code.
  $form_state['MYMODULE_result'] = $op;
  $form_state['rebuild'] = TRUE;
}

```
> 3 votes

---
Tags: forms
---


# Question
Title: Views pager shows an incorrect current page
I have a page view displaying a table of fields with a few exposed filters. This page view also has a full pager (8 items per page). The view is not using AJAX, nor does it have any caching enabled (currently).

When on the view page, using the pager to navigate to specific pages, or next/last page works fine (since the pager adds the "?page=N" query argument). However, the issue I am experiencing is that if I try to navigate from any other page back to page 1 (so the view does not pass "?page=" as an argument), the pager is "stuck" displaying the last page I was on as the current page. The results listed are correct (displays the results for page 1), it is just the pager is displaying the wrong page as selected.

On the first page of results, I click on the pager link to go to page 3; page reloads with results of page 3, and the pager shows page 3 as current page. I then click on the pager link to go to "\<\< first". The page reloads with the results of page 1; however, the pager still shows page 3 as the current page.

A few more details, I am using a custom theme with custom CSS to style the pager (but css should not interfere with the pager). I am not altering the pager at all in my template.php, nor do I have a custom pager.tpl.php.

Has anyone experienced this issue? I am not sure if it is specific to a views pager, or just the Drupal pager in general. I have no idea what could be causing the problem.

I am using Drupal 7.21 and Views 7.x-3.7.

# Answer
> 0 votes
I ran into this issue for a view block when I had caching enabled on the view and block caching enabled under Performance. Try disabling the page caching under Performance.

---
Tags: 7, views, paging
---


# Question
Title: Drupal 6 Apache Solr Search Problems with result ordering & fields
As I am implementing a website made in Drupal 6 and using Apache Solr search as the search application in the website.

Drupal Version 6.22 Apache Solr Version : 3.6 Apache Solr Module: 6.1.x

Below are the two problems I am facing.

1. While searching a particular content the business requirement is to search only in the Title field, Body field and in the Terms attached in a node. How can I achieve that? I have used the HOOK\_apachesolr\_modify\_query() in some other purposes. Do I have to mention all the filters here again? like,

```

mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $query->add_filter('title', $keyword);
   $params['fl'] = 'title';
}

```
1. The second is that once the contents are being searched as per the requirement I should get the result based on the following algorithm.

1st result = (Match in Title + Match in Body + Match in Terms names) (Keyword present in all)
2nd result = (Match in Title + Match in Terms names) (Keyword only present in title & term names)
3rd result = (Match in Title + Match in Body) (Keyword present in Title & Body)

So I added a boost factor from the Apache Solr admin section as Title = 1.0 Term = 0.50 Body = 0.25

But the ordering is not maintained.

I even also mentioned

```

function mymodule_apachesolr_modify_query(&$query, &$params, $caller) {
   $params['qf'] = array('taxonomy_names^0.50', 'title^1.00', 'body^0.25');
}

```

But no effect. Please suggest any ideas. Help me on these issues, I am really stuck here :(

# Answer
> -1 votes
I would suggest you look into the Views module and/or Apache Solr Views. This blog post http://blog.hsl.virginia.edu/drupalpress/apachesolr-views-drupal-6/ might also be useful.

---
Tags: 6, search
---


title: How to create 2 product node displays

text:
# Question
Title: How to create 2 product node displays
How can I create 2 displays of a products node one for Authenticated users and one for anonymous ?

I am trying to create a single products display for my site that will display the product image and all of its fields for a single product basically like most eccomerce stores do with the image on the left and all the details on the right

there needs to be two versions of the display one for anonymous users that will display product without the add to cart button and price fields and rather display Text stating "we do not supply directly to the Public"

and then another display for authenticated users that will display the price and add to cart button.

this was easy to do for the grid views of products on my site I just created 2 views with role based access but for the actual single products node I aparently cannot use views because it is a node.

I am thinking I need to use display suit but how can i create 2 displays and use role based access.

# Answer
> 2 votes
You can use Entity view modes to create two displays for an entity.

> The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.

I'd probably then use Panels to output the product displays (but that's because I'd already be using Panels). Most likely two variants of the `node_view` page that both check user role. If a logged in user is discovered, then use a variant that uses view mode X, if the user is anonymous then use view mode Y.

---
Tags: display-suite
---


# Question
Title: How to disable default extension validation in Drupal's #managed_file Form API element?
I wrote validation function that tests file's mimetype. I commented out my old validators to avoid validation by extension:

```
'DownloadFile' => array(
  '#type' => 'managed_file',
  '#title' => t("Download"),
  '#title_display' => 'invisible',
  //'#description' => t('Allowed extensions: pdf zip exe.'),
  '#upload_validators' => array(
    //'file_validate_extensions' => array('pdf zip exe'),
    'file_validate_size' => array(variable_get('mymodule_image_size', 2 * 1024 * 1024)),
  ),
  '#upload_location' => 'public://mymodule/download',
  '#default_value' => $item->DownloadFile,
  '#required' => TRUE,
  '#theme' => 'preview_upload',
),

```

Now when I'm trying to upload exe, I get:

> The specified file putty.exe could not be uploaded. Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

Now, I will have files without extensions there. And with extensions I cannot predict. And all I want sometimes is to test for a proper MIME type match, not even an exact mimetypes sometimes. So, how can I get rid of extension validation and turn it into "everything goes"?

I managed to find issue that seemed to be about this problem, but it tells to `unset($element['#upload_validators']['file_validate_extensions']);` \- does not make sense to me as I'm creating brand new array and this isn't set at all.

I tried to use `#process` property to add a function that will unset default validators later, like shown there in issue, but `dpr($element)` shows there is nothing to unset:

```
[#upload_validators] => Array
    (
        [file_validate_size] => Array
            (
                [0] => 2097152
            )

    )

```

# Answer
> 2 votes
The answer comes from the following code used by file\_save\_upload().

```
  if (isset($validators['file_validate_extensions'])) {
    if (isset($validators['file_validate_extensions'][0])) {
      // Build the list of non-munged extensions if the caller provided them.
      $extensions = $validators['file_validate_extensions'][0];
    }
    else {
      // If 'file_validate_extensions' is set and the list is empty then the
      // caller wants to allow any extension. In this case we have to remove the
      // validator or else it will reject all extensions.
      unset($validators['file_validate_extensions']);
    }
  }
  else {
    // No validator was provided, so add one using the default list.
    // Build a default non-munged safe list for file_munge_filename().
    $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
    $validators['file_validate_extensions'] = array();
    $validators['file_validate_extensions'][0] = $extensions;
  }

```

In your case you should use the following array.

```
  'DownloadFile' => array(
    '#upload_validators' => array(
      'file_validate_extensions' => array(),
      'file_validate_size' => array(variable_get('mymodule_image_size', 2 * 1024 * 1024)),
    ),
  );

```

In that way `$validators['file_validate_extensions']` is set, but `$validators['file_validate_extensions'][0]` is not. As result, the code will not set `$extensions`, and the following code will not be executed either.

```
  if (!empty($extensions)) {
    // Munge the filename to protect against possible malicious extension hiding
    // within an unknown file type (ie: filename.html.foo).
    $file->filename = file_munge_filename($file->filename, $extensions);
  }

```

The code has a strange way to check if the list is empty; it assumes the array is empty of there isn't an item with index equal to 0. I would have rather used the following one, which would not make assumptions about the lower array index being used.

```
  if (isset($validators['file_validate_extensions'])) {
    if (empty($validators['file_validate_extensions'])) {
      // If 'file_validate_extensions' is set and the list is empty then the
      // caller wants to allow any extension. In this case we have to remove the
      // validator or else it will reject all extensions.
      unset($validators['file_validate_extensions']);
    }
    else {
      // Build the list of non-munged extensions if the caller provided them.
      $extensions = array_shift($validators['file_validate_extensions']);
    }
  }

```

---
Tags: files, forms
---


title: _locale_import_po passing in a file

text:
# Question
Title: _locale_import_po passing in a file
I am trying to use \_locale\_import\_po($file, $langcode, $mode, $group = NULL). I want to point it to a local file in my Drupal site (e.g. drupal-7.23.fr.po').

However, when I try to do this I get the following error:

> fopen(): Filename cannot be empty locale.inc:693

I am using the following code to initialize the `$file` variable passed to the function.

```
  $file = new stdClass();
  $file->filename = 'drupal-7.23.fr.po';
  $file->filepath = drupal_get_path('module', 'mymodule') .'/'. $file->filename;

```

I have the file in sites/all/modules/mymodule/drupal-7.23.fr.po.

# Answer
Line 693 of locale.inc is

```
$fd = fopen($file->uri, 'rb');

```

So you need to provide your file path on the `uri` member of the file object, instead of/in addition to `filepath`.

There are a bunch of different things done with that file object throughout the process you're calling, so there may be more you need to add as well.
> 0 votes

---
Tags: files, i18n-l10n
---


# Question
Title: Uninstall module for which an update is pending?
I have a module for which an update is pending (drush updatedb). Unfortunately the update fails, blocking other updates of course (since it seems impossible to update selectively).

Is it safe to I pm-uninstall the module? Will this automatically delete the pending update? Or do I risk ending up in an even worse limbo?

\[ As noted in the comments, taking a database dump and then restoring if anything goes wrong is an option; I'm still curious if there is a general rule about uninstalling while db updates are pending) \]

(BTW the module is service\_links)

# Answer
Slight correction to Clive's comment above: as soon as you disable the module, it is inactive in the system tables. When you uninstall it, all of its data is erased from the database. The fact that a module has pending updates won't affect the operation of disabling or uninstalling it, but beware of re-enabling a module that has been disabled for a period of time. For way too much information on this subject, see: https://drupal.org/node/1199946
> 2 votes

---
Tags: 7, drush, installation
---


# Question
Title: Showing group managers a list of pending users
We're using Drupal Commons 3.3 and our group managers have been asking for a single view of all pending users. Email is becoming too cumbersome and unmanageable. Is there a View or Pane that I can add showing our Group Managers which users should become members?

# Answer
First, in the View `Commons Contributors - Group (User)`, I cloned the Display `group homepage`

In this new content pane, I then added a footer with a link below. This will take the user to the Administer Group/People page.

```
<a href="/group/node/!1/admin/people">Manage memberships</a>

```

Caveat: On Panels (via /admin/structure/types/manage/group/panelizer/page\_manager/content), I set view permission to: *Logged in User has "Approve or Deny permission for this group"*
> 0 votes

---
Tags: organic-groups, 7
---


title: Module an permission issues

text:
# Question
Title: Module an permission issues
I have a custom module called 'products'

I set the access options like so:

```
function products_permission() {
  return array(
    'access products' => array(
      'title' => t('TBYT Products'),
      'description' => t('Administer TBYT Products'),
    )
  );
}

```

In the admin I have enabled the module and gave everyone this permission.

Then I defined:

```
function products_menu() {
  $items = array();

  $items['products/list'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping',

    'page callback' => 'html_list_products',

    'access arguments' => array('access products')
  );

   return $items;
}

```

This works fine, however I need to now make the URI dynamic, so I added something like:

```
  $items['products/list/%/%'] = array(

```

I also added the appropriate page arguments:

```
'page arguments' => array(2, 3),

```

However when I rebuild the cache and I access:

**products/list/23**

it works fine but when I access

**products/list**

I get:

*The requested page "/products/list" could not be found.*

# Answer
> 2 votes
Addressing the (correct) conclusions you've come to in the comments...

Yes, you'll see some repetition in Drupal 6/7. Drupal 8 uses Symfony routes so things get better, but it's not stable yet.

For your specific case you don't *have* to have 3 separate menu items (although for the sake of clarity it might make sense). You can define a single list page like so

```
function products_menu() {
  $items = array();

  $items['products/list'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Enjoy shopping',
    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

```

And define your page callback like so

```
function html_list_products($arg1 = NULL, $arg2 = NULL) {
  if ($arg1 && arg2) {
    // Both args were provided.
  }
  elseif ($arg1) {
    // Just the first arg was provided.
  }
  else {
    // No args were provided.
  }
}

```

Drupal will always pass along the remaining slash-separated parts of the request URL to the callback function, so with the above method if you visit `/products/list/1/2`, `$arg1` and `$arg2` will be populated respectively. Similarly if you visit `/products/list/1` just `$arg1` will be populated, and for `/products/list`, neither will be.

---
Tags: 7, users
---