# Question
Title: Accordion Menu - Where is the original CSS file of the module?
I tried for two hours to *RTLize\Flip* the module via *Firebug* & *Style.css* but without major success. So I figured this is one of case when the flipping should be done at the module's CSS files themselves. So I went to `sites/all/modules/accordion_menu` but I couldn't find anything that has all the *CSS*. I found only `accordion_menu.css` that doesn't have more than 4-5 rows of *CSS* code. So it's not something I could *RTLize\flip*.

Therefore I ask, where is the genuine *Accordion Menu* CSS file (that appear in DOM but not in the style window)? How could I track it down and flip it's CSS?

Thanks,

# Answer
> 1 votes
The Accordion Menu module uses jQuery UI, which is included with core. If the styles you're looking for are in a CSS file, they'll be in /misc/ui/jquery.ui.accordion.css (or possibly one of the more general jQuery UI CSS files).

Bear in mind that jQuery UI is a javascript library, so the styles might be applied directly to the elements at runtime, and may never exist in a CSS file as such.

---
Tags: navigation
---


# Question
Title: Is there an official/recommended way to organize CSS files for a responsive theme?
While creating a **responsive** theme (eg. a bootstrap based sub-theme) is there an **official/recommended** way to organize CSS files for different **media queries**? In general I put everything into one CSS file.

## 1. All In One

**mytheme.info:**

```
...
stylesheets[all][] = css/style.css
...

```

**style.css:**

```
body { ... }

p { ... }

...

@media (max-width: 767px) {
...
}

@media (min-width: 1024px) {
...
}

```

## 2. Separated CSS Files

**mytheme.info:**

```
stylesheets[all][] = css/style.css
stylesheets[all][] = css/480.css
stylesheets[all][] = css/720.css
stylesheets[all][] = css/960.css

```

**style.css, 480.css, 720.css ...**

## 3. Separate CSS Files for Each Media Query Defined in .info File

**mytheme.info:**

```
stylesheets[all][] = css/style.css
stylesheets[all and (min-width: 480px)][] = css/480.css
stylesheets[all and (min-width: 720px)][] = css/720.css
stylesheets[all and (min-width: 960px)][] = css/960.css

```

**style.css, 480.css, 720.css ...**

## 4. Other?

I wonder what is the recommended way for this or it doesn't matter (structural, performance wise etc).

# Answer
This is possibly hard to answer. But all the way are acceptable.

Mostly people don't like reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

*My opinion would be one of two things:*

1. If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests).
2. If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

I also found another question related to this https://stackoverflow.com/questions/16657159/when-using-media-queries-does-a-phone-load-non-relevent-queries-and-images . This will further clear your concept about this.
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How render first node in views result in different view mode?
Currently, I handle it by using `context`. before calling `views_embed_view`, I set a variable in `context` and in `node.tpl.php` at first result I unset this variable...

is there any better way to handle it?

# Answer
> 7 votes
You could use the Display Suite in combination with Views. This allows you for example to choose a different view mode for each row or alternating view modes or whatever you want.

# Answer
> 0 votes
You shouldn't use node.tpl.php to theme something related to Views.

Instead, use one of the theme template files Views tells you about in 'Theme information' in Views UI.

# Answer
> 0 votes
You should use an "attachment" view. This is an article where the author solved a similar problem to yours.

# Answer
> 0 votes
I think in regular cases the best approach is to create an views block inside the specific view and adjust the delta for the block and the view accordingly (like mentioned in this overlapping thread).

For more specific control you could also use the module Views nodes split as mentioned in another answer.

---
Tags: 7, views
---


# Question
Title: Search/filter box for Views on separate page
I am running the latest versions of Drupal 7 and Views 3.

I have a Views catalog with exposed filters for two different fields. What I would like to accomplish is to have a search box for the catalog on a different page (let's say the front page) with one field only - searching/filtering within either of the two fields. Upon submission, the user is taken to the catalog page with the results showing, and the exposed filters are free to be used again.

The only way I've been able to approximate this is to have a Global Combine fields filter running which is hidden on the catalog page, and utilized by a search filter box that I hard coded via a module. But the fact that the hidden combine field will actually have content in it once the page is loaded compromises the functionality of the visible exposed filters.

Is there a way to go about doing this?

# Answer
> 1 votes
Hope you know, in views there is one option called "EXposed form in Block"

Just enable this option then you can display the exposed filter block anywhere.

Hope this one helps you

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


# Question
Title: How do I get Facebook latest uploaded images for an account?
I am new in Drupal, I want to get all the images from my Facebook account and want to display them into front end.

I tried Facebook Album Fetcher module but this module give me the facility to get images only for a particular album not for overall. I want to get and display only the latest uploaded images from my whole account (Images will be anywhere like profile images or timeline images or album images etc).

So can anyone please tell me, is there any module which can fill my above requirement? If not then how can i get all the latest uploaded images to display them into front end?

Please help.

Thanks in advance.

# Answer
> 0 votes
I have resolved this in two ways.

1. First I use Facebook `FQL query` to get the image of Facebook page posts image. You can find the code from here. Facebook Platform API versions after 2.0 will not support FQL. So I get the images using Facebook graph API.
2. Then I get Facebook post images using `Facebook graph API`. Here is my code: Firstly you should have to get `page id` from where you want to get post images. From here you can get the Facebook page id.

After that use the code:

```
$data = file_get_contents("https://graph.facebook.com/page_id/photos/uploaded");
$results = json_decode($data);
foreach ($results as $value) {
  echo '<img src="'. $value->source .'">';
}

```

# Answer
> 0 votes
According to this answer on SO (to a 'similar' question posted 'after' this question ...), there seems to be another (better?) solution to this issue. Below is (part of) what that answer says ...

**= = = Start = = =**

Firstly I got the page id where all the images uploaded. To get the Facebook page id just go through the below two link:

https://graph.facebook.com/

https://graph.facebook.com/testpage.

Here is my code by which i got all the images for `testpage` page:

```
<?php
include_once "facebook/facebook.php";
$facebook = new Facebook(array(
    'appId'     => 'YOUR_API',
    'secret'    => 'YOUR_API_SECRET',
    'cookie' => true
));
$accessToken = $facebook->getAccessToken();
$photoQuery = urlencode('SELECT pid,owner,src_small,src_big FROM photo WHERE aid IN (SELECT aid  FROM album  WHERE owner = "YOUR_PAGE_ID")');
$photoFQL = 'https://api.facebook.com/method/fql.query?query='.$photoQuery .'&access_token='.$accessToken.'&format=json';
$photoResults = file_get_contents($photoFQL);
$photo12 = json_decode($photoResults);
foreach ($photo12 as $value) {
    echo '<img src="'. $value->src_big .'">';
}
?>

```

**= = = Stop = = =**

---
Tags: 7, social-network
---


title: Displaying Price Ranges on Views

text:
# Question
Title: Displaying Price Ranges on Views
Let's say I have 3 products in a product display that cost $5.00, $3.00, $7.00.

Right now in Commerce Kickstart 2, the view displays the first product's price which happens to be $5.00.

I would like the View to display the price range, $3.00 - $7.00, but only if there is a variance in prices (if all the products are $3.00 - just display $3.00).

# Answer
I've done it using Display Suite code field like that:

```
<?php
$max['amount'] = 0;
$min['amount'] = 0;
$products = field_get_items('node', $entity, 'field_products');
foreach($products as $product) {
  $product = commerce_product_load($product['product_id']);
  $commerce_price = array_shift(field_get_items('commerce_product', $product, 'commerce_price'));
  if($commerce_price['amount'] > $max['amount']) {
    $max = $commerce_price;
  }
  if($commerce_price['amount'] < $min['amount'] || $min['amount'] == 0) {
    $min = $commerce_price;
  }
}
return $min['amount'] < $max['amount'] ? commerce_currency_format($min['amount'], $min['currency_code']) . ' - ' . commerce_currency_format($max['amount'], $max['currency_code']) : commerce_currency_format($min['amount'], $min['currency_code']);
?>

```
> 0 votes

# Answer
A more generic approach of achieving this would be to use the module Drupal Commerce Extra Price Formatters

At the moment of writing this words, the functionality to display price formatted in ranges is achieved by means of this patch.
> 0 votes

---
Tags: commerce
---


# Question
Title: I want to save and view the node content in the same page without page refresh using content types
I have to create content type as CELL. **CELL** content type have some fields. I want to show the fields in the node create page.

How to save the data without page refresh. How to view the saved content also using views. Anyone guide to me?

I have created it cell view block and show to only node/add/cell page.

But i want to save the data without page refresh and also get the data from db without page refresh. Please anyone guide to me.

Thanks in advance.

# Answer
1. Here I have some material for you that will help you to save node form through ajax without refreshing the page at https://www.drupal.org/node/752056 . Here is also another link that will clear your idea about ajax enabled form at https://www.drupal.org/node/264429 .
2. The solution of second part of your question that shows the node value is so simple. Just make a block views containing your required field from your selected content type and then place that block into your current admin theme at desired region. Don't forget to apply restriction to only show to specific content type.
> 1 votes

---
Tags: views, nodes, ajax
---


title: Creating a custom field type

text:
# Question
Title: Creating a custom field type
I'm trying to create a custom FieldType which provides the fields for a complete address (street, house\_number, post\_code and city).

I created a `FieldWidget`, `FieldFormatter`, and a `FieldType` class and a field template, following Drupal 8: Creating a custom field - Part 1: Field type.

The widget is not rendered, unless I add a `hook_element_info()` implementation and a `hook_preprocess_address()` where I have to define the same stuff defined in `FieldWidget::formElement()`.

This is the Drupal 7 way, though. Am I missing something?

### FieldWidget class

```

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element = $element + array(
    'street' => array(
      '#title' => $this->t('Street'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->street) ? $items[$delta]->street : NULL,
      '#required' => FALSE,
    ),
    'street_nr' => array( /* … */),
    'zip' => array( /* … */),
    'city' => array( /* … */),
  );

  $form['#validate'][] = array($this, 'validateCompleteAddress');

  return $element;
}

```

### FieldFormater class

```
public function viewElements(FieldItemListInterface $items) {
  $elements = array();

  $elements['addresses'] = array(
    '#type' => 'fieldset',
    '#tree' => true,
  );

  foreach ($items as $delta => $item) {
    $elements['addresses'][$delta] = array(
      '#theme' => 'fields_address',
      'elements' => $item,
      // 'street' => String::checkPlain($item->street),
      // 'street_nr' => String::checkPlain($item->street_nr),
      // 'zip' => String::checkPlain($item->zip),
      // 'city' => String::checkPlain($item->city),
    );
  }

```

### FieldType class

```
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
  $properties = array(
    'street' => DataDefinition::create('string')->setLabel(t('Street'))->addConstraint('Length', array('max' => 255)),
    'street_nr' => DataDefinition::create('string')->setLabel(t('Street number'))->addConstraint('Length', array('max' => 100)),
    'zip' => DataDefinition::create('string')->setLabel(t('Zip'))->addConstraint('Length', array('max' => 5)),
    'city' => DataDefinition::create('string')->setLabel(t('City'))->addConstraint('Length', array('max' => 255)),
  );

  return $properties;
}

public static function schema(FieldStorageDefinitionInterface $field_definition) {
  return array(
    'columns' => array(
      'street' => array(/* … */),
      'street_nr' => array(/* … */),
      'zip' => array(/* … */),
      'city' => array(/* … */),
     ),
     'indexes' => array(),
     'foreign keys' => array(),
   );
}

```

# Answer
> -1 votes
It seems like I have to provide a custom `Element` class in the module\Element folder to define the custom input elements for the form rendering.

See `\Drupal\Core\Render\Element\Textfield`.

---
Tags: entities, 8
---


# Question
Title: Display another page's content without changing url
I want to return different content for the front page according to some conditions. Actually there is already a function used as page callback; I want to simply return the modified content (a node with /other as path alias) from it.

Is there a way to display another page's content without changing the original called URL?

# Answer
Yes, you would do something like this in your page callback function:

```
// Resolve the alias "other" to get the normal path (node/%node)
$normal_path = drupal_get_normal_path('other');

menu_set_active_item($normal_path);
return menu_execute_active_handler(NULL, FALSE);

```
> 3 votes

---
Tags: 7
---


# Question
Title: Migrate to node content type with the right user id (migrate module)
I want to migrate an old website (not Drupal) into Drupal. I want to migrate a table to a specific content type...

Inside that table there are many fields in addition to the user\_id field, so every record has 'field\_1', 'field\_2', ..., 'field\_n' and 'user\_id' field (foreign key of table "users")

First I successfully migrated "users" table. **The problem is that 'user\_id' ( of old website) is not the same as 'uid' of the Drupal website.** For example assuming that the first record will be migrated, has the 'user\_id' = 255. This user is already inserted with the 'uid' = 55 inside Drupal. Now I want to insert the node with the correct uid (witch is 55), but inside the table I have 255.

How can I do the correct mapping inside the Migrate class to insert every record inside "node" table with the correct 'uid' ? Or if there is another solution to do it "All in one" (create users and the nodes at the same time) maybe Migrate module has some powerfull functionality like creating a temporary database table that tell the migrate classes that the uid 55 is the same as the user\_id 255 of the old website...

Thanks in advance.

# Answer
You use the `sourceMigration()` method of the migrate module. You should:

1) Write one migration to migrate old users to the new version of drupal. 2) Then write a migration that moves an old table to the new version of drupal.

In (2) when you setup your field migration it sounds like you've written:

```
# Field Mappings Docs: https://www.drupal.org/node/1133448
# this maps new <= old field.
$this->addFieldMapping('new_user_id_field', 'old_user_id_field');

```

When you want to write:

```
# Search for sourceMigration on this page:
# https://www.drupal.org/node/1133448
$this->addFieldMapping('new_user_id_field', 'old_user_id_field')->sourceMigration('MigrateLegacyUsers');

```

This then uses a previously run `MigrateLegacyUsers` migration I described in (1) as the `lookup` for the new user ID in the new drupal site from the `mapping table` stored by Migrate for the `old_user_id_field` created during the `MigrateLegacyUsers` migration task.

Also note if you possibly have multiple users migrated into the system, say from a drupal legacy system, a wordpress system or LDAP you could write:

```
`->sourceMigration(array('MigrateLegacyUsers', 'MigrateWordressUsers', 'MigrateLDAPUsers'));`

```

This means: Find the legacy user id among all these possible prior migrations of Users. The first user\_id that matches the requested legacy ID will be used by migrate (so be careful to assure all the user\_ids are unique across multiple sources).
> 2 votes

---
Tags: 7, migrations
---


title: Add tag to db_insert?

text:
# Question
Title: Add tag to db_insert?
I want to do some debugging with a `db_insert` query. I tried to use the `addTag()` method, but I got an error:

```
$query = db_insert('nodes') ->addTag('my query');

PHP Fatal error:  Call to undefined method InsertQuery_mysql::addTag()

```

Is there a way I can tag this query or otherwise make it available to `hook_query_alter`?

**Edit** This query is not giving me the expected results, and I want to know why. To see why, I need to see the query with its values. Looking in the documentation for InsertQuery\_mysql, it appears there's no `getArguments()` method.

Is there any way to see the values that are being inserted?

# Answer
> 1 votes
There are the children classes of `Query`:

* `class DeleteQuery implements QueryConditionInterface`
* `class InsertQuery`
* `class MergeQuery implements QueryConditionInterface`
* `class SelectQuery implements SelectQueryInterface`
* `class TruncateQuery`
* `class UpdateQuery implements QueryConditionInterface`

Only `SelectQuery` implements `addTag` method. However, if you realyl are creating query object just there, you wouldn't need a tag anyway. Tags are only useful for `hook_query_alter`, and you shouldn't need to alter query you just created.

---

Your best options, as far as I know them, are:

1. Enable query log in your database
2. Devel module with it's query display

---
Tags: database
---


# Question
Title: Disable registration functionality for sub-domain in Drupal 7
I am using `Domain access` module for my multi-site creation and using common database for both the site:

```
1. example1.com (Default domain)
2. example2.com (sub domain)

```

I want default registration functionality for `default domain (example1.com)`, but don't want this functionality on `sub domain (example2.com)`.

If I configure this registration functionality only for Administrators from admin section (`Home » Administration » Configuration » People`) from `default domain (example1.com)` look like below screenshot:

Then this will be applicable for both `example1.com` and `example2.com`, as I am using common database and common tables for both the sites.

So can anyone please guide me how can I disable the `Registration` functionality for `sub domain (example2.com)` and use this same for `default domain (example1.com)`.

Thanks in advance.

# Answer
According to this answer on SO (to a 'similar' question posted 'a bit before' this question ...), this is a possible answer to this question (= quote from that question):

**= = = Start = = =**

As far as I know you can have different variables per domain (Because the Registration option is a variable) using the latest Domain Access module (currently 7.x-3.11 from 2014-Mar-02). It can be done with a submodule named **Domain Settings**. Enable it if haven't done yet.

If for any reason does not work for you I would suggest to use the Domain Variable module to handle variables for each domain.

**= = = Stop = = =**
> 0 votes

---
Tags: 7, multi-sites, domain-access, subsites
---


title: add to cart in Commerce + Panels

text:
# Question
Title: add to cart in Commerce + Panels
Where in the Panels "add content" list can I find the "add to cart" button?

So far I can only add it via node / node content =

but this prints node title + body text + add to cart as opposed to just add to cart - here is the node content panel with a cyan border:

How can I add just the "add to cart" button without the other stuff?

Thanks...

# Answer
> 5 votes
The "Add to Cart Form" is not available directly from Panels. You need to create a view to load the Add to Cart Form and then display that view in the panel. When creating the view you have total control over what you want to display or not display.

Panels is a way to put other Drupal content constructs together, first you have to build the constructs to hold the content though...

# Answer
> 4 votes
You need to show the Product reference field (in the "node" section) and use the formatter as "Add to cart" form.

# Answer
> 0 votes
I spent a lot of time figuring out how to create an ad to cart button in my custom panel node of product, but finally I have found a simple way.

1. I am not using teaser view of nodes, I use views and panels everywhere. So I configure the teaser view of node - so I hid everything except the price field.
2. In panels module I add content entity - Rendered Node at the settings a choose the teaser View mode and nearly that's it. But at the teaser mode there is the header and read more link what I do not need at all.
3. At your theme you need to find the `node--teaser.tpl.php` usually at the templates directory an erase the header and the read more link.

And that's all, you have a *ad to cart* button where ever you want :)

---
Tags: panels, commerce
---


# Question
Title: How to fetch the field data in computed field
In my content type i have range field which have two value from and to. i would like to print the from value only through the computed field.The object array looks like this

```
[object array]
  [field_range]
     [und]
      [0]
       [from]
       [to]

```

I tried to fetch the form value by using below piece of code but i am not able to get result. Please anyone guide me to achieve this.

```
$field_items = field_get_items($entity_type, $entity, 'field_range');
$drilldata = $field_items['und']['0']['value'];
$entity_field[0]['value'] = $drilldata->from;

```

# Answer
> 1 votes
`field_get_items()` takes care of language negotiation for you, so the field value is one level up. e.g.

```
$field_items = field_get_items($entity_type, $entity, 'field_range');
if (!empty($field_items[0])) {
  $data = $field_items[0]['value']->from;
}

```

---
Tags: entities
---


# Question
Title: Add 'Top product' field to products Ubercart
I'm trying to filter products on the homepage of my webshop (Views module). I want to add small ribbons to my products like: New,Top,Sale.

I made everything with the Views module but I think need to add a field to the Product content type but don't know what I need to choose, if I edit the product there should be a checkbox so I can edit if this product is New,Top,Sale or not.

# Answer
> 0 votes
The default product and all product classes are a node content type that can have fields added to it. Go to **Structure \> Content types \> Product \> Manage fields** to add your checkbox fields. The field will then be available in any node view for display or filtering.

---
Tags: views, nodes, ubercart
---


# Question
Title: PHP require_once() warning with hook_menu
I'm writing a small module for learning purpose, where I try to create a module settings form using hook\_menu() and form\_api.
Everything look good in my code but I still getting this error message :

> Warning: require\_once(/var/www/html/drupal/modules/system/demo\_usernames\_form.inc): failed to open stream: No such file or directory in menu\_execute\_active\_handler() (line 515 of /var/www/html/drupal/includes/menu.inc). Warning: require\_once(/var/www/html/drupal/modules/system/demo\_usernames\_form.inc): failed to open stream: No such file or directory in menu\_execute\_active\_handler() (line 515 of /var/www/html/drupal/includes/menu.inc).

```
function demo_menu(){
    $items[]=array();
    $items['admin/config/people/usernames']=array(
        'title'=>'bad usernames list',
        'description'=>t('configure not allowed usernames'),
        'page_callback'=>'drupal_get_form',
        'page arguments'=>array('demo_usernames_form'),
        'access arguments'=>array('administer site configuration'),
        'file'=>'demo_usernames_form.inc',
        );
    return $items;

```

```
function demo_usernames_form($form,&$form_state){
    $form['bad_usernames']=array(
        '#type'=>'textfield',
        '#title'=>'Bad usernames',
        '#default_value'=>variable_get('bad_usernames'),
        '#description'=>t('Enter a list of "bad usernames" separated by commas.  If a user tries to enter one of these usernames either on account creation or when editing their account, the form will display an error message.'),
        );
    return(system_settings_form($form));

}

```

# Answer
> 5 votes
If you look a bit closer at the path in the error message:

> /var/www/html/drupal/modules/system/demo\_usernames\_form.inc

You'll notice it's trying to find your include file in the system module.

It's happening because the user module's implementation of `hook_menu()` has this in it:

```
$items ['admin/config/people'] = array(
  'title' => 'People',
  'description' => 'Configure user accounts.',
  'position' => 'left',
  'weight' => -20,
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file' => 'system.admin.inc',
  'file path' => drupal_get_path('module', 'system'),
);

```

Notice the `file path` at the bottom, explicitly setting the path Drupal should look for the included file in.

Since properties are inherited from parent paths, and the path of your item sits nicely under that one, you get an implicit `file path` that you weren't expecting. The result: your module path is no longer consulted when the system tries to find the include file.

To fix, just add the correct `file path` to your `hook_menu()` code:

```
$items['admin/config/people/usernames']=array(
  'title'=>'bad usernames list',
  'description'=>t('configure not allowed usernames'),
  'page_callback'=>'drupal_get_form',
  'page arguments'=>array('demo_usernames_form'),
  'access arguments'=>array('administer site configuration'),
  'file'=>'demo_usernames_form.inc',
  'file path' => drupal_get_path('module', 'demo'),
);

```

And flush them caches.

# Answer
> 1 votes
it's weird because it's calling "demo\_usernames\_form.inc" from drupal/modules/system/ not from your module directory in your case demo/. make sure you clear cache. if did't work try to add "file path" and see how it goes, this just for debugging but it should pick the file from your module by default. see more here hook\_menu: "file path": The path to the directory containing the file specified in "file". This defaults to the path to the module implementing the hook."

---
Tags: forms, routes
---


title: How to add reset button to forms?

text:
# Question
Title: How to add reset button to forms?
I've been researching this matter for a while with no clear answer yet.
So, here are a few questions ...

1. I'm **assuming** (correct me if I'm wrong) that Drupal 7 doesn't support reset buttons. It appears, according to the form API (as discussed in Pro Drupal 7 Development), that all the buttons (input type="submit", button, and image\_button) are by default submit buttons. There doesn't appear to be a way to override the defaults either.

So, if I wanted to add functionality to my forms for my users to clear forms (if they choose), would I have to create a module?
2. Would I be able to pull this off by using the **general button type** with **executes\_submit\_callback** set to **false** and by adding some type of Ajax function to the mousedown event?

\** EDIT: I added the following to my hook\_form\_alter() \**

```
$form['reset'] = array(
'#input' => TRUE,
'#name' => 'reset',
'#button_type' => 'reset',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => TRUE,
'#process' => '',
'#theme_wrappers' => array('button'),
);

```

I got the following error message & warning:

> Notice: Undefined index: #type in \_form\_builder\_handle\_input\_element() (line 1949 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).
>
> Warning: Invalid argument supplied for foreach() in form\_builder() (line 1763 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).

Is there a way to add the "reset" button type to the types of buttons without crashing the entire form.inc?

# Answer
> 10 votes
My preferred way to do this is.

Add the button to your form like so:

```
$form['options']['reset'] = array(
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('MY_MODULE_FORM_ID_reset'),
);

```

Then create the reset function like so:

```
function MY_MODULE_FORM_ID_reset($form, &$form_state) {
  $form_state['rebuild'] = FALSE;
}

```

No Javascript, no markup.

# Answer
> 6 votes
Don't know of support in Form API for a reset button, but simple enough to add a form alter to add one.

```
MYMODULE_form_alter($form, $form_state, $form_id) {
  $form['resetbutton'] = array(
    '#markup' => '<button type="reset"/>',
    '#weight' => 1000
  );
  return $form;
}

```

# Answer
> 2 votes
```
function mymodule_form_alter(&$form, &$form_state, $form_id) {

switch ($form_id) {

case 'myform':
  $form['buttons']['reset_button'] = array(
    '#type' => 'markup',
    '#value' => '<input class="form-button" value="Reset" type="reset">',
    '#weight' => 2000,
  );
  break;
 }
 return $form;
}

```

# Answer
> 1 votes
This is 100% working:

```
$form['reset'] = array(
    '#type' => 'markup',
    '#markup' => '<input type="reset" value="Reset All Values" class="form-submit">',
);

```

# Answer
> 0 votes
Usually I give reset hyperlink which is pointing to current page URL using Markup form type.

When ever we click this link, it will refresh the page & will reset all the form elements. Else using javascript / Jquery we can reset the form elements by providing specific CSS Class / ID to that link.

# Answer
> 0 votes
None of the previous answers worked in the case I've been facing (`views_exposed_form` with BEF and ajax enabled). I had set up the reset button from BEF, but it was working only for one of my two views displays, whatever I tried...

I purpose another approach, in case it could help.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function moduleName_form_views_exposed_form_alter(&$form, &$form_state) {

  if (isset($form_state['view']->current_display) && 'some_display' == $form_state['view']->current_display ) {

    $submit_btn_id = $form['submit']['#id'];
    if (!empty($submit_btn_id) && !empty($form['reset'])) {
      //avoid the know issue redirecting views resets to /node
      $form['#action'] = '/' . $_GET['q'];
      // Add own reset button
      $form['submit']['#suffix'] = '<input type="reset" onclick="javascript:jQuery(this.form).clearForm();jQuery(this.form).find(\'#' . $submit_btn_id . '\').trigger(\'click\');return false;">' . t('Reset') . '</input>';
      $form['submit']['#attributes']['class'][] = 'my-views-filter-submit';
      // Remove the original RESET button.
      unset($form['reset']);
    }
  }
}

```

About the issue redirecting views resets to `/node`... `onclick="history.go(0)`; is an alternative.

This was inspired by Julian blog add ajaxified reset button for views exposed filters but I had to adapt it substantially.

# Answer
> -2 votes
This is my way to add Reset button, hope you like it :D

```
$form['reset'] = array(
'#markup'   => '<input type="reset" class="form-submit" />',
'#title'    => 'Reset',
);

```

---
Tags: 7, forms
---


title: View: Only display parent term?

text:
# Question
Title: View: Only display parent term?
I'm trying to create a view that will display a number of nodes sorted by their parent terms.

For instance, if my terms have the following hierarchy:

```
- Fruit
--Apple
--Banana
--Orange
-Vegetable
--Broccoli
--Carrot
--Beet

```

I would ideally like to get two 'headings', one for Fruit, one for Vegetables and then list nodes with any sub-term in those sections.

I have tried using view relationships and contextual filters but I just feel lost. What should I do?

Thank you!

# Answer
Go to your view settings. Add term relationship - your term field. Add Filter critera - Parent term. Operator 'equal' value - leave empty
> 1 votes

# Answer
You first need to relate the child term to the parent, and then use the grouping feature to group nodes by the parent term.

The tricky part about this is that it only works to a depth of 2. If a term is a parent *at any depth* it will be added to the group. To explain, in the example below "apples" would also be considered a parent and so you would end up with an "apples" group in addition to fruit and vegetables. (If anyone out there knows how to limit the grouping of parents by depth, leave a comment.)

*This won't work:*

> fruit
> \- - bananas
> \- - apples
> \- - - - granny smith
> \- - - - macintosh
> vegetables
> \- - carrots

*This works:*

> fruit
> \- - bananas
> \- - apples
> \- - oranges
> vegetables
> \- - carrots

### View Set-up

**Relationships**

*Content: Taxonomy terms on node*

```
             Vocabularies .. [select]
               Identifier .. "child"

```

*Taxonomy term: Parent term*

```
             Relationship .. child
               Identifier .. "parent"
Require this relationship .. [checked]

```

**Fields**

*Content: Title*

```
No special settings

```

*Taxonomy Term: Name*

```
             Relationship .. parent
     Exclude from display .. [checked]

```

**Format**

*Format: Settings*

```
      Grouping field Nr.1 .. (parent) Taxonomy Term: Name

```

**Query settings (Other)**

```
                 Distinct .. [checked]

```

*Note: The above settings reduces duplicates. If for some reason this causes issues or you're looking for more fine-grained control, use Aggregation (under "Other").*

Hope that helps!
> 1 votes

---
Tags: views
---


# Question
Title: How to apply node access rules when querying menu_links table
I am creating a custom block which displays a menu. The menu is constructed by retrieving certain menu links from the menu\_links table in the database. It has occurred to me that building it this way could introduce a security issue, in the situation that a user does not have permission to view a certain node, but that menu link is still included in in the custom block.

I am wondering if there is some way of filtering results obtained from menu\_links table based on current user role?

Menu links are currently being retrieved with queries like this one:

```
// Get all siblings of parent menu.
$siblings = db_select('menu_links', 'ml')
  ->fields('ml')
  ->condition('plid', $target['plid'])
  ->condition('hidden', 0)
  ->orderBy('weight')
  ->execute();

```

Actual menu structure is being constructed as a render array (basically each menu item is a link within a div wrapper). Below is example of how a menu item is being constructed:

```
foreach ($siblings as $sibling) {
  $link = l($sibling->link_title, $sibling->link_path);
  $menu_item = array(
    '#type' => 'container',
    '#attributes' => array(
      'class' => array('nav-level0'),
    ),
    'content' => array(
      '#markup' => $link,
    ),
  );
  $menu[] = $menu_item;
}

```

# Answer
Yes, `menu_get_item()` will set return an `access` element that notes whether the current user has access.

```
  $siblings = db_select('menu_links', 'ml')
    ->fields('ml')
    ->condition('plid', $target['plid'])
    ->condition('hidden', 0)
    ->orderBy('weight')
    ->execute();
  foreach($siblings as $sibling) {
    $menu_item = menu_get_item($sibling->link_path);

    if($menu_item['access']) {
      //Current user has access
    } else {
      //Current user doesn't has access
    }
  }

```
> 0 votes

---
Tags: routes, database, security
---


title: hook_node_access not working

text:
# Question
Title: hook_node_access not working
I am trying to use hook\_node\_access to change some permissions when viewing a node type. The problem is that even when I call it in my module, it doesn't work.

```
function MyModule_node_access($node,$op,$account) {
  die("it works!");
}

```

I can 100% confirm that other hooks in the same module are working fine. I have disabled and reenabled the module. I have cleared all cache. I can confirm that my test user is not uid = 1, and it does not have the "Bypass content access control" permission. So why is hook\_node\_access not working for me? Does it not work by itself?

# Answer
node\_access is a hook like any other, so I can see no reason why it wouldn't be called if:

* your hook implementation is named correctly
* the module is activated
* the file the hook implementation is in has been included
* the 'module\_implements' cache has been cleared
* the page you are viewing is calling node\_access() at some point (try a `node/xxx` page for example.)

You might try executing `module_implements('node_access')` and checking if your module is included in that list.

If so, node\_access is not being called.

If not, the function YourModule\_node\_access does not exist, or is not included.
> 6 votes

# Answer
I used `hook_node_access()` and had the same issue: It wasn't firing and driving me nuts.

What worked for me was NOT to be logged in as an admin. I went in as a different role and all worked as expected.
> 26 votes

# Answer
From hook\_node\_access

> The administrative account (user ID #1) always passes any access check, so this hook is not called in that case. Users with the "bypass node access" permission may always view and edit content through the administrative interface.
> 8 votes

---
Tags: 7, users
---


# Question
Title: Location Contextual Filter: Distance/Proximity
I am trying to create a location-based contextual filter, and it seems like it should be taking four arguments - Lat, Lon, distance (number) and distance (unit).

How should this filter actually be created in the URL? I'm trying the following format:

42.279594,-83.732124,25, 2, miles

and getting nothing.

Would I just create a url with four arguments? Like location/%/%/%/%?

I've never used a contextual filter with multiple arguments before.

# Answer
> 0 votes
The correct answer is this:

```
?distance%5Blatitude%5D=42.279594&distance%5Blongitude%5D=-83.732124&distance%5Bsearch_distance%5D=1&distance%5Bsearch_units%5D=mile

```

---
Tags: 7, views, location
---


# Question
Title: How to get XML/JSON data for api.drupal.org?
In my earlier question How to get node IDs from drupal.org?, I can get the XML data of a node by going to https://www.drupal.org/api-d7/node/274365.xml where 274365 is the node id of a particular page. In similar way I can access all the node in **drupal.org** Website.

Now I want the same kind of **XML data** for a node pages in https://api.drupal.org.

For example what is the XML data page for https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7 ?

# Answer
> 1 votes
I was curious about this, too. Below is a dump of the API in JSON format. Unfortunately I don't think the same is available in XML format, or that the query can be further refined to, say, retrieve only a list of hooks.

URL structure:

```
api/(project)/full_list/(branch)?limit=M&page=N

```

https://api.drupal.org/api/drupal/full\_list/7?limit=20&page=0

### Source

---
Tags: 7, community-official-site
---


# Question
Title: Dedicated image style for media gallery teaser
Is there any possiblity to define another dedicated image style for the teaser of a media gallery node only? I can change the default gallery thumbnail image style but this has also effect on the galleries overview page.

Because I like to create an image slider on the front page with the 5 newest galleries but need the image in another format then the default square thumbnail format.

Is there any possbility to do that so?

# Answer
> 0 votes
I managed to achieve what I want. I used the `Entity View Modes (evm)` module. I created a custom view mode under **Configuration » Entity View Modes » File**.

This view mode is now available under **Structure » File types » Image » Manage file display**

Here I can select the checkbox **Image**. And then select my desired image style under the **Display settings** in tab **Image** select box **Image style**.

This new view mode is now usable in display suite. If you go to the content type **Gallery** and click on **Manage display** where display suite hooks in you can now choose the formatter **Rendered file** for the field **Gallery media**. In the formatter settings you'll find your new view mode. Select it and et voilà you get the image with your desired image style.

---

**DS solution**

I also found a solution with display suite itself. Without the needing for the additional Entity View Modes module.

Just create a new view mode for **File** using display suite. Then in the **Structure \> File types** menu you can activate the view mode for **Images**. And choose your custom image style.

This view mode you can then select in the field template settings like in the description above.

# Answer
> 1 votes
You can create your own image style at admin/config/media/image-styles by click "Add style" link.

Use below code in your template file to fetch particular image style.

```
$my_style = image_style_url('your-img-style', 'image/uri');
<img src=' . $my_style . '/>

```

More details about image style.

# Answer
> 0 votes
Here is what you need to do.

1. Create a new image style as @kalidasan mentioned in his answer.
2. Copy the template you are using from `Display Suite` `layout` directory and place it in your theme template directory.
3. Implement `hook_ds_pre_render_alter()` and from there apply the `image_style_url()` as mentioned by @kalidasan in his answer.

`$vars['image_style'] = image_style_url('IMAGE_STYLE', 'IMAGE_URI');`
4. Modify the template you copied from `Display Suite` to render the `$image_style` you created from #3.

---
Tags: 7, nodes, media
---


# Question
Title: Access denied at password reset page when logging in
I run a D7 site that for some reason is not allowing users to reset their passwords, but only on the server. The email with the one-time login link is sent just fine, but when the user clicks on the link, they get a 403 page with the generic "You are not authorized to access this page" message. I know this must be server environment specific, because with a clone of the site on my local machine (sending the email using the SMTP module), it works just fine. I'm guessing the issue happens in user\_edit\_access(), where it is comparing the value of $account-\>uid with $GLOBALS\['user'\]-\>uid, but that's just a guess at this point.

Any suggestions as to what the problem could be? The servers are using Varnish, so that's one thought that came to mind, but I'm not sure how to figure that out.

Thanks.

# Answer
Comment out the `/* $cookie_domain = $_SERVER['HTTP_HOST']; */` from settings.php from the path \sites\defaults will work for you.

or else use the below code in settings.php:

```
<?php
/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains. Make sure to always start the $cookie_domain
 * with a leading dot, as per RFC 2109.
 */
$cookie_domain = '.your_domain.com';
$conf['https'] = TRUE;
?>

```

On sites with anonymous users, it is handy not to set this so that you login as admin on one tab and anonymous on another by not using "www" on one of them.

source
> 1 votes

---
Tags: users, proxies
---


# Question
Title: Where do I find the settings for adding a vocabulary to a content type in Drupal 7?
In Drupal 7, I can't find the ***Content types and Required*** setting under ***edit vocabulary***.

How do I customise it?

***Drupal6***

***Drupal7***

# Answer
> 2 votes
Head over to the **Manage fields** tab of your content type. For example, for "article" that would be admin/structure/types/manage/article/fields. Then add a **Term Reference** field.

This question is about Drupal 7, but be aware that *Term Reference* appears to be deprecated and potentially be removed from Drupal 8 (in favor of the entity reference field). For more details on that, refer to the question about "Are there any benefits/caveats with using Entity Reference over Term Reference?", in which there is a comment also like "*Term reference isn't going anywhere and there will be an upgrade path from 7 to 8*".

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


title: How do I return JSON data?

text:
# Question
Title: How do I return JSON data?
Is this the correct way to return json data. If not, how should it be accomplished? I would like to return the data back to car.module.

### card.module

```
drupal_add_js('jQuery(document).ready(function () {

  currentRequest = $.ajax({
  timeout:0,
  cache: false,
  url: pageUrl,
  dataType: "json",
  type: "GET",
  success: function(data) {
    $("#edit-field-currency-type-und-0-value").val(data.currency);
  }

});

```

### AJAX request module

```
$items['mccurr/%'] = array(
  'title' => '',
  'page callback' => 'ajax_currency_type',
  'access arguments' => array('access content'),
  'page arguments' => array(1),
  'type' => MENU_SUGGESTED_ITEM,
);

function ajax_currency_type($ccode) {
 drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
  $query = "SELECT countries_country.currency
    FROM countries_country
    WHERE countries_country.iso2 = '".$ccode."'";

  $data = db_query($query);

  return drupal_json_encode($data);
}

```

# Answer
> 12 votes
To return $data in json format using Drupal-7's page callback output, you should return through :

```
drupal_json_output($data);

```

in your page callback function. For more ref : http://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_json\_output/7

Note : in your javascript in car.module, var pageUrl seems undefined. Make sure it is defined.

# Answer
> 1 votes
You really should never pass unsanitized input anywhere, see "Bobby Tables".

Drupal has the facility to escape database parameters like this;

```
$query = "SELECT countries_country.currency
    FROM countries_country
    WHERE countries_country.iso2 = :ccode";

$data = db_query($query, array(':ccode' => $ccode));

```

Note that you'll also need to `->fetchAll()` else you're just returning a database object.

# Answer
> 0 votes
I've recently found the REST/JSON module that once enabled exposes APIs to list nodes and commends, to log in / log out users, and to create entities with REST calls that read and output JSON data.

It doesn't require any further code or configuration.

This module is unsupported due to a security issue the maintainer didn't fix, since June 8, 2016.

---
Tags: 7
---


# Question
Title: Node export module imported node as another node numbers
I used Node Export module to export my nodes.

I exported 3 articles that are node/1, node/2 and node3.

While I imported it into another site, the node became node/4, node/5 and node6.

How do I make it imported as the same node number.

If there is already have that node, it will override it.

***Drupal 6***

Settings:

**Node export**

When importing a node that already exists: Create a new revision of the existing node

***UUID***

Automatic UUID generation for taxonomy:

# Answer
You can't, and you shouldn't.

Node Export requires UUID for a reason, and that reason is decoupling database identifier of a node (`nid`) from it's logical identifier and address. These are supposed to be defined by UUID now, so if you are using UUID module and still have addresses like http://example.com/node/1 then your site is not using modules in a way they are designed to work.

Also, as Node Export project page says, if you need anything fancy on import, you should export in Feeds format, and use Feeds for import. I believe that updating existing nodes is a case where it would be recommended approach.
> 2 votes

---
Tags: nodes
---


# Question
Title: Update warning: "Some of the pending updates cannot be applied because their dependencies were not met." Followed by "No pending updates."
I inherited a site from a previous webmaster (who doesn't seem to have known what he what doing) last month and I have been trying to fix it up since then, but one pesky update issue won't go away. Whenever I run update.php, it goes through halfway and then stops with the following messages:

✓ Verify requirements(done)
✓ Overview(done)
▶ Review updates(active)

**Warning message**

Some of the pending updates cannot be applied because their dependencies were not met.

**Status message**

No pending updates.

*Front page*
*Administration pages*

I've been getting this error message for some time now whenever I run update. Some searching revealed that uninstalling and reinstalling the affected module might fix the error, but I can't figure out where it is coming from, or which module could be causing it. Is there any way to find out which module is causing this error without uninstalling and re-installing every single module on the site?

# Answer
> 1 votes
Just in case someone else finds this ... I added a watchdog line to the function **update\_script\_selection\_form($form, &$form\_state)** in update.php.

```
foreach ($updates as $module => $update) {
  if (!isset($update['start'])) {
    $form['start'][$module] = array(
      '#type' => 'item',
      '#title' => $module . ' module',
      '#markup'  => $update['warning'],
      '#prefix' => '<div class="messages warning">',
      '#suffix' => '</div>',
    );
    watchdog('update','NO START: '.$module);
    $incompatible_updates_exist = TRUE;

    ...

```

It was *XML sitemap* causing the problems on a D6-\>D7 upgrade, and I ended up having to delete its tables manually before it would uninstall.

---
Tags: updating
---


# Question
Title: recaptcha not allowing login on localhost
hi Not sure if this is specifically a Drupal question but I'll try it here first.

I am using Google recaptcha on my site, I set it up while the site was already online. but now I'm trying to make some changes I've backedup and downloaded my site to a localhost dev machine. now when I use this site I get: "Google reCAPTCHA does not accept this submission. Try again please, or contact to Site support services."

its a bit frustrating and the only method I can think of is to remove this tool on the website, then dump the DB for my local version.

Anyone know another way around this, specifically to get it working properly?

# Answer
For Google, your production site is not the same, as your devel one. But you can disable modules using drush, that does not require you to log in.
> 0 votes

---
Tags: captcha
---


title: Drupal-Bootstrap CSS-oriented question

text:
# Question
Title: Drupal-Bootstrap CSS-oriented question
## Background

I've installed the Bootstrap theme, created a sub-theme, edited it's INFO file, and the theme itself seem to appear fine while surfing at the site.

## The problem

I went to this themes' Style.CSS file and added some CSS, but for some reason, Most (if not all) of the CSS I add requires the `!important` declaration at the end of each property... Any idea why all of these `!important`'s needed? It is surly not the natural behavior of any theme...

## Further details

* The site is RTL.
* I'm not sure if there is a connection but this problem might do with the fact that my new sub-theme is running online only to me, via the ThemeKey module which let's you associate a specific theme with a specific something (like users).

# Answer
As mentioned by @clive in the comments, the issue is certainly specificity or **style precedence**, which basically means that some CSS rules will have more importance than others. I'll give you the 2 most basic things you need to know:

**Order.** The latest in the code a CSS rule is, the more *power* it has. So, your custom CSS stylesheet should be loaded after other stylesheets.

**Selector specificity.** By rule, the more specific a selector is, the more *power* it has. An *ID* selector takes precedence over a *class* selector, and a class selector over an *element* selector. For instance, let's say you want to style a div:

```
<div id="login" class="col-md-1">...</div>

```

In your CSS, you could reference this div in, basically, three ways:

```
div { color: red; }

.col-md-1 { color: green; }

#login { color: orange; }

```

In this case `#login` rules will have precedence because of two reasons: **Order** (it is below the other two selectors) and **Selector specificity** (an ID selector is more specific because it's unique). Therefore, the text color will be orange.

The only exception to these rules is when you use the `!important` keyword, which *adds superpowers* to your rule, forcing it to take precedence over any other selector. That's why in your code, it only works when you do this, as you mention.

So, instead of adding `!important`, try to understand your selectors and you'll do just fine.

EDIT: As mentioned in the comments, a syntax error (in this case, a missing bracket) in your CSS file could cause all following code not being read (Tip: If you use SASS or Scss, they will alert you of these type of errors).
> 3 votes

---
Tags: theming
---


# Question
Title: Edit admin email template for new user registrations
How do I edit the default email that gets sent to admin upon new user registration? I presume this is being managed by LoginToboggan because its being referenced in the email body text:

> UserName has applied for an account.
>
> http://example.com/user/XX/edit
>
> The user has automatically received the permissions of the **LoginToboggan** validating role. To give the user full site permissions, click the link below:
>
> http://example.com/user/validate/XX/XXXXXXXXXXX/XXXXXXXXX\_XXXXXXXXXXXXXXXX-XXXXXXXXXXXXX/admin
>
> Alternatively, you may visit their user account listed above and remove them from the validating role.

# Answer
If you look into logintoboggan.module you would see that this message is hard-coded and appended using the hook\_mail\_alter function and that it's altering the **Welcome (awaiting approval)** (user\_register\_pending\_approval\_admin) located in admin/config/people/accounts. So if you like to append the data in the middle, you can edit the said email body in the admin page but if you also like to alter the message by logintoboggan then you need to implement hook\_mail\_alter also.
> 1 votes

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


# Question
Title: How to insert multiple checkbox value in database?
In the process of creating data base, I need to read the Name, Father Name, Gender and Language. I could able to successfully store the data for all the fields stated above. When it comes to language field, I need to provide a **checkbox** option where user can select two or three options. But the problem is, it is not showing up in the proper format.

In database I used language field as varchar(50):

**my\_register.module**

```
 <?php
 // $Id$

 /**
 * Implement hook_help().
 */
 function my_register_help($path, $arg) {
   if ($path == 'admin/help#my_register') {
      return t('Fill the registration form by user');
   }
 }

 /**
 * Implements hook_menu().
 */
 function my_register_menu() {
   $items = array();

   $items['admin/registration'] = array(
     'title' => 'Registration',
     'description' => 'Configuration for the My register Module.',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('my_register_form'),
     'access arguments' => array('administer users'),
     'type' => MENU_NORMAL_ITEM,
    );

   $items['admin/registration/show'] = array(
    'title' => 'View Registered User',
    'description' => 'Tabuler disply of registered user',
    'page callback' => 'my_register_table_page_display',
    'access callback' => TRUE,
    'access arguments' => array('administer users'),
   'type' => MENU_NORMAL_ITEM,
  );

 return $items;
}

/**
* Form builder.
*/
function my_register_form($form, &$form_state) {
  // Text for Name.
  $form['my_register_uname'] = array(
   '#type' => 'textfield',
 '#title' => t('Enter Name'),
 '#description' => t('Enter the user name'),
 '#size' => 40,
 '#maxlength' => 120,
 '#required' => TRUE,
  );
// Text for F_name.
 $form['my_register_fathername'] = array(
'#type' => 'textfield',
'#title' => t('Father Name'),
'#description' => t('Enter the Father name'),
'#size' => 40,
'#maxlength' => 120,
'#required' => TRUE,
 );

// Text for contact number.
 $form['my_register_phone'] = array(
'#type' => 'textfield',
'#title' => t('Contact Number'),
'#description' => t('Mention 10 digit Valid Contact Number'),
'#size' => 20,
'#maxlength' => 10,
'#required' => TRUE,
 );

 // Text for Email Id.
 $form['my_register_email'] = array(
'#type' => 'textfield',
'#title' => t('E-mail Address'),
'#description' => t('Mention valid E-mail address'),
'#size' => 30,
'#maxlength' => 50,
'#required' => TRUE,
  );
  // Radio for gender
  $selectgender = array(0 => t('Male'), 1 => t('Female'), 2 => t('other'));
  $form['gender']['selectgender'] = array(
  '#type' => 'radios',
 '#title' => t('Select Gender'),
'#default_value' => isset($node->selectgender) ? $node->selectgender : 0,
'#options' => $selectgender,
 );

  //Textarea for Address.
  $form['my_register_address'] = array(
 '#type' => 'textarea',
 '#title' => t('Postal Address'),
 '#description' => t('Postal address'),
 '#rows' => 5,
 '#columns' => 40,
 '#required' => TRUE,
  );
  // Drop down for Select education
  $form['education'] = array(
 '#title' => t('Select which class you have Passed'),
 '#type' => 'select',
 '#description' => 'Select the Class whic you have passed',
 '#options' => array(t('--- SELECT ---'), t('10th'), t('12th'), t('BCA'), t('BBA'), t('B-Tech'), t('MCA'), t('M-Tech')),
  );
  // Check box for select language
  $form['my_register_language'] = array(
 '#type' => 'checkboxes',
 '#options' => drupal_map_assoc(array(t('Hindi'), t('English'), t('other'))),
   '#title' => t('Select language you Known'),
   );

  //submit button
  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Submit'),
   '#submit' => array('my_register_form_submit'),
   '#validate' => array('my_register_form_validate'),
  );

return $form;
 }

  $friend_ids = serialize(array_filter($form_state['values']['my_register_language']));
  global $user;
   db_insert('my_register')
     ->fields(array(
     'rid' => $user->rid,
   'uname' => $form_state['values']['my_register_uname'],
   'father_name' => $form_state['values']['my_register_fathername'],
   'contact' => $form_state['values']['my_register_phone'],
   'email_id' => $form_state['values']['my_register_email'],
   'address' => $form_state['values']['my_register_address'],
  'education' => $value_edu,
  'language' => $friend_ids,
  'gender' => $value_gender,

   ))->execute();
   drupal_set_message("Successfully user registered");
   }

    function my_register_table_page_display() {

     $header = array(
    array('data' => t('Rid')),
    array('data' => t('Name')),
     array('data' => t('Father Name')),
    array('data' => t('Address')),
    array('data' => t('Contact')),
   array('data' => t('E-mail Id')),
   array('data' => t('Education')),
   array('data' => t('Gender')),
   array('data' => t('Language')),
   );

$query = db_query("SELECT * FROM {my_register}");

     $rows = array();
           foreach($query as $res) {
         $rows[] = array($res->rid, $res->uname, $res->father_name, $res->address, $res->contact, $res->email_id, $res->education, $res->gender, $res->language,);
      }
        // If rows are not empty theme and display the rows.

        $output = '';

        if (!empty($rows)) {

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

      }

     else {

        $output .= t("No results found.");

     }

     return $output;

    }

```

# Answer
> 1 votes
Looks like you'll need to unserialize the data:

```
$arr = unserialize($result->my_field);

```

Then you can turn the array into a string (or whatever):

```
$str = implode(', ', array_filter($arr));

```

---
Tags: database
---


# Question
Title: How to show a place holder block if a view is empty
I have a site that has multiple inventory views. When a view is empty (no items to list) I need to display a block that tells the user to check back later.

How can I do this?

# Answer
> 2 votes
Views has a feature that already accommodates this; under the **Advanced** section there is a **NO RESULTS BEHAVIOR** option that lets you add different fields on the condition there are no results in the view.

---
Tags: views, blocks, rules
---


# Question
Title: Drupal form disable form error message or use ajax validate instead of #require
I have a complex form. Which will let users to select some drop-down items to add a food diary record.

Currently, I'm using this

> if (!form\_get\_errors()) {.....}

to decide whether to insert new record to database or not. (in "function adddiary\_form\_submit($form, &$form\_state)" area).

If a user did not select all fields correctly, I use this

> "$commands = array(); $commands\[\]=ajax\_command\_alert('Please select all fields！'); return array('#type' =\> 'ajax', '#commands' =\> $commands); }"

to show a alert window to notified the user.

However, my problem is that the error message produce by Drupal will not show directly on the add record page (diary/add) because I use a ajax on submit button, and instead it show on the page I assign to redirect to (diary/list).

> $form\['submit'\] = array( '#type' =\> 'submit', '#value' =\> t('Submit'), '#executes\_submit\_callback' =\> FALSE, '#ajax' =\> array( 'callback' =\> 'adddiary\_form\_submit', ), );

I'm not good at coding. I also try to use ajax validate but not working.

Do anyone know how to make the error message disable? or reset? or show directly in the current page instead of showing up when a record is already insert into database.(kind of strange right?)

Or how to use ajax? to check every select list is selected...

I have no idea how to make this work correctly.

I tried my best to describe the situation. If you still not clear, you may ask for detail.

Hope someone may help me with this, I've already look up information to achieve this form for a week.

Thanks@@~!

```
<?php

function adddiary_menu(){
    return array(
        'diary/add' => array(
            'title' => 'Add Diary',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('adddiary_page'),
            'access arguments' => array('access content'),
        )
    );
}

function adddiary_permission() {
  return array(
    'adddiary module' => array(
      'title' => t('Add diary module permission'),
  ));
}

function adddiary_page($form, &$form_state) {

    if (user_access('adddiary module')) {
    //Allowed

    $form['date'] = array(
    '#type' => 'date_popup',
    //'#title' => 'Date',
    '#default_value' => date('Y-m-d'),
    '#date_format' => 'Y-m-d',
    //'#date_label_position' => 'within',
    '#date_year_range' => '-0:+0',
    );

    $form['time'] = array(
    '#title' => t('Time'),
    '#type' => 'radios',
    '#options' => array(
        1 => t('Breakfast'),
        2 => t('Lunch'),
        3 => t('Dinner'),
       ),
    '#required' => TRUE,
    );

    $form['type'] = array(
    '#type' => 'select',
    '#title' => 'Food',
    '#options' => array(
        1 => t('Type1'),
        2 => t('Type2'),
        3 => t('Type3'),
        4 => t('Type4'),
        5 => t('Type5'),
        6 => t('Type6'),
       ),
    '#required' => TRUE,
    );

    //Type1
    $query1 = db_select('food_profile');
    $query1->fields('food_profile', array('ID', 'type','name'));
    $query1->condition('type', '1', '=');
    $query1->orderBy('name', 'ASC');
    $results1 = $query1->execute();

    $options1 = array();
    foreach ($results1 as $result1) {
    $options1[$result1->ID] = $result1->name;
    }

    $form['type1'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '1'),
        ),
    ),
    '#options' => $options1,
    );

    //Type2
    $query2 = db_select('food_profile');
    $query2->fields('food_profile', array('ID', 'type','name'));
    $query2->condition('type', '2', '=');
    $query2->orderBy('name', 'ASC');
    $results2 = $query2->execute();

    $options2 = array();
    foreach ($results2 as $result2) {
    $options2[$result2->ID] = $result2->name;
    }

    $form['type2'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '2'),
        ),
    ),
    '#options' => $options2,
    );

    //Type3
    $query3 = db_select('food_profile');
    $query3->fields('food_profile', array('ID', 'type','name'));
    $query3->condition('type', '3', '=');
    $query3->orderBy('name', 'ASC');
    $results3 = $query3->execute();

    $options3 = array();
    foreach ($results3 as $result3) {
    $options3[$result3->ID] = $result3->name;
    }

    $form['type3'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '3'),
        ),
    ),
    '#options' => $options3,
    );

    //Type4
    $query4 = db_select('food_profile');
    $query4->fields('food_profile', array('ID', 'type','name'));
    $query4->condition('type', '4', '=');
    $query4->orderBy('name', 'ASC');
    $results4 = $query4->execute();

    $options4 = array();
    foreach ($results4 as $result4) {
    $options4[$result4->ID] = $result4->name;
    }

    $form['type4'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '4'),
        ),
    ),
    '#options' => $options4,
    );

    //Type5
    $query5 = db_select('food_profile');
    $query5->fields('food_profile', array('ID', 'type','name'));
    $query5->condition('type', '5', '=');
    $query5->orderBy('name', 'ASC');
    $results5 = $query5->execute();

    $options5 = array();
    foreach ($results5 as $result5) {
    $options5[$result5->ID] = $result5->name;
    }

    $form['type5'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '5'),
        ),
    ),
    '#options' => $options5,
    );

    //Type6
    $query6 = db_select('food_profile');
    $query6->fields('food_profile', array('ID', 'type','name'));
    $query6->condition('type', '6', '=');
    $query6->orderBy('name', 'ASC');
    $results6 = $query6->execute();

    $options6 = array();
    foreach ($results6 as $result6) {
    $options6[$result6->ID] = $result6->name;
    }

    $form['type6'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '6'),
        ),
    ),
    '#options' => $options6,
    );

    $form['portion'] = array(
    '#title' => t('Portion'),
    '#type' => 'select',
    '#options' => array(
        1 => t('1'),
        2 => t('2'),
        3 => t('3'),
        4 => t('4'),
        5 => t('5'),
       ),
    '#required' => TRUE,
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#executes_submit_callback' => FALSE,
    '#ajax' => array(
        'callback' => 'adddiary_form_submit',
         ),
    );

    return $form;
    } else {
    //Access denied
    drupal_goto("user/login");
  }
}

function adddiary_form_validate($form, &$form_state) {

}

function adddiary_form_submit($form, &$form_state) {
    if (!form_get_errors()) {
    $food_ID = form_result_helper($form_state);

    $result = db_query('SELECT name, calorie, protein, fat, fat_1, fat_2, fat_3, cho, cho_1, cho_2, mineral, mineral_1, mineral_2, mineral_3, mineral_4 FROM {food_profile} n WHERE ID = :food_ID', array(':food_ID' => $food_ID));
    foreach($result as $item) {
        $name = $item->name;
        $calorie = $item->calorie;
        $protein = $item->protein;
        $fat = $item->fat;
        $fat_1 = $item->fat_1;
        $fat_2 = $item->fat_2;
        $fat_3 = $item->fat_3;
        $cho = $item->cho;
        $cho_1 = $item->cho_1;
        $cho_2 = $item->cho_2;
        $mineral = $item->mineral;
        $mineral_1 = $item->mineral_1;
        $mineral_2 = $item->mineral_2;
        $mineral_3 = $item->mineral_3;
        $mineral_4 = $item->mineral_4;
    }

    global $user;
    $timestamp = strtotime($form_state['values']['date']);
    $query = db_insert('food_diary')
    ->fields(array(
      'user' => $user->name,
      'uid' => $user->uid,
      'date' => $timestamp,
      'time' => $form_state['values']['time'],
      'type' => $form_state['values']['type'],
      'food_ID' => $food_ID,
      'portion' => $form_state['values']['portion'],
      'food' => $name,
      'calorie' => $calorie,
      'protein' => $protein,
      'fat' => $fat,
      'fat_1' => $fat_1,
      'fat_2' => $fat_2,
      'fat_3' => $fat_3,
      'cho' => $cho,
      'cho_1' => $cho_1,
      'cho_2' => $cho_2,
      'mineral' => $mineral,
      'mineral_1' => $mineral_1,
      'mineral_2' => $mineral_2,
      'mineral_3' => $mineral_3,
      'mineral_4' => $mineral_4,
    ))
    ->execute();

    drupal_set_message(t('Record Added!!!!'));

    //redirect to particular page
    ctools_include('ajax');
    $commands[] = ctools_ajax_command_redirect('diary/list');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
    else {
    $commands = array();
    $commands[]=ajax_command_alert('Please select all fields！');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
}

function form_result_helper($form_state) {
  $type_name = $form_state['values']['type'];
  $food_ID = t('No food Selected');
  $food = '';
  switch ($type_name) {
    case 1 :
       $food = $form_state['values']['type1'];
       $food_ID = $form_state['values']['type1'];
    break;
    case 2 :
        $food = $form_state['values']['type2'];
        $food_ID = $form_state['values']['type2'];
    break;
    case 3 :
        $food = $form_state['values']['type3'];
        $food_ID = $form_state['values']['type3'];
    break;
    case 4 :
        $food = $form_state['values']['type4'];
        $food_ID = $form_state['values']['type4'];
    break;
    case 5 :
        $food = $form_state['values']['type5'];
        $food_ID = $form_state['values']['type5'];
    break;
    case 6 :
        $food = $form_state['values']['type6'];
        $food_ID = $form_state['values']['type6'];
    break;
  }
  return $food_ID;
}

```

# Answer
So your issue is about displaying the system message on the page when an ajax submit is triggered right? So based on Ajax framework, you need to add the ff. to your $commands array like so:

```
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));

```

Hope it works for you.

## EDITED

I investigated more and found noticed that the form AJAX callbacks needs to return the whole form or a part of that form that needs to be updated and I remembered that when forms are submitted using AJAX, it displays the error and/or success messages inside the form because the form itself is the one being rebuilt. This is a simple example:

```
/**
 * Form adddiary_addform.
 */
function adddiary_addform($form, &$form_state) {
  // This wraps the form and will be the target for the submit callback.
  $form['#prefix'] = '<div id="box">';
  $form['#suffix'] = '</div>';

  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Text'),
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => '_adddiary_addform_submit_callback',
      // This targets the <div id="box"> and it's contents.
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Form validation for adddiary_addform.
 */
function adddiary_addform_validate($form, &$form_state) {
  if ($form_state['values']['text'] != 'leo') {
    form_set_error('text', t('It\'s supposed to be leo.'));
  }
}

/**
 * Form submit for adddiary_addform.
 */
function adddiary_addform_submit($form, &$form_state) {
  drupal_set_message('normal form submitted');
  // This will fire if JS is not enabled in the browser.
  // Just might come in handy but you can of course improve it.
  $form_state['redirect'] = 'node';
}

/**
 * Form submit callback for adddiary_addform.
 */
function _adddiary_addform_submit_callback($form, &$form_state) {
  if ($errors = form_get_errors()) {
    // We return the whole form so that the message from form_set_error or
    // drupal_set_message will be included in the form's AJAX content updating.
    return $form;
  }
  else {
    // If we have no errors, then we can redirect now to whatever page you want.
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('node');
    print ajax_render($commands);
    exit;
  }
}

```

Sorry for another edit again, I updated the ff. functions: **adddiary\_addform\_submit** and **\_adddiary\_addform\_submit\_callback**. Please take a look again. I think this would fit your needs now.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: How to send an eMail on specific dates indicated in 3 different date fields?
In 'Add user page' I have added extra fields like:

1. date of orientation
2. out of date
3. anniversary date

I want to remind the users by sending a mail on all 3 of the above mentioned dates, but I am not able to figure out what exactly I need to do.

So far, I have tried with the Date Reminder module and walk through `admin->site configuration->date reminders`. But there I couldn't see any email setup page. I've also gone through a Rules tutorial but I am not getting how to achieve what I want to do.

Is there anybody familiar with the Rules module who has some suggestions about this? Or if some other module is available to do this?

# Answer
> 0 votes
You can perfectly use the Rules module for this. Here are the main steps to do so:

1. You need "a" field related to the "date" your want to do something with (you're fine with that, you already have 3, so repeat what is below for each of the 3 fields).
2. Create a rules **Component** for sending an eMail (specific to the reminder-eMail you want to send).
3. Create a Rule to trigger the Rules component from Step 2, which typically involves some date offset (like "how long ahead should the eMail be eMailed?").

For a sample of step 2 and step 3 above (in Rules export format), refer to my answer to the question about "Rule to store user's last post date and scheduled rule based 30 day reminder".

**Note**: If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.

---
Tags: rules, datetime
---


# Question
Title: Problems enabling clean URLs in apache 2.4
I can't seem to figure out how to enable clean URLs in apache 2.4.6. I have an existing drupal site on ubuntu 12.04 under apache 2.2 and it works just fine. I made a new ubuntu 14.04 server and I managed to get everything installed correctly. I copied over my existing drupal site to the new server and the home page works. No other pages work and I get 404 not found errors because all the links on the site are clean URLs. Could someone point me in the right direction as to how to enable clean URLs? I already enabled the rewrite module... but without success. I can't access my admin or anything on the drupal site on the new server because clean URLs doesn't work...

```
Here is my .htaccess file:

#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
   RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

```

---------------------------here is my vhost file------

```
<VirtualHost *:80>

    ServerName www.religion-new.byu.edu

    ServerAdmin webmaster@localhost
    DocumentRoot /home/administrator/webroot

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName www.religion-new.byu.edu
    ServerAlias religion-new.byu.edu
    ServerAlias byureligion-new.byu.edu
    ServerAlias www.religion-new.byu.edu
    ServerAlias reled-new.byu.edu

    ServerAlias familyhistorylab-new.byu.edu
    ServerAlias www.familyhistorylab-new.byu.edu

    DocumentRoot /home/administrator/webroot/religion-new.byu.edu
    #<Directory />
    #   Options FollowSymlinks
    #   AllowOverride All
    #</Directory>
    #<Directory /home/administrator/webroot/religion.byu.edu/>
    #   Options FollowSymLinks MultiViews
    #   AllowOverride All
    #   Order allow,deny
    #   allow from all
    #</Directory>
    <Directory /home/administrator/webroot/religion-new.byu.edu/public>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerAlias reledresources-new.byu.edu
    ServerAlias www.reledresources-new.byu.edu

    DocumentRoot /home/administrator/webroot/reledresources-new.byu.edu
    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>
    <Directory /home/administrator/webroot/reledresources-new.byu.edu>
        Options FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerAlias calledtoserve.byu.edu
    ServerAlias www.calledtoserve.byu.edu

    DocumentRoot /home/administrator/webroot/calledtoserve.byu.edu
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/administrator/webroot/calledtoserve.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    ServerAlias census-new.byu.edu
    ServerAlias www.census-new.byu.edu

    DocumentRoot /home/administrator/webroot/census-new.byu.edu
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/administrator/webroot/census-new.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
    </Directory>
    <Directory /home/administrator/webroot/census-new.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerAlias globalmormonism-new.byu.edu
    ServerAlias www.globalmormonism-new.byu.edu

    DocumentRoot /home/administrator/webroot/globalmormonism-new.byu.edu
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/administrator/webroot/globalmormonism-new.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>
    <Directory /home/administrator/webroot/globalmormonism-new.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerAlias paftutorial-new.byu.edu
    ServerAlias www.paftutorial-new.byu.edu

    DocumentRoot /home/administrator/webroot/paftutorial-new.byu.edu
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /home/administrator/webroot/paftutorial-new.byu.edu/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot /home/administrator/webroot/religion-new.byu.edu
    ServerName religion-new.byu.edu
    ServerAlias byureligion-new.byu.edu
    ServerAlias www.religion-new.byu.edu

    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>
    <Directory /home/administrator/webroot/religion-new.byu.edu>
        Options FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog /var/log/apache2/error.log

    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerAlias 261.byu.edu
    redirect permanent / http://familyhistorylab.byu.edu/261
</VirtualHost>

<VirtualHost *:80>
    ServerAlias fore.byu.edu
    ServerAlias www.fore.byu.edu
    ServerAlias friendsofreligiouseducation.byu.edu
    ServerAlias www.friendsofreligiouseducation.byu.edu
    redirect permanent / http://religion.byu.edu/fore
</VirtualHost>

```

# Answer
> 4 votes
As mentioned by the others, you'll need to include

```
AllowOverride All

```

In the appropriate `<Directory>` stanza for your Drupal document root. Currently it looks commented out.

Otherwise `.htaccess` won't be read and the rewrite rules won't be applied.

It looks like you have two+ `VirtualHost` definitions with the same `ServerName`, you should also consolidate those to one.

Lastly, ensure `mod_rewrite` is enabled.

e.g:

```
sudo a2enmod rewrite

```

# Answer
> 2 votes
Enable mod\_rewrite for Apache

```
a2enmod rewrite

```

Now edit the `000-default.conf` located at `/etc/apache2/sites-available/`

```
nano /etc/apache2/sites-available/000-default.conf

```

Add the below mentioned lines just under `DocumentRoot /var/www/html`

```
    DocumentRoot /var/www/html
    <Directory /var/www/html>
        AllowOverride All
        Order Allow,Deny
        Allow from all
    </Directory>

```

This will add `AllowOverride` within the default website configuration

Make sure `.htaccess` is in the default web directory!

```
ls /var/www/html/.htaccess

```

If nothing shows after using the above command, download Drupal again and copy the `.htaccess` file to that directory

You're done!

---
Tags: uri
---


# Question
Title: How to import an SQL file and COMPLETELY erase the previous one
I'm having a hard time with buggy modules and need to do a lot of installs, uninstalls and so on.

But even if I uninstall, the modules leave data on the SQL file, and the only way to start from scratch is a new install every time...

How can I save SQL files that will delete ALL older data when imported?

An fresh SQL file that doesn't contain any data of newly installed and uninstalled modules.

I've tried add drop dables and other settings, but it seems that once you install a module...it's too late..it keeps creeping back into the database, sometimes form dependencies also?

# Answer
> 1 votes
You can use drush:

```
drush sql-drop; drush sqlc < path/to/sql/dump/file.sql

```

Understand it will drop your entire Drupal db and the second command will rebuild it from your dump file.

You can create a base dump from:

```
drush sql-dump > path/to/save/dump.sql

```

Here's the link to the drush commands website, select sql from the menu on the left drush commands

---
Tags: database
---


# Question
Title: How to change the number of Administration Views results in the Drupal back end?
How can I change the number of list items (results), using Drupal's back end?

Is it possible to filter how many results, instead of having multiple pages of items? Something to select like 10, 50, 100, 500, ALL? Should be a simple setting, but can't find it.

I've installed Administration Views, but it's a pain since I have to adjust a dozen views, one by one.

# Answer
> 0 votes
To my knowledge, there is no such thing as a "global setting" within Drupal administration (what you call "back end") to set such "how many results".

The only way to do so (assuming you use Drupal 7), is to perform these steps for each of the individual views where you want to set "how many results" you want:

* Use the Views UI to edit the view.
* In the 2nd column, within *Pager*:

+ Use pager: use the options "Display a specified number of items".
    + Pager options: set the "Items per page" to "how many results" you want.

---
Tags: views, users
---


# Question
Title: How to make field label as node reference link?
If I have field label as `Links` and type is a node reference link to `Page Title`. And its displayed like this:

**Links**: Page Title

How to make the label is the link to the node without showing Page Title like this:

Links

# Answer
I propose to do so (if you have a module Display Suite):

Go to ../admin/structure/ds/view\_modes

Add a view mode: name is "label" and entities: "Node"

Then go to ../admin/structure/types/manage/your-content-type/display and on "Custom display settings" tab check the "Label" mode

Now go to ../admin/structure/types/manage/your-content-type/display/label select "Reset" (ds\_reset) Layout, then make visible only the "Read more" and customise it: "Link text" - "See details" for example...

Then on referenced content type select "Rendered entity", and "View mode" - "Label"

Done!
> 2 votes

# Answer
You'll need to alter how it is rendered using a field template file (fieldname.tpl.php).
> 1 votes

---
Tags: entities
---


# Question
Title: Why is Drupal with redis slower than mariadb?
I've got a big Drupal site running Commerce, with cloudflare caching static resources, maybe 20K users or more per day.

MariaDB caches about 500mb worth of queries, we're running freeBSD with php56 and php fastcgi. I'm using the redis PHP extension.

When I turn on redis for all the cache tables, I see the php-fcgi processes start to spike from 7% CPU up to about 35% and load goes through the roof.

Tried it a couple of times, which would minimize cache stampeding, but still I'm somewhat confused as to why redis is performing so poorly.

I've read through redis.conf and the main change I've made is not to snapshot the db to file.

I can connect with redis-cli monitor and see tons of cache data passing through.

Any ideas about what's happening here?

Thanks!

# Answer
This topic should probably be closed, as the Drupal Redis module maintainer, I am taking over the issue in the module official issue tracker, specific questions are pending there, and a few micro-optimizations have already been done since this question was opened.

For everyone that would help us or need support, please consider participating to https://www.drupal.org/node/2550275 \- this would be great help.

Thanks in advance to everyone that will give us a few minutes to solve this and improve the module.
> 3 votes

---
Tags: commerce, caching, database
---


# Question
Title: Whats causing this garbled text below my pages?
Hoping someone might have experienced this and know the culprit code. This keeps appearing below some pages intermittently. Only on logged in members.

# Answer
You could try searching for part of the string in your codebase. If you have SSH access then you could run something like:

```
cd /path/to/document/root
grep -r "W!b\EU6" .

```

Otherwise if the file is on you local computer then you could use any search tool to look for "W!b\EU6" (those particular characters are from the last line of your screenshot.

Note that it may not be in the codebase. It could be in the database or could be the output of some function such as an encoding function. You could check if it's in the database by dumping the database to a .sql file (not compressed) and searching in that.

If you find it and are not sure what to do with the results then paste them here for further advice.
> 1 votes

---
Tags: users
---


# Question
Title: How can I display 2 or more fields horizontally?
In my content type I have several fields. I want to display two or more of them horizontally.

Here is an example:

```
 Auto
+------------+
|  INPUT     |
+------------+

```

```
 Ascensore
+------------+
|  INPUT     |
+------------+

```

```
Nome                Cognome
+------------+          +------------+
|  INPUT     |          |  INPUT     |
+------------+          +------------+

```

```
Città
+------------+
|  INPUT     |
+------------+

```

How can I do this?

# Answer
> 0 votes
By using the Display Suite module you should be able to do this.

By default Drupal core wraps fields in multiple HTML elements. Display Suite allows you to override this markup via the user interface by using field templates. You can add CSS classes to the fields and start styling them in your CSS.

For more details, refer to the Community Documentation about Control markup with field templates.

# Answer
> 0 votes
I would use fieldgroup to wrap a container with a specific class around the "Nome" and "Conome" fields, and then add some css to the theme to float the children of the container with that class.

# Answer
> 0 votes
With css, there are 2 ways you can do this:

```
.Nome { float: left; }

```

SEE EXAMPLE

OR

```
.Nome {display: inline-block; }
.Cognome {display: inline-block; }

```

SEE EXAMPLE

If you want to move cognome more to the right, then add, for example:

```
.cognome { position: relative; left: 100px; }

```

When its relative, its 100px away from the left of Nome, in case you are wondering why I'm using left instead of right (counter intuitive)

---
Tags: entities
---