# Question
Title: Remove/Hide the block if the View is empty?
Is there any API to know if the block is empty? Basically what I'm trying to do is to hide/unset the block inside `template_preprocess_page`.

Here is my currrent code:

```
 if ($variables['page']['rail_full']) {
    foreach ($variables['page']['rail_full'] as $keys => $blocks) {
      if (isset($blocks['content']['#views_contextual_links_info'])) {
        $name = (isset($blocks['content']['#views_contextual_links_info']['views_ui'])) ? $blocks['content']['#views_contextual_links_info']['views_ui']['view']->name : '';
        $display_id = explode('-', $blocks['#block']->delta);
        $block = views_get_view_result($name, $display_id[1]);
        if (empty($block)) {
          unset($variables['page']['rail_full'][$keys]);
        }
      }
    }
  }

```

But the above code always return a `count` of `1` when I print `$block`.

The below works fine but not a good solution. I want it to be dynamic in all block as possible.

```
if (!isset($variables['node']->field_author_favorite_links['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_2']);
}

if (!isset($variables['node']->field_article_column['en'])) {
    unset($variables['page']['rail_full']['views_franchise_page-block_3']);
}

```

# Answer
> 6 votes
I had the same behavior with "empty" fields. Unless you don't hide the fields themselves, the design/ markup still renders. Solution for me was to filter for fields being "NOT NULL". (Maybe it depends on the "fences"-module i have installed, too. Not sure, because not tested ...)

# Answer
> 2 votes
By default, if a view with a Block display returns no results, it won't be rendered. That is unless you've set some "No Results Behavior" which the view will display when empty. So check to make sure it has nothing set.

So coding shouldn't be necessary unless you're trying to do something more custom. If so, you may want to clarify what it is you're trying to accomplish.

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


# Question
Title: Using hook_node_submit() from a custom module
I have built a custom module named 'ABC'. I have created a content type 'CT' having some text fields. When a user add content of type 'CT' and Save/Preview the form, I want to use the values that the user added in the form and make a web service call and update the form values based on the data returned from the web service call which would further be saved to database.

I am using `hook_node_submit()` as below.

```
function CT_node_submit($node, $form, &$form_state) {
  global $user;
  //dpm($user);
  $nameofuser = $user->name;
  $timezone = $user->timezone;
  $title = $form['field_title']['#value'];
  $pid = $user->uid;
  $pname = $user->name;
  $rurl = $form['field_recording_url']['#value'];
  $purl = $form['field_presenter_url']['#value'];

  $kdetails  = array (
     'nameofuser' => $nameofuser,
'title' => $title,
'pid' => $pid,
'pname' => $pname,
  );
  Make_A_WebService_Call($kdetails, $form, $form_state);
}

```

The problem is that when I am calling the above code from ABC.module file, the code is not being called on clicking the Save/Preview button.

# Answer
> 2 votes
`hook_node_submit()` will only be invoked for the module implementing the associated content type. If module A defines the content type, module B cannot implement `hook_node_submit()` on module A's behalf, unless it specifically calls the function `module_B_node_submit()`.

If you want to hook into the validation process of a node form you can use the standard `hook_form_alter()`, e.g.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['#validate'][] = 'MYMODULE_node_form_validate';
  }
}

function MYMODULE_node_form_validate($form, &$form_state) {
  // Logic here...
}

```

# Answer
> 1 votes
In short, you are saying that in the ABC.module you are implemented the CT content type, and you are wondering why `ABC_node_submit()` (the implementation of hook\_node\_submit()) is not being invoked.

If `ABC_node_submit()` is a function contained in ABC.module, then it will be invoked only in the case, the implementation of hook\_node\_info() is similar to the following one.

```
function abc_node_info() {
  return array(
    'ct' => array(
      'name' => t('the content type name'),
      'base' => 'ct',
      'description' => t('the content type description'),
    ),
  );
}

```

(I use lowercase letters since it is preferable that the short name of a module uses only lowercase letters.)

In this case, when invoking `hook_node_submit()` for that content type, Drupal will look for `abc_node_submit()`.

In fact, in the documentation for `hook_node_info()`, `base` is described as follows:

> The base string used to construct callbacks corresponding to this node type (for example, if base is defined as example\_foo, then `example_foo_insert()` will be called when inserting a node of that type). This string is usually the name of the module, but not always.

This answer is valid if `ABC_node_submit()` is a function contained in the ABC.module. If you have two modules (ABC.module and CT.module) where ABC.module is implementing the content type, and CT.module is another module that needs to add a form validation or a form submission handler to the form used to edit a node of that content type, then see Clive's answer.

---
Tags: hooks, nodes
---


# Question
Title: Where is the documentation for the ACL module/api?
Has anyone successfully created a client module that controls node access via the ACL module? I installed this module and created my own UIs to populate the three tables: acl, acl\_node and acl\_user. I started to create nodes, which populated acl\_node with appropriate values, but nothing else seemed to happen. No new realm in the node-access table, nothing. Have I missed a step? I can't find any documentation on this module/api. Thanks.

The notes in the nodes\_access\_example module (part of the examples project) encourage you to 'read up' on the ACL module. I can't find anything to read though.

# Answer
> 2 votes
If you take a look at the ACL project page, you'll see that the following four client modules exist:

You'll find plenty of examples on how to use the API in the source code of those.

The documentation for ACL are the comments embedded inside `acl.module`. They are quite helpful when you try to create a client module.

P.S.: I am the maintainer of Flexi Access. I can verify that ACL works as advertised.

---
Tags: users
---


# Question
Title: Utilizing admin panel values elsewhere in a module
So I've got a custom admin panel page in a module I've written, and I want to get a value out of it.

Let's say I have a text box on this admin page, with a value, and I want to get that at some other point.

Do I need to use variable\_set and put that into the database and then variable\_get it in the function I want to use it in - or do I call it some other way?

Basically this thread:

https://drupal.org/node/2074589

Essentially, I just want to have a user be able to select a picklist value in the admin, and then call that picklist value later on in the actual module, for display.

# Answer
You need to utilize `system_settings_form` when you write your admin form.

```
function mymodule_admin_form($form, &$form_state) {
  $form['my_textfield'] = array(
    '#type' => 'text',
    '#title' => 'Title',
    '#default_value' => isset($form_state['values']['my_textfield']) ? $form_state['values']['my_textfield'] : '',
  );

  return system_settings_form($form);
}

```

Submitting this form will call `system_settings_form_submit` which saves all the form fields as a variable, so you need to be careful when naming the form fields.

Now all you need to do is call:

`variable_get('my_textfield', 'default value to return if no value is set');`

from any function after drupal is bootstrapped.

Here's more information on how to create a configuration form: Creating the configuration form
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to print formatted contents of Viewfield in a custom template?
I am having trouble printing the contents of two Viewfields in my custom node template. They are two separate blocks in the same overall View. I have tried the following, but it did not print anything:

```
<?php echo $node->field_fieldname1[0]['view']; ?>
<?php echo $node->field_fieldname2[0]['view']; ?>

```

When I add

```
<?php print_r($node); ?>

```

to my template, it returns the following for the two Viewfields in question:

> \[field\_fieldname1\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[vname\] =\> myviewname|block\_1 \[vargs\] =\> ) ) )
>
> \[field\_fieldname2\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[vname\] =\> myviewname|block\_2 \[vargs\] =\> ) ) )

Can anyone direct me on how I can print the contents of these Viewfields in my tpl file?

Thanks!

# Answer
> 0 votes
I used the following code:

```
<?php print views_embed_view('myviewname','block_1', $node->nid); ?>
<?php print views_embed_view('myviewname','block_2', $node->nid); ?>

```

And the view's info is printing just fine now in my tpl files. Hope this can help someone in the future.

Thanks for Worldfallz on the Drupal forum for this suggestion! https://drupal.org/node/2075411#comment-7800227

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


# Question
Title: How to import custom content type in XML?
I have installed the newest Drupal 7.12 and need to import custom content type data exported from custom CMS but ... don't know what is the correct XML structure.

1) I have added `<MY_CUSTOM_CONTENT_TYPE>` into Structure \- added about 20 fields

2) prepare Import feed

* Attach to content type: Use standalone form
* Fetcher: file upload
* Parser: Sitemap parser - Parse Sitemap XML format feeds.
* Processor: Node processor
* Node processor settings: Text format: plain text; Content type: `<MY_CUSTOM_CONTENT_TYPE>`

3) I have exported XML file with content (probably with the wrong XML structure)

```
<?xml version="1.0" encoding="UTF-8"?>
<articles>
<article type="MY_CUSTOM_CONTENT_TYPE">
     <title>1234</title>
     <custom_1>1234</custom_1>
     <custom_2>abcd</custom_2>
     ...
     <custom_20>...20...</custom_20>
</article>
</articles>

```

3) after loading XML file getting "There are no new nodes."

I can prepare XML structure when exporting content, but want to know how to do it.

# Answer
> 1 votes
In my case an error *"There are no new nodes"* was caused by a wrong xml context in the xpath parser setting.

In your case should be: `//article` and not only: `article`.

This is because `//article` in xpath is equivalent to say *"all the article tags"*. If you put only *article* in the xpath, context feeds does not import anything.

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


title: Generate password hash

text:
# Question
Title: Generate password hash
I have an external application written in VB.NET that needs to add user accounts to a drupal database.

We tried posting to the /user/register but something is funky with that code and it is not working. I also considered using a RESTful API plugin but that has proven to be more work than we are capable of delivering on short notice.

Just when I figured we could:

1. Add a value to sequences table
2. Use that previous value as ID of next user

We now discover that we need some fancy smancy hashed password. I look into the code and see D7 uses sha512 but also some hashing salt -- which again is yet another drupal method which accepts the number or iterations to hash (or something to that effect).

If the VB app uses a sha512 on a password will this suffice with Drupal? Will uses be able to login?

Tips, comments, etc more than welcome :)

Alex

# Answer
> 2 votes
No - a simple sha512 wouldn't be the same because its lacking the "salt" added by Drupal that prevents the "ability to use pre-hashed lists of candidate passwords" against your database (among other things). Its a security improvement over D5/D6 where a simple md5 update query could reset a user's password.

You might get more mileage out of connecting to the password-hash.sh script (in the scripts folder of your Drupal installation) in your VB script using whatever the equivalent to PHP exec() is in VB..

# Answer
> 0 votes
I believe that you'd need to be SHA512 hashing the password WITH the same style salt(s) as used on the Drupal instance.

My reasoning is that Drupal uses the salt when checking the validity of passwords and if you're saving unsalted SHA512 passwords they won't decode correctly when Drupal uses the Salt.

It's worth a try certainly however you're right in your own deduction that using an API of some form would be a better method.

You should start by following the password creation process in the includes/password.inc file.

You may be able to make use of the password\_hash.sh script in the Scripts folder to perform the heavy lifting or to get ideas on how to implement this.

---
Tags: users
---


title: Setting up Pressflow 6 with Vagrant VM

text:
# Question
Title: Setting up Pressflow 6 with Vagrant VM
Has anyone managed to get Pressflow built into a Vagrant box? I'm new to vagrant and am completely failing at this. Have looked into both Puppet and Chef to configure it (either would be fine) and can't seem to find a recipe that does the trick.

This example.make file seems to describe a way to do this with Puppet, but then I have the added complexity of putting Drush on the vagrant box and I'm not really even sure what to do with the ".make" file.

Any pointers are appreciated - thanks!

EDIT:

Here's the state of my Vagrantfile:

```
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant::Config.run do |config|

 # Every Vagrant virtual environment requires a box to build off of.
 config.vm.box = "quetzal64"

 # Boot with a GUI so you can see the screen. (Default is headless)
 # config.vm.boot_mode = :gui

 # Forward a port from the guest to the host, which allows for outside
 # computers to access the VM, whereas host only networking does not.
 config.vm.forward_port 80, 8080
 config.vm.forward_port 3036, 3037

 # somehow specify to use drush, puppet, and the example.make file?

end

```

and example.make:

```
; Core version
; ------------
core = 6.x

; API version
; ------------
api = 2

; Core project
; ------------
; Use Pressflow instead of Drupal core:
projects[pressflow][type] = "core"
projects[pressflow][download][type] = "file"
projects[pressflow][download][url] = "http://launchpad.net/pressflow/6.x/6.15.73/+download/pressflow-6.15.73.tar.gz"

```

# Answer
After trying quite a few things, we ended up putting together a shell script to do the provisioning. Most of it is specific to our application, but here are the relevant excerpts for anyone who might want to try this:

(there is probably some configuration necessary that this script omits)

```
#!/bin/sh

cd ~

echo "Beginning fresh install..."
sudo apt-get update

echo "Installing base utilities..."
sudo apt-get -qq -y install zip unzip

# Install LAMP stack
echo "Installing LAMP stack..."
sudo apt-get -qq -y install tasksel && sudo tasksel install lamp-server
sudo apt-get -qq -y install php5-gd php-pear php5-xdebug php5-dev php5-curl
sudo a2enmod rewrite # Enable apache rewrite module

# Install pressflow if necessary
echo "Downloading and installing pressflow..."
wget -qNO /tmp/pressflow.tar.gz https://github.com/pressflow/6/archive/pressflow-6.26.109.tar.gz
sudo rm -rf /tmp/pressflow && mkdir /tmp/pressflow
tar -xzf /tmp/pressflow.tar.gz -C /tmp/pressflow
sudo rm -rf /tmp/pressflow/6-pressflow-6.26.109/sites/all
rsync -a /tmp/pressflow/6-pressflow-6.26.109/* ~/yoursitepath # !! Your Drupal directory here.
sudo rm -rf /tmp/pressflow /tmp/pressflow.tar.gz

# Update php.ini
echo "Updating PHP config options..."
PHPINILOC="/etc/php5/apache2/php.ini"
sudo sed -i 's/memory_limit = 128M/memory_limit = 1024M/g' $PHPINILOC
sudo sed -i '/error_reporting = E_ALL.*/c\error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT' $PHPINILOC

# Create database schemas
echo "Creating databases..."
mysql -uroot -e"CREATE DATABASE IF NOT EXISTS ourfa5_drupal; CREATE DATABASE IF NOT EXISTS stats;"

# Here, you'll probably need to download any default tables needed by your
#   application, update /etc/hosts, etc.. This portion of the script is
#   specific to our application so I've left it out.

# Restart apache for good measure
sudo service apache2 restart

sudo apt-get upgrade

```
> 0 votes

---
Tags: 6, virtual-machine
---


# Question
Title: Can't get preprocess_node function to override items
I've been stuck on getting a custom preprocess\_node function to work in a Drupal 6 install. I can get it to echo out things based on values but I just can't seem to get overrides working. The latest thing I've tried is the answer described in the answer on this page. If I do:

```
$node->title = "Test";

```

and do a print\_r on the $node I can see that it is overridden in the array with the new value but the title that's being output is still the old one. I've also tried setting $variables\[title\] but no luck. I'm actually trying to target something deeper than the title but thought I'd start with this. Here's an example I've tried putting in the template.php file. I've replaced my actual theme name with mythemename.

```
function mythemename_preprocess_node(&$variables) {

//Profiles
if($variables['type'] == "child_profile"){

    $node = $variables['node'];

        $node->title = "Test";
        //This echo correctly shows the new title but it's not actually overriding anything
        echo $node->title;

    $variables['node']=$node;
}}

```

# Answer
> 3 votes
If you look at node.tpl.php, the title is being printed like this:

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

```

As you can see that's using the `$title` variable, not `$node->title`.

There's a one-to-one mapping between the array keys of the template's variables, and names of variables available in the template file. If you have `$variables['my_awesome_var']` in the preprocess function, that variable will be available as `$my_awesome_var` in the template file.

So with that in mind, all you should need to do in your preprocess function is this:

```
function mythemename_preprocess_node(&$variables) {
  //Profiles
  if ($variables['type'] == "child_profile") {
    $variables['title'] = 'Test';
  }
}

```

To complete the thought - you could also change the node template to `print $node->title` instead, and your current code would work fine. But since the original template file uses a separate `$title` variable, it would be better to stick to convention and use that method.

---
Tags: 6, theming
---


# Question
Title: Using ajax to filter drupal autocomplete form
I'm trying to build a custom search form, and I want to limit the scope of the search with a dropdown select menu, ie. choose "jewelry" in the dropdown menu and the autocomplete form will only return matches of that category.

Here's what I have so far:

```
function mymodule_search_menu() {
$items['mymodule_search-autocomplete-test'] = array(
'title' => 'Test autocomplete',
'page callback' => 'drupal_get_form',
'page arguments' => array('category'),
'access arguments' => array('view published content'),
'type' => MENU_NORMAL_ITEM,
);

$items['mymodule_search-autocomplete-engine'] = array(
 'page callback' => 'mymodule_search_autocomplete',
 'access arguments' => array('view published content'),
 'type' => MENU_CALLBACK,
);
 return $items;
 }

function mymodule_search_form($form, &$form_state) {
$form = array();

$form['category'] = array(
    '#type' => 'select',
    '#title' => 'First Dropdown',
    '#options' => array('All','Product'),
    '#ajax' => array(
    'callback' => 'mymodule_search_ajax_callback',
    'wrapper' => ???,
    'method' => ???,
    ),
);

$form['search_autocomplete'] = array(
'#title' => t('Search'),
'#type' => 'textfield',
'#maxlength' => 60,
'#autocomplete_path' => 'mymodule_search-autocomplete-engine',
'#prefix' => '<div id="searchform">',
'#suffix' => '</div>',
 );

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Søg alt',
 );

 return $form;
 }

function mymodule_search_autocomplete($text) {
$results = array();
//query products
$query_products = db_select('commerce_product', 'p');
$query_products
->condition('p.title', '%' . db_like($text) . '%', 'LIKE')
->fields('p', array('title'))
->orderBy('title', 'ASC');
$res = $query_products->execute();
while ($res1 = $res->fetchAssoc()) {
  $matches[1][$res1['title']] .= check_plain($res1['title']);
}

array_unshift($matches[1], "PRODUCTS");

//query content
$query_content = db_select('node', 'n');
$query_content
->condition('n.title', '%' . db_like($text) . '%', 'LIKE')
->fields('n', array('title'))
->orderBy('title', 'ASC');
$res = $query_content->execute();
while ($res2 = $res->fetchAssoc()) {
  $matches[2][$res2['title']] = check_plain($res2['title']);
}

array_unshift($matches[2], "CONTENT");

$matches = mymodule_search_flatten($matches);
$newmatches = array();
foreach ($matches as $match){
$newmatches[$match] = $match;
}

drupal_json_output($newmatches);
}

function mymodule_search_ajax_callback($form, $form_state) {
  ???
}

```

As you might see, I have 2 different querys in my autocomplete function, and (I think) I would like to limit the result to only the selecteded querys with help of an ajax call from the dropdown category.

Oh, and don't mind all the "unshifting" and looping that goes on in the autocomplete function - I have to have category headers in my result, and this was the only way I could think of to do that.

If there's a better way to do this, or if you know how to accomplish this, please let me know.

Thanks!!

# Answer
> 1 votes
I know it's too late but for others who might find this questions, the answers are here:

form auto complete how to restrict results by previous drop down

and

Dynamic select list in the form (dependent dropdown)

---
Tags: forms, ajax
---


# Question
Title: AJAX autocomplete based on other field value
I'm trying to implement an auto complete form with a little twist. I want its auto complete options to be limited by another field (text field to be more specific).

I understand how AJAX API works and should able to create an auto complete filter for a field based on it's own values but I have no idea how to create a an a auto complete filter based on another field in the form.

From what I have found only this question is similar to my problem, it is unfortunately unanswered. I don't want the code, just hint where to look would be useful.

BTW: I have came up with a solution but it's unbelievably dirty hack that requires going into database twice. I could implement AJAX callback for the field I want the filter to be based on, store the value of the field in the callback to custom database table and then in the callback of the field I want to filter get the value and make it work.

BTW2: The field I want to base the filter on will be text field, the other one custom entityreference.

BTW3: I'm almost sure it is possible somehow since the entityreference option limit module does something like that. (It does it with a help of one other field which I don't want (And I didn't understand it at all even though I tried anyway :) ))

# Answer
> 2 votes
Great job on the research ... here's a solution I came up with. The Drupal Form API and Ajax API should be able to do this but I stopped after I got abit confused too some time ago -- I wrote a fallback using jQuery (which comes bundled with Drupal).

In a custom module .info file I add my javascript:

```
scripts[] = eap_student_feedback2_ajax.js

```

You could add this via a form\_alter() call instead and using #attached FAPI key.

Then in my javascript file I have dependant dropdowns. You have to select a Country before you select a Program available in that country. When you select a Country, those countries Program list is fetched via Ajax and inserted into that HTML select list -- the widget is then made available. The jQuery code is as follows:

```
jQuery(function($) {

  $('#edit-field-survey-program-und option:gt(0)').remove();
  $('#edit-field-survey-program-und').attr('disabled', 'disabled');

  $("#edit-field-survey-country-und").click(function() {
    var selected_country = $("#edit-field-survey-country-und").val();
    if (selected_country != '_none') {
      $.ajax({
        type:'GET',
        url: '/eap-ajax/eap-country-programs/' + selected_country,
        data: '',
          success:function(data){
          //console.log("got: ");
          //console.log(data);
          // Do actual work.
          $('#edit-field-survey-program-und option:gt(0)').remove();
          $.each(data, function(key, value) {
            $('#edit-field-survey-program-und').append(
              '<option value="' + key + '">' + value + '</option>'
            );
          });
          $('#edit-field-survey-program-und').removeAttr('disabled');
        }
      });
    }
  });
});

```

In my module file I implement hook\_menu to supply the ajax endpoint:

```
// Make a frigging ajax callback.
function eap_student_feedback2_menu() {
  $items['eap-ajax/eap-country-programs/%'] = array(
    'page callback' => '_eap_student_feedback2_programs_json_endpoint',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
  );
  return $items;
}

```

And also implement the logic to return some JSON for jQuery:

```
function _eap_student_feedback2_programs_json_endpoint($country_term_id) {
  $matches = array();
  $result = db_query('
      SELECT tth.tid, ttd.name AS term_name
      FROM taxonomy_term_hierarchy tth
      LEFT JOIN taxonomy_term_data ttd ON tth.tid = ttd.tid
      WHERE tth.parent = :tid
      ORDER BY 2 ASC
  ', array(':tid' => $country_term_id));
  // add matches to $matches
  foreach ($result as $row) {
    $matches[$row->tid] = check_plain($row->term_name);
  }
  // return for JS
  return drupal_json_output($matches);
}

```

# Answer
> 2 votes
I know it's a bit amateur but the question has already been answered I just didn't find it.

It's here:

form auto complete how to restrict results by previous drop down

and here:

Using ajax to filter drupal autocomplete form

BTW: I would delete the question but since I didn't find the answered questions myself I thought that this one might be more discoverable.

//I can't accept my own answer now, sory for that.

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


title: Download file after login

text:
# Question
Title: Download file after login
I'm looking for direction with regards to how to get a file to download only after you are logged in, and to be prompted to login if you try to download it and then upon a correct submission, have that file automatically download. The login form is to be presented in a modal dialog upon clicking the file when logged out.

Right now I have the modal form displaying when clicking the file download link, but I essentially need to reconstruct the login mechanism to work via AJAX I believe. This includes validations and establishing the user's logged in session. I'm not sure how to go about it... thoughts from the Drupal Answers community?

# Answer
> 1 votes
Private files download permission

> Version 1.x provided "two useful features which Drupal itself is missing: a simple permission to allow downloading of private files by role, plus the ability to combine both public and private downloads".
>
> Version 2.x removes the "global" permission and implements a per-directory by-user and by-role filter instead, to let the administrator better tweak the whole website and increment the overall security.

with this module you can achieve your requirement by following this tutorial source

Hope it helps you!

---
Tags: 7, ajax, users, files
---


# Question
Title: Show available languages, but remove "Language Undefined"
I want to show the available languages, that works, but how can I hide the "Language: undefined" text if "language neutral" is selected.

Thx, Andi

# Answer
> 0 votes
I know I'm not answering the question directly, but you can disabled 'Language Neutral' (and other languages) on a per-content type basis using Disable "Language neutral".

---
Tags: i18n-l10n
---


title: How to render set of Form API elements?

text:
# Question
Title: How to render set of Form API elements?
I have an array like the following.

```
$form["something"]["something"] = array(
  0 => array( "#markup" => "line 0" ),
  1 => array( "#markup" => "line 1" ),
  2 => array( "#markup" => "line 2" ),
);

```

When rendering it in the theme function with `drupal_render($form["something"]["something"])`, I get only the first line.

> line 0

When I try to use `foreach`, this somehow does not return anything.

So what am I doing wrong? Should I modify an array itself and add some wrapper element? I would prefer to render it all with one line, without `foreach`.

# Answer
> 6 votes
Instead of `drupal_render()`, you should use drupal\_render\_children().

```
print drupal_render_children($form["something"]["something"]);

```

---
Tags: theming, forms
---


# Question
Title: What are the equivalent functions that I should use for HTTP handling?
Looking at the functions listed in the HTTP handling page for Drupal 7, I noticed that the following functions don't exist anymore in Drupal 8. (The links are for the Drupal 7 documentation pages, where the links to the Drupal 8 documentation for those functions are missing.)

What functions/methods should I instead use in Drupal 8?

# Answer
These are the functions/methods/classes that should be used in Drupal 8.6.x code.

* `drupal_access_denied()` has been replaced from the AccessDeniedHttpException class. Page callbacks that need to return the Access Denied error should used code similar to the following one.

```
// system_batch_page()
public function batchPage(Request $request) {
  require_once $this->root . '/core/includes/batch.inc';
  $output = _batch_page($request);
  if ($output === FALSE) {
    throw new AccessDeniedHttpException();
  }
  elseif ($output instanceof Response) {
    return $output;
  }
  elseif (isset($output)) {
    $title = isset($output['#title']) ? $output['#title'] : NULL;
    $page = [
      '#type' => 'page',
      '#title' => $title,
      '#show_messages' => FALSE,
      'content' => $output,
    ];

    // Also inject title as a page header (if available).
    if ($title) {
      $page['header'] = [
        '#type' => 'page_title',
        '#title' => $title,
      ];
    }
    return $page;
  }
}

```
* Instead of `drupal_get_query_array()` there is `parse_query()` (a function in the `GuzzleHttp\Psr7` namespace), which is part of Guzzle.
* `drupal_goto()` has been replaced from the `RedirectResponse` class. Page callbacks that need to redirect users should use code similar to the following one. (Notice that form submission handlers should not use this class.)

```
// AddSectionController::build()
public function build(SectionStorageInterface $section_storage, $delta, $plugin_id) {
  $section_storage
    ->insertSection($delta, new Section($plugin_id));
  $this->layoutTempstoreRepository
    ->set($section_storage);
  if ($this->isAjax()) {
    return $this->rebuildAndClose($section_storage);
  }
  else {
    $url = $section_storage->getLayoutBuilderUrl();
    return new RedirectResponse($url->setAbsolute()->toString());
  }
}

```
* `drupal_http_request()` has been replaced from a Drupal 8 service that implements the ClientInterface interface. Drupal 8 code should be similar to the following one.

```
// system_retrieve_file()
try {
  $data = (string) \Drupal::httpClient()->get($url)->getBody();
  $local = $managed ? file_save_data($data, $path, $replace) : file_unmanaged_save_data($data, $path, $replace);
} catch (RequestException $exception) {
  \Drupal::messenger()->addError(t('Failed to fetch file due to error "%error"', ['%error' => $exception->getMessage()]));
  return FALSE;
}

```
* `drupal_not_found()` has been replaced from the NotFoundHttpException class. Page callbacks should use code similar to the following one.

```
// BookController::bookExport()
public function bookExport($type, NodeInterface $node) {
  $method = 'bookExport' . Container::camelize($type);

  // @todo Convert the custom export functionality to serializer.
  if (!method_exists($this->bookExport, $method)) {
    $this->messenger()->addStatus(t('Unknown export format.'));
    throw new NotFoundHttpException();
  }
  $exported_book = $this->bookExport->{$method}($node);
  return new Response($this->renderer->renderRoot($exported_book));
}

```
* `drupal_site_offline()` should be replaced by an event subscriber, similar to the following one.

```
public static function getSubscribedEvents() {
  $events[KernelEvents::REQUEST][] = ['onKernelRequestMaintenance', 30];
  $events[KernelEvents::EXCEPTION][] = ['onKernelRequestMaintenance'];
  return $events;
}

public function onKernelRequestMaintenance(GetResponseEvent $event) {
  $request = $event->getRequest();
  $route_match = RouteMatch::createFromRequest($request);
  if ($this->maintenanceMode->applies($route_match)) {
    // Don't cache maintenance mode pages.
    \Drupal::service('page_cache_kill_switch')->trigger();
    if (!$this->maintenanceMode->exempt($this->account)) {
      // Deliver the 503 page if the site is in maintenance mode and the
      // logged in user is not allowed to bypass it.
      // If the request format is not 'html' then show default maintenance
      // mode page else show a text/plain page with maintenance message.
      if ($request->getRequestFormat() !== 'html') {
        $response = new Response($this->getSiteMaintenanceMessage(), %03, ['Content-Type' => 'text/plain']);
        $event->setResponse($response);
        return;
      }
      drupal_maintenance_theme();
      $response = $this->bareHtmlPageRenderer->renderBarePage([          '#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page');
      $response->setStatusCode(503);
      $event->setResponse($response);
    }
    else {
      // Display a message if the logged in user has access to the site in
      // maintenance mode. However, suppress it on the maintenance mode
      // settings page.
      if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
        if ($this->account->hasPermission('administer site configuration')) {
          $this->messenger->addMessage($this
      ->t('Operating in maintenance mode. <a href=":url">Go online.</a>', [':url' => $this->urlGenerator->generate('system.site_maintenance_mode')]), 'status', FALSE);
        }
        else {
          $this->messenger->addMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
        }
      }
    }
  }
}

```

+ `drupal_encode_path()` has been replaced by `UrlHelper::encodePath()`
    + `drupal_get_query_parameters()` has been replaced by `UrlHelper::filterQueryParameters()`
    + `drupal_http_build_query()` has been replaced by `UrlHelper::buildQuery()`, which will be removed once Drupal core requires at least PHP 5.4 (At that point, it will be possible to directly use `http_build_query()`.)
    + `drupal_parse_url()` has been replaced by `UrlHelper::parse()`

Notice that, compared with earlier Drupal versions, there are some important changes. For example, some methods that were in the `Url` class has been moved in the `UrlHelper` class; some of the Guzzle classes aren't used anymore.
> 16 votes

---
Tags: 8
---


# Question
Title: What modules do I need to add tokens in my content that references the current nodes field?
I have a blog content type and I also have a taxonomy reference field for "color". How do I embed the field's color value in the body of my blog post via a token?

# Answer
You'll need...

* Entity API for its extended entity/field token support
* Token filter which provides a simple filter that supports tokens

And probably nothing else :)
> 0 votes

---
Tags: 7, tokens
---


# Question
Title: Remove password reset fields on user profile
Since we're only permitting logging in via the Drupal Admin and LDAP.

How might I turn off or hide these fields in the User's Edit Account (`user/xx/edit`) tab?

# Answer
To hide the password fields on the user edit form, put this code in your custom module, which implements hook\_form\_FORM\_ID\_alter():

```
function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  hide($form['account']['pass']);
}

```

You may also want to prevent users from going to `user/password` page and change their passwords on that page:

```
function YOURMODULE_menu_alter(&$items) {
  $items['user/password']['access callback'] = 'user_access';
  $items['user/password']['access arguments'] = array('administer users');
}

```

One more hint, if you want to remove the links on the user login block:

```
function YOURMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['links'] = '';
}

```
> 4 votes

---
Tags: users, authentication-authorization
---


# Question
Title: How to restrict node access to nodes based on field value?
Im making simple private message system (no need privatemsg), just node with title, body, and user reference field (entity\_reference) for recipient(s). How can I restrict access to node only for node author, and users listed in field?

# Answer
I think the Node Access User Reference module will do exactly what you want. It allows you to restrict access to a node based upon a user reference field in that node. It even comes in Drupal 6 and 7 flavors.

From what I can tell though, you want to make sure you use only one node access module for your system, so you may want to look at the Node Access Module Overview to make sure this is the best bet.
> 3 votes

# Answer
However, if you need this to work with OG, you might have some issues. I wanted to do the same exact thing, and following this guidance, http://www.phase2technology.com/blog/drupal-7-node-access-grants-locks-and-keys/ , decided to use hook\_node\_access\_records() and hook\_node\_grants().

I have a field, field\_draft, that is a boolean. If it is on, then access is restricted to just group users who have 'view draft content' role in their group. Furthermore, they can only see the node with this field if it is in the group that they have the permission in.

First, since I want to use permissions on the group level, I use hook\_og\_permissions to duplicate my site-wide permissions in OG:

```
 /**
  * Implements hook_og_permission().
  */
 function example_og_permission() {
   $permissions = array();
   foreach (example_permission() as $name => $details) {
    $permissions[$name] = array(
      'title' => $details['title'],
      'description' => isset($details['description']) ? $details['description'] : '',
      'default role' => array(OG_ADMINISTRATOR_ROLE),
    );
  }
  return $permissions;
}

```

Next, I use og\_user\_access() to assign the grant to users who have the access draft content permission in their group(s):

```
function example_node_grants($account, $op) {

    // Check OG
    // We check permissions to access the node, for all the groups the user is a
    // member.
    foreach (og_get_entity_groups() as $group_type => $gids) {
      foreach ($gids as $gid) {
        if ($op == 'view' && og_user_access($group_type, $gid, 'access draft content', $account)) {
            $grants['example_draft_view_'.$gid] = array(EXAMPLE_GRANT_ALL);
        }
      }
    }

    return $grants;
}

```

Finally, I create the grant records. Note that since the field, field\_draft, is a custom field, I need to make sure it exists in the node BEFORE I test if it is on or off.

```
function example_node_access_records($node) {

    // We only care about the node if it's been marked draft. If not, it is
    // treated just like any other node and we completely ignore it.
    if (array_key_exists('field_draft', $node)) { // check to see if field_draft exists in this node
        if (array_key_exists('und', $node->field_draft)) { // I guess needed to do this for those nodes with empty values
            if ($node->field_draft['und'][0]['value'] == 1) {

        // Create grants for OG
        foreach (og_get_entity_groups() as $group_type => $gids) {
          foreach ($gids as $gid) {
            $grants[] = array(
                'realm' => 'example_draft_view_'.$gid,
                'gid' => EXAMPLE_GRANT_ALL,
                'grant_view' => 1,
                'grant_update' => 0,
                'grant_delete' => 0,
                'priority' => 0,
            );
          }
        }
      }
   }

        return $grants;
    }
    // Return nothing if the node has not been marked draft.
}

```

And, voila, I now have an architecture which gives group users access to group "draft" content based upon group roles.
> 1 votes

---
Tags: users
---


title: How to create a form on a new page?

text:
# Question
Title: How to create a form on a new page?
I'm new to Drupal. What I'd like to do is create a form on a new page, having full control over the css/html of the form, and post the form to PHP for processing. The PHP should do some custom things to the form data, dump some stuff to the DB, return some stuff from the DB, and either redirect to a new page or return an error. No need to go into details about the PHP/DB stuff - just need to figure out how to go about creating a new page, and where to post the form to for processing. Should be able to figure everything else out from there!

# Answer
To create a form on a page you need to use Drupal's Form API. It seems a bit complex at the first sight, but it isn't as it seems.

The steps you need to follow:

1. Create a custom module
2. Implement hook\_menu() in your module and set a path for your page which should render the form.
3. A form builder function that builds a form using the Form API.

An Example for hook\_menu() implementation:

```
function YOURMODULE_menu() {
  $items['some/path'] = array(
    'title' => 'My page title',
    'description' => 'An example page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_example_form'),
  );
  return $items;
}

```

This code registers a paths as http://example.com/some/path and calls drupal\_get\_form() function, which gets a form with the given id, which in this example is `YOURMODULE_example_form`.

An example for the form builder function:

```
function YOURMODULE_example_form($form, &$form_state) {
  $form['some_text_field'] = array(
    '#title' => t('Enter some text'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

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

  return $form;
}

```
> 1 votes

---
Tags: forms, nodes
---


title: hook_menu path with multiple wildcards

text:
# Question
Title: hook_menu path with multiple wildcards
I have an administration system setup in a custom module that controls groups of items and specific items. The item groups can be added, edited, or removed and each item groups associated items can also be added, edited, or removed.

The current path structure is like this:

```
$items['admin/config/esc_shared/esc_shared_lists'] = array(
    'title' => 'Shared Lists',
    'description' => 'View current set of options.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_view_groups_form'),
    'access arguments' => array('manage list options'),
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/settings'] = array(
    'title' => 'Settings',
    'description' => 'Manage shared list options.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_settings'),
    'access arguments' => array('administer shared lists'),
    'file' => 'includes/esc_shared_lists.admin.inc',
    'weight' => 0,
);
$items['admin/config/esc_shared/esc_shared_lists/manage'] = array(
    'title' => 'Manage',
    'description' => 'Manage list options.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_view_groups_form'),
    'access arguments' => array('manage list options'),
    'file' => 'includes/esc_shared_lists.manage.inc',
    'weight' => 1,
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/add'] = array(
    'title' => 'Add group',
    'description' => 'Add a list option group.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_group_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'includes/esc_shared_lists.manage.inc',
    'weight' => 2,
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/edit'] = array(
    'title' => 'Edit group',
    'description' => 'Edit a list option group.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_group_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/remove'] = array(
    'title' => 'Remove group',
    'description' => 'Remove a list option group.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_group_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/options'] = array(
    'title' => 'List options',
    'description' => 'View list options for a specific list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_view_options_form'),
    'access arguments' => array('manage list options'),
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/options/add'] = array(
    'title' => 'Add option',
    'description' => 'Add list options to a specific list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_options_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/options/%/edit'] = array(
    'title' => 'Edit option',
    'description' => 'Edit list option for a specific list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_options_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/esc_shared_lists.manage.inc',
);
$items['admin/config/esc_shared/esc_shared_lists/manage/group/%/options/%/remove'] = array(
    'title' => 'Remove option',
    'description' => 'Remove list option from a specific list.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('esc_shared_lists_admin_manage_options_form'),
    'access arguments' => array('manage list options'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/esc_shared_lists.manage.inc',
);

```

There are other menu tree items but for brevity's sake I'm only pasting the relevant branches.

The issue I'm having is that everything works as expected up to and including getting a list of items from a group. From there if you try to edit or remove an item it just ignores the second /% and /edit.

I've done this before but slightly different. The difference being that it was a structure like:

```
admin/config/modulename/grouptype/%/itemtype/%/edit

```

If I change my paths to remove /manage from them it works as expected.

```
admin/config/esc_shared/esc_shared_lists/manage/group/%/options/%/edit // does not work
admin/config/esc_shared/esc_shared_lists/group/%/options/%/edit // works

```

What I want to know is why that would make any difference. I should be able to put any number of arguments in a path mixed with wildcards and it should behave the way one would expect.

It would almost make sense if it was defaulting all paths containing admin/config/esc\_shared/esc\_shared\_lists/manage to that page. But instead it only screws up after the first wildcard.

Is this some kind of bug?

# Answer
> 4 votes
It's not a bug, but it's probably not obvious why that doesn't work - the number of menu parts is limited to 9, by the `MENU_MAX_PARTS` constant:

> The maximum number of path elements for a menu callback

Your first path has 10 parts so won't be parsed properly by the various functions in menu.inc (`menu_get_item()` notably).

---
Tags: 7, routes
---


title: Drupal blocks not showing up

text:
# Question
Title: Drupal blocks not showing up
I am editing a site someone else built for my small nonprofit organization, and as you will see, I know very little about working with drupal (or anything beyond basic HTML, really.) I apologize in advance for that and will be so appreciative if anyone can help me.

I am trying to fix a problem. I am trying to add a listed page to a block, and the block is now not showing up on any pages it was previously associated with. When I went into a different block and tried to add a page, that block also stopped showing up. (You can see an example here: http://africaid.com/upcomingevents -- the left hand side block has disappeared.)

I am wondering if the problem is related to two warning messages. The first, on the "Administer" home page, says "One or more problems were detected with your Drupal installation. Check the status report for more information."

When I go to list content, I get the following message:

```
strict warning: Non-static method view::load() should not be called statically in /home/africaid/public_html/sites/all/modules/views/views.module on line 843.
strict warning: Declaration of views_plugin_display::options_validate() should be compatible with views_plugin::options_validate(&$form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/plugins/views_plugin_display.inc on line 1877.
strict warning: Declaration of views_plugin_display_page::options_submit() should be compatible with views_plugin_display::options_submit(&$form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/plugins/views_plugin_display_page.inc on line 481.
strict warning: Declaration of views_handler_field_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_field.inc on line 641.
strict warning: Declaration of views_handler_field_user::init() should be compatible with views_handler_field::init(&$view, $options) in /home/africaid/public_html/sites/all/modules/views/modules/user/views_handler_field_user.inc on line 48.
strict warning: Declaration of views_handler_sort_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_sort.inc on line 82.
strict warning: Declaration of views_handler_filter::options_validate() should be compatible with views_handler::options_validate($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 585.
strict warning: Declaration of views_handler_filter::options_submit() should be compatible with views_handler::options_submit($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 585.
strict warning: Declaration of views_handler_filter_broken::ui_name() should be compatible with views_handler::ui_name($short = false) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter.inc on line 609.
strict warning: Declaration of views_handler_filter_boolean_operator::value_validate() should be compatible with views_handler_filter::value_validate($form, &$form_state) in /home/africaid/public_html/sites/all/modules/views/handlers/views_handler_filter_boolean_operator.inc on line 128.
strict warning: Declaration of views_bulk_operations_plugin_style::options() should be compatible with views_object::options() in /home/africaid/public_html/sites/all/modules/views_bulk_operations/views_bulk_operations_plugin_style.inc on line 280.

```

If anybody can help me with this, I will be grateful for eternity.

Thank you, Ashley

# Answer
> 2 votes
I'm making a few assumptions, the main one being that you're using Drupal 6...

Basically your PHP error reporting settings include `E_STRICT` compliance, and the code in the version of Views you've got installed isn't compatible with it. D6, and subsequently the associated version of Views, was written for PHP4 and PHP5, and as such isn't compatible with `E_STRICT`.

You can either

* Disable `E_STRICT` error reporting in your php.ini/other php conf file (if you're not sure how to do this, get whoever administers your server to do it - it'll make sense to them). Or
* Apply the patch in this issue (comment #11) which will remove the problems for PHP5.3. If you have PHP5.4 installed, there's another patch in #26 to apply too.

---
Tags: blocks
---


# Question
Title: Webform Module can't send email from user anonymous
I'm using Drupal 7 and Webform Module for create contacts forms (This problem also what I have in Pressflow 6).

Only authenticated users can send mail through the form. However, I need that anonymous users can also use the form.

The error is as follows:

```
Error sending e-mail from sender@email.com to target@mail.edu.pe: SMTP Error: Data not accepted.
SMTP server error: 5.7.1 Sender domain not allowed.

```

How I can make the form send mail with both roles (authenticated and anonymous)? How I can avoid spam for users anonymous?

## Details

Each time you use the contact form (either anonymous or authenticated) to send an email to the person responsible of receiving these emails.

# Answer
Anonymous users can absolutely submit webforms. On the Form Settings page under submission access, there are permission checkboxes for each role. You can use Captcha or Mollom to help prevent spam submissions.

The error you're having seems like you have SMTP misconfigured. Are you currently using the SMTP module? If so, run a test to send an email to yourself. If that fails, then it's definitely the problem.
> 1 votes

---
Tags: 7, webforms, emails
---


title: Add a hidden field on form submit

text:
# Question
Title: Add a hidden field on form submit
I am working on a login form (information sent via https to a remote system), that by default contains a username field, a password field and a static hidden field (necessary in order to validate with the remote system).

There is one additional hidden field necessary, which should be built from the value of the username and the value of the existing hidden validation field, separated by an underscore, like this: username\_hidden\_id

Is it possible to achieve that after the form has been submitted? I tried to add the field using the form submit function, but that doesn't seem to work.

I could add this the mentioned field and generate it's value via JavaScript/jQuery, but I wouldn't like to have this field visible/public.

I have the following code:

```
function custom_login_form($form, $form_state) {

    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => t('Username'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#size' => 15,
      '#required' => TRUE,
    );
    $form['password'] = array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#size' => 15,
      '#required' => TRUE,
    );
    // Hidden validation field
    $form['hidden_id'] = array(
      '#type' => 'hidden',
      '#value' => '1234',
    );
    // Submit button
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Log in'),
    );

    return $form;
}

function custom_login_form_validate(&$form, &$form_state) {

  if (empty($form_state['values']['username'])) {
    form_set_error('username', 'Please enter a username.');
    $form_state['rebuild'] = TRUE;
  }
  if (empty($form_state['values']['password'])) {
    form_set_error('password', 'Please enter a password.');
    $form_state['rebuild'] = TRUE;
  }

}

function custom_login_form_submit(&$form, &$form_state) {

  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $form['username_hidden_id'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'],
    );
  }

}

```

# Answer
You don't want to modify the `$form` array in the `_submit` function. Rather, you should modify the `$form_state['values']` array, as that's where all submitted values are stored. So:

```
function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $form_state['values']['username_hidden_id'] = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
}

```

Note that you can also do all of the above in the `_validate` function, and `$form_state['values']['username_hidden_id']` will then be available in the `_submit` function.

Why do you need it to act like a submitted field, though? I would just save it as a variable and use it as needed, like so:

```
function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $username_hidden_id = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
  // Do something with $username_hidden_id here.
}

```
> 1 votes

---
Tags: forms
---


title: Adding custom actions to rules

text:
# Question
Title: Adding custom actions to rules
I am trying to add custom actions, events and conditions to work with Rules interface. I began by adding custom actions by creating a custom module. Here's my code till now.

**rules\_example.info :**

```
name = Rules Example
description = Test module to add new actions, events, and conditions
core = 7.x

```

**rules\_example.module :**

```
<?php
/**
 */

```

**rules\_example.rules.inc :**

```
<?php

 /**
  * @file
  * Example rules module to create actions, events, and conditions
  */

/**
 * Implement hook_rules_action_info()

 * Declare any meta data about actions for Rules
 */

function rules_example_rules_action_info() {
$actions = array(
    'rules_example_actions_hello_world' => array(
        'label' => t('Print Hello World on the page'),
        'group' => t('Rules Example'),
        ),
    'rules_example_actions_hello_user' => array(
        'label' => t('Print Hello to the logged in user'),
        'group' => t('Rules Example'),
        'parameter' => array(
            'account' => array(
                'type' => 'user',
                'label' => t('User to say hello to'),
                ),
            ),
        ),
    );

return $actions;
}

/**
 * The action function for rules_example_action_hello_world
 */

function rules_example_action_hello_world() {
drupal_set_message(t('Hello World'));
}

/**
 * The action function for rules_example_action_hello_user
 */

function rules_example_action_hello_user($account) {
drupal_set_message(t('Hello @username',
 array('@username' => $account->name)));
}

```

Well, this is it. I have saved all these files in a folder rules\_example in sites/all/modules. When i install the module or rather try to install it i get this error:

**`ReflectionException: Function rules_example_actions_hello_world() does not exist in ReflectionFunction->__construct() (line 1691 of /opt/lampp/htdocs/sites/all/modules/rules/includes/rules.core.inc)`**

I am not sure what the error is. I am going to rules.core.inc but am not able to understand what is causing the error. Thanks.

# Answer
> 9 votes
There is a typo in your code - the function name is "rules\_example\_actions\_hello\_world" in your actions definition, while the actual function is called "rules\_example\_action\_hello\_world".

# Answer
> 1 votes
In rules\_example.module, add this:

`module_load_include('inc', 'rules_example', 'rules_example.rules');`

---
Tags: 7, users
---


# Question
Title: Best way to create a Facebook Follow button on nodes
I have some nodes with information about a political candidate. Some of the candidates have a Facebook profile, which I link to using an URL-field.

But they also want a follow button directly on the page. I was thinking of typing in their handle to a text field and create a field formatter to render the code for the actual button.

Is this the best way to do it?

# Answer
> 0 votes
Facebook Subscribe Button

> This module will automatically add the Facebook code for Facebook Subscribe button which will be displayed in the block and each page node.

> * Administrators can also control which content type(s) the Facebook Subscribe button will or won't appear on, as well as which role(s) are allowed to view the button (regardless of whether or not the user is logged into Facebook at the time).
> * Along with a Subscribe button appearing for each node, there is an optional block that can be set to appear on each page.
> * By default, the button will only appear on a node's "full" page view. This option is also customizable, however, so that the button(s) will show up on teasers as well.

---
Tags: social-network
---


# Question
Title: services userpoints with xmlrpc server can't be linked by external device?
I had searched the article, and i still can't figure out how to use services userpoints with xmlrpc.(My Environment drupal 7,Service 3.x, userpoints )

i read the readme in the userpoints module.

```
$result = xmlrpc($server_url, 'userpoints.points', $key, $uid, $points, $tid, $event, $description);

```

i wrote this code in the other sites,and tried to add/subtract the points.It doesn't work.

I tried function xmlrpc() in drupal API and follow the api rules, it doesn't work either. drupal api function: xmlrpc($url, $args, $options = array())

the code i wrote:

```
$key='1234';// casually set
$uid=1;
$points=1;
$tid=18;
$event='event testing';
$description='description testing';
$result = xmlrpc('http://my.domain/userpoints-api/', array(
  'userpoints.points' => array($key, $uid,$points,$tid,$event,$description),
));
dpm($result);

```

$result is nothing. Does anybody have the experience on this? Thank you guys. Please help me.

i check the access.log i got the message belowed

```
210.65.11.209 - - [23/Aug/2013:15:49:50 +0800] "POST /userpoints-api/add HTTP/1.0" 200 767 "-" "Drupal (+drupal.org/)

```

# Answer
> 0 votes
I didn't test xmlrpc($server\_url, 'userpoints.points', $key, $uid, $points, $tid, $event, $description) is worked or not.

Instead, I use POSTMAN extension from chrome store to post data to the userpoints service api endpoints path.

1. The userpoints alias must be filled, the data here is "pointss".
2. url:http:userdomain/userpoints\_api/pointss method:POST
3. header: Content-type | application/xml
4. raw/xml

> ```
> <?xml version="1.0"?>
> <methodCall>
>    <methodName>pointss.add</methodName>
>    <params>
>      <param>
>            <name>uid</name>
>            <value><int>1</int></value>
>            <name>points</name>
>            <value><int>170</int></value>
>            <name>tid</name>
>            <value><int>18</int></value>
>            <name>operation</name>
>            <value><string>test for operation</string></value>
>            <name>description</name>
>            <value><string>test for description</string></value>
>            <name>entity_type</name>
>            <value><string>node</string></value>
>            <name>entity_id</name>
>            <value><int>1</int></value>
>      </param>
>    </params>
> </methodCall>
>
> ```

Done.

# Answer
> 0 votes
Userpoints Services support Rest Server and XmlRPC Server

i changed the code of the userpoints\_service

Now We Can use Rest Server on userpoints

```
 /**
 * Implementation of hook_services_resources().
 */
function userpoints_service_services_resources() {
  return array(
    'userpoints' => array(
      'retrieve' => array(
        'help' => 'Retrieve the amount of points a user has',
        'file' => array('file' => 'inc', 'module' => 'userpoints_service'),
        'callback' => 'userpoints_service_get',
        'access callback' => 'userpoints_service_view_access',
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'uid',
            'type' => 'int',
            'optional' => FALSE,
            'description' => 'The User ID for which the points should be loaded. Defaults to the .',
            'source' => array('path' => 0),
          ),
          array(
            'name' => 'tid',
            'type' => 'all',
            'optional' => TRUE,
            'source' => array('path' => 1),
            'description' => t('An optional Term ID for the category.'),
          ),
          array(
            'name' => 'type',
            'type' => 'string',
            'optional' => TRUE,
            'source' => array('path' => 2),
            'description' => t('The type of points, either max or current, to which it defaults.'),
          ),
        ),
      ),
      'update'=>array(
        'help' => 'Add or subtract a given amount of points for a user',
          'file' => array('file' => 'inc', 'module' => 'userpoints_service'),
          'callback' => 'userpoints_service_add',
          'access callback' => 'userpoints_admin_access',
          'access arguments' => array('add'),
          'args' => array(
            array(
              'name' => 'uid',
              'type' => 'int',
              'optional' => FALSE,
              'description' => 'A valid Drupal User ID.',
              'source' => array('path' => 0),
            ),
            array(
              'name' => 'points',
              'type' => 'int',
              'optional' => FALSE,
              'source' => array('param' => 'points'),
              'description' => 'Number of points to add/subtract.',
            ),
            array(
              'name' => 'tid',
              'type' => 'int',
              'optional' => TRUE,
              'source' => array('data' => 'tid'),
              'description' => t('An optional Term ID for the category.'),
            ),
            array(
              'name' => 'operation',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'operation'),
              'description' => t('An operation string for this transaction.'),
            ),
            array(
              'name' => 'description',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'description'),
              'description' => t('An optional description of this transaction.'),
            ),
            array(
              'name' => 'entity_type',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'entity_type'),
              'description' => t('An optional description of this transaction.'),
            ),
            array(
              'name' => 'entity_id',
              'type' => 'int',
              'optional' => TRUE,
              'source' => array('data' => 'entity_id'),
              'description' => t('An optional description of this transaction.'),
            ),
          ),
      ),
      'index' => array(
        'help' => 'Index of all users with points',
        'file' => array('file' => 'inc', 'module' => 'userpoints_service'),
        'callback' => 'userpoints_service_index',
        'access callback' => 'userpoints_service_view_access',
        'args' => array(
          array(
            'name' => 'page',
            'optional' => TRUE,
            'type' => 'int',
            'description' => 'The zero-based index of the page to get, defaults to 0.',
            'default value' => 0,
            'source' => array('param' => 'page'),
          ),
          array(
            'name' => 'tid',
            'type' => 'string',
            'optional' => TRUE,
            'source' => array('param' => 'tid'),
            'description' => t('An optional Term ID for the category.'),
          ),
          array(
            'name' => 'sort',
            'type' => 'string',
            'optional' => TRUE,
            'default value' => 'points',
            'source' => array('param' => 'sort'),
            'description' => t('Sort field'),
          ),
          array(
            'name' => 'dir',
            'type' => 'string',
            'optional' => TRUE,
            'default value' => 'DESC',
            'source' => array('param' => 'dir'),
            'description' => t('Sort direction'),
          ),
        ),
      ),
      'actions' => array(
        'add' => array(
          'help' => 'Add or subtract a given amount of points for a user',
          'file' => array('file' => 'inc', 'module' => 'userpoints_service'),
          'callback' => 'userpoints_service_add',
          'access callback' => 'userpoints_admin_access',
          'access arguments' => array('add'),
          'args' => array(
            array(
              'name' => 'uid',
              'type' => 'int',
              'optional' => FALSE,
              'description' => 'A valid Drupal User ID.',
              'source' => array('path' => 0),
            ),
            array(
              'name' => 'points',
              'type' => 'int',
              'optional' => FALSE,
              'source' => array('param' => 'points'),
              'description' => 'Number of points to add/subtract.',
            ),
            array(
              'name' => 'tid',
              'type' => 'int',
              'optional' => TRUE,
              'source' => array('data' => 'tid'),
              'description' => t('An optional Term ID for the category.'),
            ),
            array(
              'name' => 'operation',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'operation'),
              'description' => t('An operation string for this transaction.'),
            ),
            array(
              'name' => 'description',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'description'),
              'description' => t('An optional description of this transaction.'),
            ),
            array(
              'name' => 'entity_type',
              'type' => 'string',
              'optional' => TRUE,
              'source' => array('data' => 'entity_type'),
              'description' => t('An optional description of this transaction.'),
            ),
            array(
              'name' => 'entity_id',
              'type' => 'int',
              'optional' => TRUE,
              'source' => array('data' => 'entity_id'),
              'description' => t('An optional description of this transaction.'),
            ),
          ),
        ),
      ),
    ),
  );
}

```

---
Tags: services, userpoints
---


# Question
Title: Search api & solr search => no results found
Configuration: I am using Drupal 7, search api and search api solr.

Description & problem: I am trying to use search api and solr search(as a back end) to search for nodes. I have a solr server running in localhost:8983/solr/admin/. I create a solr server inside drupal configuration, then I create a node index using this server and I index the field: title. **The index runs successfully and indexes my 11 articles**.

Then i create a search page using search\_api\_page to test out the searching functionality. Result: I get "*Your search yielded no results*" when searching for a word in the title of the articles (the word exists in the titles)

I am starting to become desperate here. The index is working correctly but neither through a search page nor through a view can I access the results. It says there are none :O Any ideas?

EDIT: I can query by hand, if i go to localhost:8983/solr/select/?q=spell:test then I get all the articles with the word "test" in their title. Also a ?q= will show all the indexed articles

# Answer
> 1 votes
There is a 'solr-devel' module to help http://drupal.org/project/solr\_devel.

Make sure that the query works directly in the solr native search page. Isolate the drupal side this way.

Make sure that you have updated schema.xml and solrconfig.xml with the ones that come with the module as per the module README.txt. Reindex.

> Move apache-solr-1.4.1/example/solr/conf/schema.xml and rename it to something like schema.bak. Then move the solr-conf/solr-1.4/schema.xml that comes with this Drupal module to take its place.
>
> Similarly, move apache-solr-1.4.1/example/solr/conf/solrconfig.xml and rename it like solrconfig.bak. Then move the solr-conf/solr-1.4/solrconfig.xml that comes with this module to take its place.

# Answer
> 1 votes
I've setup Apache Solr successfully a few times, here's a look at my setup, please excuse the squiggles, I've redacted certain parts to keep client anonymity.

I'm going to assume you're using the default Solr config found in the latest Search API Solr module (derivatives of this have always worked for me).

You should have both a Server and Index setup with Apache Solr like the above, there should be the message "The Solr server could be reached" also like pictured.

Make sure you have filled all fields out correctly if Drupal is having trouble reaching the Solr server, for example if you choose https, but haven't customised the default Solr config to enable https then it will not work.

Now it's important to make sure you're indexing at least one field as 'fulltext' otherwise you can't perform any free text searches. It's usually a good idea to have Title indexed as fulltext.

I don't know how you have your Search API pages configured, but I personally like to do it via views (because views is awesome). Make a view using your Index that you created.

In the newly created view add an exposed filter of type Search: Fulltext.

There's a couple of advantages with using Views so I'd definitely recommend this way over search pages. Let me know how you get on.

---
Tags: search
---


# Question
Title: Looking for either "Date Field Popup Widget (Views Filtering)" or "Date Field Reference (with Popup widget)"
I've been looking for quite a while, but I can't seem to find a solution in Drupal 7.

Anyone know a module or a method of filtering a date field popup widget, to only allow dates to be selected based on a views filter in the node creation form?

Or a way to reference another date field (possibly via Entity reference) that allows me to still use the date popup widget?

Any help would be much appreciated. Thank you.

# Answer
Date Restrictions provides restrictions on allowed values based on several criteria. It still doesn't implement filtering by views results, but you may give it a try.
> 1 votes

---
Tags: views, entities, datetime
---


title: Closing colorbox after submit

text:
# Question
Title: Closing colorbox after submit
I'm using colorbox module to load the login form, but after submit the form the page reloaded inside the "iframe" .

what i want to close the color box "iframe" and reloading the main page.

i searched for a long time but i can't find any solution.

# Answer
Use parent.jQuery.fn.colorbox.close();

for closing colorbox, when submitting form.

like, add the onClick event inside the submit button code:

```
<input type='submit' value="Submit' onClick='parent.jQuery.fn.colorbox.close();'>

```
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: What is the difference between using hook_views_pre_render() or preprocess functions?
What is the difference in using hook\_views\_pre\_render(&$view) instead of using \[THEME\_NAME\]\_preprocess\_views\_view\_table\_\[VIEW\_NAME\] . I am just changing the '#markup' of field. hook\_views\_pre\_render() is being used in custom module and \[THEME\_NAME\]\_preprocess\_views\_view\_table\_\[VIEW\_NAME\] is used in template.php file ?

# Answer
> 6 votes
Behind the scenes they're pretty different (one is a hook provided by Views, the other part of the theme system). Practically speaking, as a module/theme developer you'll see very little difference. What you can do in one you can do in the other, and `hook_views_pre_render()` can even be implemented in a theme.

I'd say just pick the one which offers you the most intuitive/simple way to make the changes you need to. If the theme preprocess requires more complex logic/code use the pre\_render hook, and vice versa.

---
Tags: 7, views, hooks, theming
---


# Question
Title: Root term in Pathauto only works for child terms?
My taxonomy structure looks like this:

```
Film
- Short film
- Special film

```

Using Pathauto, I would like the url to always include the root term.

So for nodes tagged with 'film' the path is: *film/node-title*. For nodes tagged with 'short film' the path is also: *film/node-title*

I thought the 'root term' token would do the trick, setting pathauto pattern to: `[node:field-category:root:name]/[node:title]`

But it only works for children. If a film is tagged 'film', the token isn't used for some reason. Perhaps I am misunderstanding the meaning of 'root'?

# Answer
I encountered the same problem and wrote the patch for token module Here is patch https://drupal.org/node/2050421#comment-7806099
> 3 votes

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


# Question
Title: Can I remove Zen Default Regions if Im not using them
I want to remove regions such as 'navigation' & 'highlighted' from structure/blocks just so I can visually see what is in use, and not have a list of Blocks im not using sitting there.

# Answer
> 1 votes
You cannot remove regions that have blocks in them - at least not without consequences. If you will do so, blocks will disappear and there is a chance for Drupal and PHP errors. To get rid of unneeded regions, you need to proceed in that order:

1. Remove all blocks from them
2. Remove them from `.tpl` files, to be sure nothing will try to render region that does not exist anymore
3. Now you can delete them from `.info` file

# Answer
> 0 votes
You can remove entire regions by taking them out of your .info file for that theme. Your .info file will be located in the Zen theme folder and should be called zen.info. Open your .info file and remove the line that states:

regions\[navigation\] = Navigation bar

If you want to keep things clean and orderly, you should also remove any call to those regions in any page.tpl.php files you have. They'll look something like:

```
<?php print $header ?>

```

And you may want to make a custom theme of your own if you plan on making a bunch of modifications.

---
Tags: theming
---


title: Show only text in a form

text:
# Question
Title: Show only text in a form
I just want to show the status of an item on one AJAX call. I cannot find any form element that allows me to only output text. I don't want a textfield form, since that would allow the users to enter a value.

How do I show text only in a form created with the form API?

# Answer
> 5 votes
If you want to show only text, use `'#markup'` form element, with syntax like this:

```
$form['status'] = array(
  '#markup' => '<p>' . variable_get('status', t('Off')) . '</p>',
);

```

# Answer
> 0 votes
Why don't you use Webform ? If you want to hide something :

* Css -\> display:none
* Js -\> $('#fo').hide();
* Hack the weform module

---
Tags: forms
---


# Question
Title: How to remove Analysis button from Webform results tab
I am trying to located the template file or function that outputs the following buttonson the webform results tab

Secondary tabs

```
Submissions(active tab)
Analysis
Table
Download
Clear

```

Can anyone advise how I can tweak/remove/hide some of these

# Answer
The best way to hide menu item from the secondary tabs should be to alter the access callback of the menu item.

```
function yourmodule_menu_alter(&$item) {
  // This hides the analysis item. Others should work simillary.
  $item['node/%webform_menu/webform-results/analysis']['access callback'] = 'yourmodule_webform_result_access';
}

function yourmodule_webform_result_access($node, $account = NULL) {
  // You can put here any custom logic of your needs.
  return FALSE;
}

```
> 3 votes

---
Tags: webforms
---


title: How to display badges with username?

text:
# Question
Title: How to display badges with username?
How can i display the badges with username like stackexchange? I am using D6 and user badge and userpoints modules.

# Answer
Two modules you can try both of which integrate with user badges but will need a little more customization to get it right. Try the user\_picture\_block module:

> Create just one block with the logged on user's picture, if he/she has one. In addition, User titles, points and badges are also displayed, if there are any.

Also, there is the author\_pane module which also has built-in integration with user\_badges:
> 1 votes

---
Tags: 6, users
---


# Question
Title: How does one diplay only the referenced entities associated with specific node in a view block?
I have two content types that are related to one another with and entity reference field, Research project and Profile. In my block display view, I would like to display only the entities that are referenced by a specific Research project.

# Answer
If you use Drupal 7, you must go to: Structure \> Views \> (Choose the view you want to customize). There you will find a section "Filter Criteria" if nothing exists press add on the right and add your criteria. You select it and continue with the customization, each element has different customization.

On the bottom you usually see the result, if nothing is shown, then this does not necessarily mean that you made a mistake (I had that problem once). Don't forget to save.
> 0 votes

---
Tags: views
---


# Question
Title: How to add Login menu to the first sidebar (secondary menu)
I need to remove from the 'secondary menu' the login/logout menu from the header, and display in the first sidebar,

It doesnt seem to be as easy as just draging and dropping in blocks,

# Answer
Try turning off the secondary menu (admin/structure/menu/settings).

Then, on the blocks admin screen (admin/structure/block), place the User menu in the first sidebar.
> 0 votes

---
Tags: blocks, users
---


# Question
Title: Rules- How can I make a variable/token with the site URL minus the language path?
I have created a rule set to handle login redirects for users on my site. If a user logs in from a page that is set to a different language from that user's language (example: English user logs in on a Japanese page), the user will be redirected to a page with the same language as the page upon which they logged in (in the example, a Japanese page).

To fix this, I want to force my redirects to be the appropriate language path based on the user language.

However, the \[site:url\] replacement pattern which is provided by Rules includes the language path (because it is the front page).

My front page is https://mysite.com/en.

I want to create a new variable which is the URL of my site minus the language path: https://mysite.com/

I tried creating a variable of type *text* with a value of

```
<?php substr("[site:url]", 0, -2); ?>

```

but for some reason this just gives me the value of \[site:url\]; it appears that the substr() function has no effect. I don't understand PHP very well so I could be missing something obvious-- I just want to remove the last two characters of the \[site:url\]. How can I do this within Rules?

# Answer
> 1 votes
Use Drupal global variable $base\_root for that.

# Answer
> 0 votes
Independent from Drupal 6 and 7, `<?php url('<front>'); ?>` should give the path to the front page unless you specify a language. See url()

```
<?php
global $user;
$user->language;
?>

```

You can get the logged in user's prefered language from above snippet.

# Answer
> 0 votes
Try this:

```
<?php substr(url('<front>', array('absolute' => TRUE)), 0, -2); ?>

```

---
Tags: rules, i18n-l10n
---


# Question
Title: All pages showing "Access Denied" if not logged in
I am on MAMP, able to login and try to figure things out. (First time developing in Drupal). I am using Drupal 7, with Project Kickstart distribution. https://drupal.org/project/project\_kickstart

This is meant to be a public site in the end - any idea what I should be checking to see why anonymous user cannot view content? I checked `node_access` and there is an entry for GID 0. There is also a user 0.

# Answer
> 2 votes
When you are logged in as admin, go to /admin/people/permissions and make sure that anonymous users are given *View published content* permissions.

If you are new to Drupal, you should probably stay away from the database tables for now.

---
Tags: 7, users
---


# Question
Title: Add allowed file extensions in Views Send file field
Using the Views Send module to send mass email. On the email creation page I want to set my custom validation extensions for the file field provided by Views Send in combination with MimeMail (r# 267 in views\_send.module).

For the file field I am trying to set the only allowed extension to be of type **.docx** by using the following function:

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_form_views_send_page") {
    if ($form_state['step'] == 'views_send_config_form') {

      $form['mail']['views_send_attachments'] = array(
        '#type' => 'file',
        '#title' => t('Attachment'),
        '#upload_validators' => array(
          'file_validate_extensions' => array('docx'),
        ),
     );
  }
}

```

Unfortuanetely this is not working. What am I doing wrong here?

# Answer
> 3 votes
Turns out the file behavior you're looking for is not defined for `file` elements, but for `managed_files`. It's as easy as:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_form_send_page_alter(&$form, &$form_state) {
  if ($form_state['step'] == 'views_send_config_form') {
    $form['mail']['views_send_attachments']['#type'] = 'managed_file';
    $form['mail']['views_send_attachments']['#upload_validators']['file_validate_extensions'][] = 'docx';
  }
}

```

But views\_send will have to be patched to support managed\_files. This still needs work in the issue queue.

---

Yet, as I mention in the issue, you can hack it directly in the module. It's not recommended, but we don't have a hook here and the issue above might take a while to be solved. So just change the line

```
$file = file_save_upload('views_send_attachments', array(), $dir);

```

to

```
$file = file_save_upload('views_send_attachments', array('file_validate_extensions' => array('docx')), $dir);

```

---
Tags: files, views
---


# Question
Title: Views fields settings style settings no options avaible
In views, after I choose 'Fields' as format, I want to add HTML to the title field. The way you would normally do this is is expand the "Style settings" fieldset, then check "Customize field HTML". Only on the Drupal site in question there is nothing that expands under the checked item. I checked permissions and flushed caches but other than that I don't know how I woul be able to look at this. Could this be a javascript issue? Also checked console for that, but no errors there.

# Answer
> 2 votes
I had the same problem and found that it is caused by using jQuery 1.8, so with an older jQuery versions it should works just fine.

---
Tags: 7, views
---


# Question
Title: Omega Subthemes, Modernizr, and Javascript placement
I am embarking on a new project and have decided to use Omega as as my base theme. I have a few related questions to overriding **html.tpl.php** in my subtheme.

I normally use Modernizr for HTML5 feature detection and to provide the HTML5 Shiv functionality. Are there any problems with replacing the conditional HTML5 Shiv with always including Modernizr? Are any of the features incompatible with the Javascript that Omega provides (like the Media Queries extra)?

Second, I normally place Javascript at the bottom of the page. Will this interfere with any of the JS that Omega relies on?

# Answer
> 2 votes
I have now done a few Omega based sites, and I have some answers about these.

I have not run into any problem with moving the `print $scripts` to right before the closing `</body>` in *html.tpl.php*. That said, this question on Stack Overflow has a good discussion on why this may be an outdated advice.

I have also had good results replacing the HTML5 shiv in *html.tpl.php* with the following code.

```
<?php if ($modernizr): ?>
  <script src="<?php print $modernizr; ?>"></script>
<?php else: ?>
  <!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<?php endif; ?>

```

I also added the following code in `template_process_html()`.

```
if (theme_get_setting('mytheme_use_modernizr')) {
  $vars["modernizr"] = "/" . path_to_theme() . "/js/modernizr-2.0.6-min.js";
}

```

I then wire up a custom theme variable in *theme-settings.php*.

```
$form['mytheme'] = array(
  '#type' => 'fieldset',
  '#title' => t('mytheme settings'),
);

$form['mytheme']['mytheme_use_modernizr'] = array(
  '#type' => 'checkbox',
  '#title' => t('Use Modernizer instead of HTML5 Shiv?'),
  '#default_value' => theme_get_setting('mytheme_use_modernizr'),
);

```

# Answer
> 1 votes
You could always use the Modernizr Drupal module and I'll do all the hard work for you ;)

One minor point of automation that still need to be completed is that the module's API needs to allow for NOT args, so that themes who supply their own copy of shiv can tell the Modernizr API to avoid including it. But we're working on it!

---
Tags: javascript, theming
---


# Question
Title: Allow anonymous users to subscribe to newsletter/mailing list
My aim: Client side: Have a block in the front page to allow any user (including anonymous users) to input their names and email addresses to subscribe the newsletter. Administration Side: being able to see the mailing list and send out newsletter to these emails.

What I have got: I downloaded and enabled the follow modules: Mail System, Mime Mail, Mime Mail Action, Mime Mail CSS Compressor, Simplenews, SMTP Authentication.

I am using Drupal 7 with Bootstrap theme.

What I have done: I have added a new simplenews block in the front page only, styled a little bit. In permission section, I ticked both ANONYMOUS USER and AUTHENTICATED USER for 'Subscribe to newsletters' option.

Problems: I input my email and clicked the subscribe button in the block as a anonymous users, there is an error:

> Unable to send e-mail. Contact the site administrator if the problem persists.

Followed by a notice:

> You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.

The SMTP Authentication module doesn't work for my account because it said my php doesn't have ssl enabled, which I don't know how to do? I have enabled ssl module in my apache, but what shall I do next?

Also I then see no subscribers added when I log on as an administrator later.

Question: How can get let anonymous subscribe to mailing list and how can I create newsletter? Any instructions on how to achieve this? Am I using the wrong modules?

# Answer
> 3 votes
Sounds like your site can not send e-mails for whatever reason.

The default newsletter settings require to confirm a subscription, you can disable that in the newsletter settings, optionally also only for testing until you've figured the e-mail problem out.

Unconfirmed subscriptions aren't displayed in the UI, that's why you can't see anything.

Instructions on how to use and configure Simplenews can be found in the README.txt and the online documentation.

Note: You're asking a lot of different questions, and your actual problem (sending e-mails being broken) has nothing to do with initial question (you might not have known that, so that's ok). Remember that you're supposed to accept a (single) answer as the correct one, how can you do that if you ask multiple, different questions?

---
Tags: 7, emails, ssl
---


title: How do I group elements in a view?

text:
# Question
Title: How do I group elements in a view?
I have 8 articles: Article 1 (Gaming), Article 2 (Local News), Article 3 (World News), Article 4 (World News), Article 5 (Gaming), Article 6, Article 7, Article 8.

In a view I would like to group the articles by: "News," "Gaming," and "Other." Combining the world and local news under one category, and moving anything that doesn't have a category to "Other." I didn't want to create a new vocabulary for just this view. I tried to accomplish this using the group by field, but I can't figure out how I could accomplish this using that method.

# Answer
> 15 votes
In your content type, you can create a "list" field called, say, Category, with the categories News, Gaming and Other. You can then categorize the content that should appear in your View using that field.

In your View, under Format, choose "Settings." There should be an option to choose a Grouping Field. Select the "Content: Category" field. Your view should now show up grouped according to News, Gaming and Other.

Was that what you had in mind?

**UPDATE** The above wasn't quite what you were looking for. No problem.

You say you have articles like Article 1 (Gaming), Article 2 (Local News), Article 3 (World News), Article 4 (World News) etc. Is it right that the word in parentheses is a taxonomy term? If not, the below won't be relevant, but I'll assume for now it is.

If so and you want to 'chunk' these terms into three categories, you could certainly modify the Views query or write your own.

Alternately (which is probably easier) you could change your existing vocabulary into a hierarchical taxonomy with News as the super-category and Local News and World News as the subcategories.

So now your vocabulary looks like:

News

* Local News
* World News

Gaming

Other

If your content was already tagged with the existing categories, you shouldn't have to change anything.

You could then create a View that displays the fields you want. Add a filter "Term Name," and enter "News." Then, add an attachment display, and attach it to your current View, overriding the filter and setting it to "Gaming." Finally, add a second attachment and override the Filter, changing it to "Other." This should give you the result you want.

# Answer
> 3 votes
You can use too, Views Distinct. This module allow add relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field.

# Answer
> 2 votes
I bumped into this thread while searching for a group-by solution, either using Views or Display Suite (D7). Somehow I cannot get the group by feature g\_thom mentioned in the Format section. Should it be there in D7? is there any Views-dependent submodule that I'm missing out? Also, in Display Suite there is a group by feature, but the only option there that's displayed is one of my custom fields that I created (I don't know why this particular one, not another). Unusable in such a case.

My goal is to have Views form a block of links (linking to custom type nodes), grouped by a taxonomy term (the term should be output but not linked to anything).

PS. respect to g\_thom for his elaborate help!

---
Tags: 7, views
---


# Question
Title: Sending email notifications to all editors the content's editorial section on content state change
I am using Using Workbench for content moderation and Workbench Access for access control.

Is it possible to use the rules integration to send an email to all of those users who are in a content node's editorial access control?

The screenshot shows what I've currently got, which is sending the notification to one particular email address on state change to Needs review.

# Answer
I don't know what the "editorial access control" is but if you don't find any easier solution you can always write your own rules action for generating the list of people you need. In my case I am sending a message to the reviewers that are provided in one of the fields of the content. It should be easily adaptable to any other porpoise.

```
/**
 * Implements hook_rules_action_info().
 */
function mymodule_workflow_rules_action_info() {
  $items = array();
  $items['mymodule_workflow_reviewers'] = array(
    'label' => t('Get reviewers'),
    'group' => t('Windbench'),
    'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('Node')),

    ),
    'provides' => array(
      'reviewers' => array('type' => 'list<user>', 'label' => t('List of reviewers')),
    ),
  );
  return $items;
}
function mymodule_workflow_reviewers($node){
  $reviewers = array();
  foreach($node->field_workflow_reviewers['und'] as $reviewer){
    $reviewers[] = user_load($reviewer['uid'],true);
  }
  return array('reviewers' => $reviewers);
}

```

And then use that action in your rules
> 2 votes

# Answer
You could try this sandbox project Workbench Notify

> Workbench Notify enables to automatically notify the editors as previously specified and individually defined in the Workbench Access's menu Editorial assignments by editor or defined by their role in the Workbench Access's menu Editorial assignments by role, on a transition state set in Workbench Moderation. For the individually defined editors, notifications will be sent only to the editors (or users) whose roles are configured accordingly in the settings of Workbench Notify.
>
> Workbench Notify works with a taxonomy or menu scheme set for Workbench Access.

Or use the snippet PHP you can find in this blog post Workbench Access et Rules - Notifier les modérateurs d'une nouvelle contribution
> 0 votes

# Answer
There's an Action "Send mail to all users of a role". Provided you have a role specifically for editorial control, that may solve this in a simple manner.

If you have a more complex review workflow (eg only a Senior Reviewer from the author's specific regional office may review their input) then you need custom code like that in Pawel's answer.
> 0 votes

---
Tags: rules, workflows, workbench
---