# Question
Title: How i can add a new line in my code here?
HI guys go to THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE and help how to separate that text in 2 lines

```
 $form['kkkkkk'] = array(
          '#type'          => 'textfield',
          '#title'         => t('blablabla'),
          '#default_value' => variable_get('kkkkkkkk', ''),
          '#description'   => t('sdakgbflabfgdsbf "THE TEXT THAT FOLLOWS I WANT IT IN NEW LINE" fdghhtrjgvfnbhsgf.'),
          '#required'      => TRUE,
          '#size'          => 10,
          '#required'      => TRUE,
        );

```

# Answer
There are two options (simplified code example):

1. `$description = t('Foo.<br>Bar.');` (recommended)
2. `$description = t('Foo.') . '<br>' . t('Bar.');`

The `<br>` tag causes a line break in HTML. Both options give the same result technically. The difference is in what translators can do with it.

Option 1 treats the sentence as a unity and gives translators more flexibility. For instance, if the French translation needs to change the word order (`'Barre.<br>Fou.'`), that's possible. However the French translator would also have the possibility to leave out the line break completely.

Option 2 is more rigid. A translator could never control which part comes before the line break and which part comes after. The translator may not even know that the sentences "Foo." and "Bar." will be combined into a single page element, because they show up as separate strings in the translation interface.
> 3 votes

---
Tags: 7, forms
---


# Question
Title: How can I send emails with drupal_mail() and hook_mail()?
I have this code for send a simple notification email.

```
function mymodule_commerce_checkout_complete($order){
  $buyer = user_load($order->uid);
  if(in_array('wholesale', $buyer->roles)){
    $params['buyer'] = $buyer;
    $params['order'] = $order;
    drupal_mail('commerce_mayoreo_workflow', 'new_order_mayoreo', 'myemail@gmail.com', user_preferred_language($buyer), $params);
  }
}

```

This is the `hook_mail()` implementation.

```
function mymodule_mail($key, &$message, $params){
  switch ($key) {
    case 'new_order_mayoreo':
      $langcode = $message['language']->language;
      $message['subject'] = t('New Quote request', array('langcode' => $langcode));
      $message['body'][] = t("New Quote request has been created\n\nYou can download the CSV format of the request here:\n\nhttp://bbheperfumes.com/download-order-csv/@order_id",array('@order_id' => $params['order']->order_id), array('langcode' => $langcode));
      break;
  }

}

```

It's not sending the email, and Im checking in recent log entries and there is not anything about a failed delivery, anything about system tried to send a mail.

I could not figure out why it's not sending the email, so I want to ask if mimemail has something to do with this issue?

I just have the MimeMailSystem in the 2 first select lists that are displayed in the configs of mail system.

By the way, I am using a fresh install of Commerce Kickstart.

# Answer
> 1 votes
Debugging such kind of eMail issues can sometimes be challenging.

Consider the 3 Modules to Help you Debug Emails in Drupal 7. Here is a quote from it:

> Problems can exist in multiple areas; like Drupal itself or your mail server. So when an email issue arises you first need to check and see if Drupal is generating emails and then make sure your mail server is sending the emails. Luckily in Drupal there are a few modules that can lessen the pain of debugging emails.

These are the 3 modules/steps mentioned on that link:

PS: Debugging Drupal emails contains another checklist with 8 possible reasons about what may be the problem.

---
Tags: 7, mimemail
---


# Question
Title: Submit values and redirect user from to external URL
What is the equivalence of:

```
   <form action="https://paypaad.bankpasargad.com/PaymentController" method="POST">
            <input type="hidden" name="content" value='<?php echo $xml ?>' />
            <input type="hidden" name="sign" value="<?php echo $sign ?>" />
            <input type="submit" value="send" name="submit" />
   </form>

```

in Drupal 7 ?

I already use following code in my form submit handler, but it doesn't work:

```
function Chargingform_nameform_submit($form, &$form_state)
   {
    $options = array();
    $options = array(
        'method' => 'POST',
        'xml' => $form_state['values']['xml'],
        'sign' => $form_state['values']['sign'],
        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
    );

   $url = 'https://paypaad.bankpasargad.com/PaymentController';
   $response = drupal_http_request($url, $options);
}

```

How I can submit XML, sign to URL and redirect user to that URL at the same time?

This is my code:

```
function Chargingform_nameform() {
    $xml = 'PHP Handbook30000130000This is good book.MySQL Handbook25000250000This is a good book too.';
    // Get sing
    $sign ='ewtnXYRWPSalHhna9hgO+Kc0W9Z8JBUeG1FkcKPvZL5w2s588c0/B9r';

    $form['xml'] = array(
       '#title' => t('xml'),
       '#type' =>'hidden',
       '#value'=>$xml,
    );
    $form['sign'] = array(
       '#title' => t('sign'),
       '#type' =>'hidden',
       '#value'=>$sign,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
    );
    return $form;
}

function Chargingform_nameform_submit($form, &$form_state) {
  $options = array();
  $options = array(
    'method' => 'POST',
    'xml' => $form_state['values']['xml'],
    'sign' => $form_state['values']['sign'],
  );
  $url = 'https//:url';
  $response = drupal_http_request($url, $options);
}

```

I don't know really how to manage it in JavaScript.

Any suggestions?

# Answer
> 1 votes
You can generate form like that using `'#type' => 'hidden'` form API fields, and using `'#action'` on form itself.

If you want to submit values to Drupal and then redirect user to external site, you cannot do it directly. HTTP protocol does not allow you to send anything from your server to another "on behalf" of your user. The only way to do it is:

1. Get data from user
2. Save data, process it, do whatever you need
3. Generate form with `action` pointing to external service (usually payment gateway), and data required by it in hidden fields
4. Use JavaScript to make user's browser submit it.

If you are trying to do it using `drupal_http_request`, it's your server that starts payment procedure, not client's browser - certainly not what you want. And payment server will not allow switching procedure between different computers - it would be a security risk to allow that. If you could hand your session on payment server to your user, what would prevent attacker from doing the same (but with his bank account, not yours)? I know that's simplified explanation - for more details you may try to ask on Information Security.

# Answer
> 0 votes
It is not a good idea to redirect a POST action. Even if you do, it is not easy or guaranteed to be stable.

If you want to do it, you will have to write custom code to issue a 307 redirect. It won't work with Drupal's redirect functions.

https://softwareengineering.stackexchange.com/a/99966

---
Tags: 7, redirection, forms
---


# Question
Title: How to form_later the user profile form to only allow 1 role to be assigned/removed
I want to restict my site editors ( a role ) to only be able to select/deselect the role 'subscriber' and not be able to meddle with the other role assignments. I have tried the following to remove the other roles :

```
case 'user_profile_form':
  global $user;
  if(in_array('site editor', $user->roles)  && !in_array('administrator', $user->roles)) {
    unset($form['account']['roles']['#options']['3']);  // administrator
    unset($form['account']['roles']['#options']['4']);  // site editor
  }

```

However this has the effect of both hiding the checkboxes and un-assigning the roles. I want any existing assignments to these roles to persist.

Your help appreciated.

# Answer
> 0 votes
Roles are removed because when the form is submitted those roles are missing (and thus unchecked). You can hide those options instead:

```
$form['account']['roles']['3'] = array(
  '#disabled' => TRUE,
  '#attributes' => array('class' => array('hidden'))
);

```

And some CSS `.hidden { display: none; }` or something.

> In D7+, form\_process\_checkboxes() and form\_process\_radios() already support you in doing so by allowing for partial sub-element pre-definitions read more

# Answer
> 0 votes
Instead of writing your own code, you may just want to use the Role Assign module:

https://www.drupal.org/project/roleassign

---
Tags: users, forms
---


# Question
Title: How to disable access to file page (view display mode = full)?
I want to **disable access** to the view display page of file by url like ***file/fid***.

What's the good way for this? I have tried to use the hook\_node\_view() but it not called for the files.

# Answer
> 2 votes
I have finally used the RABBIT HOLE module, it contains a sub-module for managing **file\_entity**! :)

# Answer
> 0 votes
You can do this by using below ways :

1. Unpublish your node
2. Node Page Disable module

> Allows easy UI access and disabling of the path /node when not used. This was inspired by a security consideration in the Production Check Module.

3. Restrict node page view

> Have you ever used a slideshow nodetype that you need to be published but don't want the node be accessible by itself using then node/XXX path? This module is for you!
>
> With this module you can disable direct access to node pages (node/XXX) based on nodetypes and permissions.
>
> Enable the module and don't forget to configure your permissions.

---
Tags: 7, files, media, entities
---


# Question
Title: webform select options validation unique
I need to prevent two different users from choosing the same option from a webform select options component. In the validation only validation required available, no unique validation.

For example: my select contains the following: 1|1, 2|2, 3|3. AnnonUser1 chooses option 2. AnnonUser2 should be presented with 1|1 and 3|3.

How can I validate unique for this select options component. I tried webform validation, but it does not provide unique validation for select options component as well.

# Answer
You can use a select list with a pre-loaded option list. In that "preload" callback you can alter available options.

Define a custom option list:

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

  $items['exclusive'] = array(
    'title' => t('Exclusive options'),
    'options callback' => 'mymodule_webform_options_exclusive',
  );

  return $items;
}

```

This callback is called every time the form is displayed, we can alter options here based on previous submissions:

```
function mymodule_webform_options_exclusive() {
  $default_options = array("One" => 1, "Two" => 2, "Three" => 3);
  $available_values = mymodule_webform_available_values(5); // nid of the webform

  return array_diff($default_options, $available_values);
}

function mymodule_webform_available_values($nid) {
  $submissions = webform_get_submissions(array("nid" => $nid));

  // get all the options values that were already submitted
  $values = array_values(array_map(function($submission) {
    return $submission->data[1][0]; // 1 == index of the field in the form
  }, $submissions));

  return $values;
}

```

Two things are hard-coded here: nid of the webform (5 here) and the index of the select widget (1 here). It might be possible to avoid hard-coding stuff, good luck!
> 1 votes

# Answer
You will almost definitely have to write some custom code to do what you are describing. Start by Googling for "drupal webform dynamic select". There are lots articles that should give you an idea where to start.
> 0 votes

# Answer
```
var option_value_order = {'volvo', 'saab', 'mercedes'};
var option_display_strings = new Array();
option_display_strings['volvo'] = 'Volvo';
//...

// Assume each of the selects' ID value is "select_1", "select_2" instead of "1", "2"
function redraw(selectNum) {
    var selectId = "select_" + selectNum;
    var s = document.getElementById(selectId);
    s.options.length = 0; // empty out
    var next = 0;
    for (var i = 0; i < option_value_order.length; i++) {
        var skip = 0;
        for (var select_index = 0; select_index < selectNum; select_index++) {
            if (document.getElementById("select_"+select_index).selected == i)
                skip = 1;
            if (skip == 0) {
                var o = option_value_order[i];
                s.options[next] = o;
                // Don't recall how to set value different from option display,
                // using option_display_strings[o]
                next++;
            }
        }
    }
}

var total_selects = 2;

function change_later_selects(s) {
    var select_num = find_number(s.id); "this returns number 2 for "select_2" - homework
    for (var i = select_num + 1; i <= total_selects; i++) {
        redraw(i);
    }
}

```

and then the HTML code

```
<select id="select_2" onchange="change_later_selects(this);">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

```
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: db_query not returning anything (or empty) - drupal 7
I am trying to perform a `db_query` but am unable to do so.

The query I am trying to perform is very simple, but to make things even simpler, the following query does not even work for me:

```
$result = db_query('SELECT name FROM users WHERE uid = 1');

```

and if I do:

```
echo (string)$result->name;

```

nothing is displayed.

Does anyone know what could be causing this?

Edit - Updated with new code:

```
define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost";
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$result = db_query('SELECT OFFICE_ID FROM {OFFICE}');
$counter = 0;
foreach($result as $record) {
  $counter = $counter + 1;
  print $record->office_id;
}
print $counter;

```

Nothing will be printed, but at the end of the loop, the number of loops performed is the same as the number of rows returned from a direct query on the DB itself.

# Answer
The return from `db_query()` is a resource that you can iterate over, it's never a single value.

The way to get a single field from a query is with the `fetchField()` method:

```
$result = db_query('SELECT name FROM {users} WHERE uid = 1')->fetchField();

```

If you've got more than one result then you can iterate over it like so:

```
foreach ($result as $row) {
  // Do something with $row...
}

```

or, you can make use of one of the helper methods to get data directly from the query into a local variable. These include:

* `fetchObject()`

> Fetches the next row and returns it as an object.
* `fetchAllAssoc()`

> Returns the result set as an associative array keyed by the given field.
* `fetchAllKeyed()`

> Returns the entire result set as a single associative array.
* `fetchAssoc()`

> Fetches the next row and returns it as an associative array.
* `fetchCol()`

> Returns an entire single column of a result set as an indexed array.
* `fetchField()`

> Returns a single field from the next record of a result set.
> 9 votes

# Answer
The answer to my problem is very weird and I have no idea why. But to solve it, all I had to do was change the query from using "single-quotes" to using "double-quotes" -

I used:

```
$result = db_query("SELECT OFFICE_ID FROM {OFFICE}");

```

Instead of:

```
$result = db_query('SELECT OFFICE_ID FROM {OFFICE}');

```

I hope someone could help me in finding the cause.
> 3 votes

# Answer
You need to execute the query. Try:

```
$result = db_query('SELECT office_id FROM {office}')->fetchAll();
foreach($result as $record) {
  print $record->office_id;
}

```

Also, are your table and column names really all uppercase?
> 0 votes

# Answer
The comparison table at *PHP Everywhere* has a row, "Common string constants," which states that PHP string constants with codes in them are not evaluated if they are in single quotes, but only if in double quotes. I wonder if db\_query needs to do some evaluation of the SQL string you passed to it that cannot take place if double quotes are used. If that's the case, it could explain your situation.

If that is the issue, then the proper answer to your question would be a link to the page of the PHP manual that explains it.
> 0 votes

---
Tags: 7, database
---


# Question
Title: Properly bootstrap drupal for standalone PHP file?
This is what I have right now:

```
<?php
    define('DRUPAL_ROOT', '/var/www/clients/client1/web15/web');
    include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
//  drupal_flush_all_caches();

    $users = views_get_view_result('userlist', 'uid_list');
    $i = 0;
    foreach ($users as $user) {
        $filename = 'sites/default/files/generated_pdfs/individual_pdf_report_' . $user->uid . '.pdf';
        generate_employee_pdf($user->uid, $filename);
        error_log('Generated ' . $filepath);
        $i++;
    }
    // create object
    $zip = new ZipArchive();
    // open archive
    if ($zip->open("sites/default/files/generated_zips/individual-reports.zip", ZIPARCHIVE::CREATE) !== TRUE) {
        die ("Could not open archive");
    }
    // initialize an iterator
    // pass it the directory to be processed
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("sites/default/files/generated_pdfs/"));
    // iterate over the directory
    // add each file found to the archive
    foreach ($iterator as $key=>$value) {
        $zip->addFile(realpath($key), $value->getFilename()) or die ("ERROR: Could not add file: $key");
    }
    // close and save archive
    $zip->close();
?>

```

I'm getting a bunch of errors from the above when run standalone. Works fine in my module. Some of the errors are:

```
Warning: Invalid argument supplied for foreach() in drupal_depth_first_search() (line 56 of /var/www/clients/client1/web15/web/includes/graph.inc).
Warning: Invalid argument supplied for foreach() in _module_build_dependencies() (line 229 of /var/www/clients/client1/web15/web/includes/module.inc).
Warning: include_once(sites/all/modules/views_bulk_operations/actions/archive.action.inc): failed to open stream: No such file or directory in views_bulk_operations_load_action_includes() (line 56 of /var/www/clients/client1/web15/web/sites/all/modules/views_bulk_operations/views_bulk_operations.module).

```

# Answer
By far the easiest way to manage the bootstrap is to use drush php-script, alias scr.

file.php:

```
<?php
echo l('Link', 'path');

```

Cli:

```
drush @alias scr file.php

```

Output:

```
<a href="/path">Link</a>

```

This way you need to deal with nothing with regard to the bootstrap, drush will solve it entirely for you, and gives you the ability to use it easily across sites thanks to aliases. (Might even work on remote sites, though I haven't tried that)
> 14 votes

# Answer
your standalone Drupal 7 bootstrap is not quite right.

Try this:

```
/**
 * Do not let execute this file from http request
 */
if (isset($_SERVER['REMOTE_ADDR'])) {
  print "...";
  exit(1);
}

/**
 * Initialize Drupal
 */
define('DRUPAL_ROOT', '/var/www/clients/client1/web15/web');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '...'; // include required module files to work with here

drupal_override_server_variables(array('url' => 'http://www.example.com/batch.php')); // trick drupal to do bootstrap
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

set_time_limit(4600); // adjust for your needs
ini_set('memory_limit', '3524M'); // adjust for your needs

```

Hope this helps.
> 11 votes

# Answer
this is enough:

```
set_include_path(get_include_path() . PATH_SEPARATOR .'/path/to/drupal/root/');
define('DRUPAL_ROOT', '/path/to/drupal/root/');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 3 votes

# Answer
The last error

> Warning: include\_once(sites/all/modules/views\_bulk\_operations/actions/archive.action.inc): failed to open stream: No such file or directory in views\_bulk\_operations\_load\_action\_includes() (line 56 of /var/www/clients/client1/web15/web/sites/all/modules/views\_bulk\_operations/views\_bulk\_operations.module).

is a bug in VBO. views\_bulk\_operations\_load\_action\_includes() does not use DRUPAL\_ROOT when using include\_once. I would file a bug and fix it in VBO.

The other error (the 2 are related to each other) might be related to \_system\_rebuild\_module\_data() not using DRUPAL\_ROOT when accessing modules .info file. I would put break points in system\_rebuild\_module\_data() for the $modules variable and see if you can pin point it. Once again file a bug with drupal core as I don't see this issue in the issue queue.

Good luck!
> 0 votes

---
Tags: 7, bootstrapping
---


title: Drush for drupal 8

text:
# Question
Title: Drush for drupal 8
i upgraded drush to 7.0-dev and within my drupal 8 folder drush status throws error

*Drush command terminated abnormally due to an unrecoverable error. Error: Call to undefined function drupal\_bootstrap() in /usr/local/Cellar/drush/HEAD/libexec/includes/bootstrap.inc, line 836*

# Answer
> 3 votes
What version of Drupal 8 are you using? Your Drush and Drupal versions must track closely, so if you are using today's HEAD of Drush 7, you should use today's HEAD of d8. If you are using d8-beta10, you should use Drush 7.0-rc2, and if you are using d8-beta9, you should use Drush 7.0-rc1.

**Update**

Just tried this with today's HEAD of Drush 7: `drush qd dev-d8-test --core=drupal-8.0.x --db-url='mysql://mysqluser@localhost:/devd8test'`

Worked great. Adjust db credentials to match your needs, of course.

---
Tags: drush
---


# Question
Title: How can I draw a donut chart based on the number of specific fields on a form?
Is there a module that can count results in a form, and then draw a donut chart like the following picture?

Note that I'm actually using content types and the Views module to create such forms. So I'm not using the commonly known Webform module to create them.

# Answer
Yes it's possible to create such charts (which are called **Donut Charts**) similar to the sample in the Interactive Google Charts gallery (move your mouse pointer over any of the slices in that sample to see the special effects it comes with also). Such Donut chart is actually a Pie chart with a hole in the center, which can be created with the `pieHole` option.

Below are some more details to get you going ...

**Option 1** (without using WebForm):

Use the Comparison of charting modules for potential alternatives to consider.

Some of the modules mentioned there:

**Option 2** (Using WebForm):

There are actually 2 alternatives to pick from:

* Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
* Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, use the Charts module to actually create the charts (module dependency).

**Remarks**

The **license** that comes with the charting library (engine) that is used in the selected Charting module, should be considered also. Some of the typical items to consider are:

* Possible privacy concerns.
* Flash based libraries (as they were also used in the D6 version of Charts) should be avoided if charts are to be displayed on mobile devices.
* Google libraries require a working internet connection (not always available in local DEV environments ...).
* Not all libraries are free of charge (some come with commercial licenses).

Disclosure: I'm a (co-) maintainer of Charts and Chart, and the author of that Comparison.
> 2 votes

---
Tags: views, 7, forms, charts
---


# Question
Title: Autopopulate a node with the content of a menu
supose i have a site with three nodes of basic page type called "element 1", "element 2" and "element 3". I want to create a menu with the following structure:
-elements
--element 1
--element 2
--element 3
Is there any way to generate a view for the "elements" node containing the children nodes from the menu, a module to do this automatically or somthing like that. Sorry if that may be an obvious question, but im relatively new in drupal, also pardon my english

# Answer
> 0 votes
* Create a new View, Block, Content -\> 'Basic Page', fields

once the main Views UI opens you can modify as desired - by default, this will create a view of Titles that act as links in a block you can place wherever you like. You can remove the Title (title) by clicking on the Title Field, and un-click 'Create a label'

---
Tags: views, routes
---


# Question
Title: "Article" html tag in body of Basic Page content type: what template is rendering this?
When creating a basic page, then previewing that page, here is a sample mark-up from the browser:

```
    <article typeof="foaf:Document" about="/?q=who-we-are" class="node-30 node node-page view-mode-full clearfix">
  <div class="field field-name-body field-type-text-with-summary field-label-hidden"><div class="field-items"><div property="content:encoded" class="field-item even"><ul><li><img src="http://drupal-dev.ngi-dev/sites/default/files/default.jpg"><p>Name</p>
<p>iOS & Android Developer</p>
</li>
</ul></div></div></div>
</article>

```

I had pasted the basic html ul/li/dl etc in the source code view using the ckeditor, saved then viewed the page in a browser.

Don't know why a `<p>` tag was wrapped around content within established html tags but my main question is where to find what template that is adding the `<article>` tag as well as the nested structure of the extra `<div>` tags

I've looked in the template files within modules and Zen (my parent theme) but I haven't found anything yet. Where is the `<article>` tag being generated? I think that would help me find the full mark-up.

# Answer
> 0 votes
I always clean that part in node.tpl.php, that's the default template for nodes if you don't have one for each content type. So i would try changing the article tag for a div tag on that file. You can make sure that it works cleaning all caches from your Drupal

---
Tags: theming
---


title: How to find meta tag source?

text:
# Question
Title: How to find meta tag source?
I have a site where the conditional,

```
<!--[if IE]><![endif]-->
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

```

shows in the header, but I can't figure out where it's coming from. I've checked the template.php, .htaccess, html.tpl.php, common.inc, an everywhere else i can think of. Any ideas of where this is hiding, or how I can find it would be greatly appreciated.

# Answer
> 0 votes
I was going to check the theme for you but it looks like that's a private theme so I'll try to outline some other places you can check.

The most common places you would find it are `html.tpl.php` and `template.php` but it sounds like you've covered those. If it's not in `html.tpl.php` then it is likely being added with `drupal_add_html_head()`.

Other places to look outside of the ones you've already checked could be in your `/modules` folder - looking for any custom modules that came with the theme. If the tag is being added with `drupal_add_html_head()` then it could be in a custom module.

If not in `template.php`, check if the theme uses individual files for preprocess functions. ie look for `html.preprocess.inc` or something similar.

The theme might have some `*.inc` files for random features - you can check those as well.

A quick grep of your theme folder for `drupal_add_html_head` or `X-UA-Compatible` would likely get you your answer quickly.

# Answer
> 0 votes
Grep your codebase for `drupal_add_html_head()` calls or "X-UA-Compatible" text. This can be inside any module. If you still don't find it, and you have the PHP filter module enabled, you might need to search the `field_data_body` table for calls in PHP code stored in the DB.

---
Tags: 7, meta-tags
---


# Question
Title: How to debug "undefined" 404 error in console on front page
I'm getting a strange 404 error on the front page only, which seems to be causing some other issues for me. I'm hopeful if I solve this it will take care of those, too.

On the front page only, when I load the console, I see the following error:

I am not sure what would be causing this as the page appears to load correctly and it isn't giving much of a clue as to what it is trying to load.

How do I debug from this point?

# Answer
> 1 votes
Thanks for the tips Clive and Beebee!

By trial and error I disabled or removed various components until I found one that made the error go away. In this case it seems to be a problem with Flexslider and Views that was used in a Views block -- I haven't solved it yet but have isolated it at least!

**UPDATE:** It seems to be a bug related to the navigation in the Flexslider module (Views integration). If I set the Flexslider style not to include navigation, it is fine.

---
Tags: debugging
---


# Question
Title: Can't get the module quick edit to work (have some error screenshots)
I've successfully installed the module Quick Edit that let's you edit nodes in-place (in a similar way to Panels in-place editor) and might save time.

After installing the module I've yet to see any **quick edit button** (img1) So I tried to check permissions and they were seem fine, and I'm the admin (img2). Than I tried to clear cache and again there was no such button, so I went to ran **cron** and some errors appeared (img3+4).

# Answer
> 3 votes
On the quick edit drupal page it says,

> Works with any Drupal 7 site (requires the Entity API, CTools and Libraries API (\>=2) modules, plus the **Underscore.js** (\>=1.5) and **Backbone.js** (\>=1.0) JavaScript libraries). If in-place WYSIWYG editing is desired, you must also use the CKEditor module.

You need to download and install the libraries module

Then you need to create a libraries folder in `sites/all` folder. So it looks like this `sites/all/libraries`

Then you need to download the Backbone.js and Underscore.js and put them inside the `sites/all/libraries` folder.

I also see you have some other errors, which is not Quick Edit related. Must be from some other module you installed.

What the errors are saying is that you need to create a custom CK editor http://ckeditor.com/builder and make sure you include the **Shared Space** and **Source Dialog** plugins. So under avalable plugins (right column), scroll and find these plugins and click on the left arrow to include them on your CK editor build. Then scroll all the way down, checkmark the I agree to terms box and click on Download. Then you need unzip and put the ckeditor folder in your `sites/all/modules/ckeditor/` folder. So it will look like this `sites/all/modules/ckeditor/ckeditor`

# Answer
> 1 votes
Install the the Backbone library.

If you have not installed the Libraries API module, do so first.

Then in your libraries folder (e.g. `sites/all/libraries/`) install the Backbone Javascript library and the Underscore Javascript library.

---
Tags: nodes, entities
---


# Question
Title: Make a folder inside the drupal installation public
I am trying to make a folder inside my Drupal installation and make it public, which means in my HostGator account I have a folder `public_html`, which has Drupal installed in it; and I have created a folder called `test` and am trying to access it like,

mydomain.com/test

But I am getting mydomain's maintenance message (this is because my primary domain is in maintenance mode, so no issues there)

```
#
# 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)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  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

  # 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} !^www\. [NC]
  # RewriteRule ^ http://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://%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]

  # Various rewrite rules.

  # 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>

```

# Answer
> 2 votes
The trick is to modify `.htaccess` to ignore specific files/folders.

Set your `.htaccess` in your drupal directory to the following

```
RewriteCond %{REQUEST_URI} "/techiequickie/"
RewriteRule (.*) $1 [L]

```

And put this code right below

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

```

In your Drupal .htaccess

Make sure your htaccess looks like the f0llowing,

```
    #
    # 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)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
      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
      RewriteCond %{REQUEST_URI} "/techiequickie/"
      RewriteRule (.*) $1 [L]

      # 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} !^www\. [NC]
      # RewriteRule ^ http://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://%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]

      # Various rewrite rules.

      # 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>

```

# Answer
> 0 votes
If the folder name isn't critical, folder under files e.g. mydomain.com/sites/default/files/test is also possible. No further adjustments needed.

# Answer
> 0 votes
1) Add the following linein the Drupal7 .htaccess file (around line 112):

```
RewriteCond %{REQUEST_URI} !^YOUR_FOLDER_HERE

```

The result should be similar to:

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

```

2) then create a .htaccess on your custom folder. Add/adjust the following rules

```
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /producton/
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
</IfModule>

```

With these settings you can install WordPress, CMSMS and probably many others webappp inside a "Drupal environment".

---
Tags: users
---


title: How to create menu when dynamic routes

text:
# Question
Title: How to create menu when dynamic routes
This link https://www.drupal.org/node/2122201 suggest us to make use of route\_callbacks when we are using dynamic routes.Can someone tell me how to make use of this route name in \*.links.menu.yml file to make menu? The problem is when we are returning $route\_collection in the routes() function then it must be containing multiple routes then how to generate menu for any particular dynamic route. I did a search inside menu\_tree table in the database and find out that no menu has been created with help of dynamic routes so I am beginning to think whether this is possible or not. If it is not possible that what is the possible solution?

# Answer
You need a derivative plugin, see views module for an example, it dynamically generates menu links for views configured to have a menu entry
> 1 votes

---
Tags: 8, routes, navigation
---


# Question
Title: Why are my custom email messages sent without styling?
I have a Commerce Kickstart website working, everything works fine. Recently I wanted to create another notification email once I give an order certain status. Well I created the rule, also created the message (actually I cloned the Commerce Order: order confirmation message)

All the emails sent from my commerce kickstart are with the right styling, they show good, but only the custom message I created does not have any styling, it is sent in html but does not have styling.

I do not understand why my custom message is sent without styles, I copied the styles and html that is in the Commerce Order: order confirmation message, but all the other messages have styles, I could not figure out what's going on.

# Answer
> 2 votes
I FINALLY found the solution to this problem, commerce kickstart is theming the emails using the mail.css provided for the mime mail module, this file is located in the Omega Kickstart theme that was the one Im using, for some reason my custom messages were not styled using that file, so I did some of research and found this post where they explain how to theme mime mail emails, and they reffer to an issue about using different admin theme than your default theme so they suggest add the mail.css file to all your themes folders...

Well so what I did was to make a subtheme of the commerce kickstart admin theme and the omeka kickstart theme, then I placed the mail.css file in the css/ folder of both, now my custom messages sent with message notify from rules are sent with the correct styling!!

Thank you!

# Answer
> 1 votes
Excerpt from Rich Email Notifications:

> To handle the email notifications, Commerce Kickstart has integrated the Messages module and the Mime mail module.

Maybe your issue is caused by what is mentioned on that same page, i.e. (bold markup added here):

> Message Notify allows messages to be sent as emails using Rules, which Commerce Kickstart happily enables by default. Admittedly, **this functionality is a bit hidden from the average user** and it's in the long term goals to expose more of this functionality to the user interface in a more understandable way.

---
Tags: 7, commerce, emails
---


# Question
Title: How to improve the clarity of hierarchical taxonomy terms in edit forms?
I have a hierarchical taxonomy vocab. When I go to -say- a node edit form that uses this, with checkboxes, the hierarchy is represented simply by prepending a `-` for every level of depth. This really does not represent the hierarchy very well - it's hard to see, and ideally it would be semantic (nested list), or at least add a class on the container elements like `taxonomy-level-N`.

Is there a module for this? Or some other hack?

# Answer
> 0 votes
One way you could approach this is to use select boxes with an 'add more items' button.

I use Simple Hierarchical Select for single value selections in a taxonomy with levels, but there's no reason you can't use it for multiple selections.

If that module doesn't make an 'add more items' button pop up then put the field in a Field Collection, yes even by itself. I know for a fact that you can have multiples of those.

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


title: Two field multiple values

text:
# Question
Title: Two field multiple values
Not sure if this is the correct terminology to explain my question, but I have a client on Drupal 7. My client organization is related to another organization that possibly has a Drupal 8 site. There is a content type that is very similar to both organizations, but the other organization has what seems to be a field group of two fields that allows for multiples in the group, as opposed to the fields. I have used field grouping quite frequently in Drupal 7, but can I duplicate that function?

# Answer
Sounds like the field collection module would fit your needs perfectly, however that doesn't have a Drupal 8 version yet so it's hard to know what the Drupal 8 site is using to do this.

For Drupal 8 there is a sandbox version of the field collection module however I'm not sure how stable it is.

Another possibility is that they have created a custom field for their site that is a combination of multiple elements.

If you want any sort of compatibility with the two sites' data the I would suggest asking them how they have implemented theirs and use that option for your Drupal 7 site.
> 0 votes

---
Tags: entities
---


# Question
Title: On node edit form, how to edit field from a referenced entity?
I've got a master entity (node) that users edit, and I've got an entity reference on it. I'd like to be able to edit a field on the referenced entity on that master referencing entity's edit form.

Is there a module for this? Or can somebody just give me a general sense of a good way to accomplish this?

I know I can create a custom form element with hook\_form\_alter, then use a form\_submit function, and then use entity\_metadata\_wrapper to load and save values.

That seems cumbersome, is there a better way to do this?

# Answer
You can use https://www.drupal.org/project/references\_dialog or https://www.drupal.org/project/inline\_entity\_form.

The first one will load the referenced entity in a popup, the other will show it as part of the original form.
> 0 votes

---
Tags: entities
---


# Question
Title: How to make content translation available for front page?
On my front page I have a language selector (English / French). The default language is French. The translation works only in the content of page (in the views) i want make the translation work in the front page.

Can someone help me please to do this? I have tried several times but could not get it to work ...

# Answer
> 1 votes
The relative URL to display as the front page is specified within admin/config/system/site-information . If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

> The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.

And these are the specific steps required to make a variable multilangual (mentioned on that community page):

1. Enable the Variable translation module included with the Internationalization package
2. Go to Administration \> Configuration \> Regional and language \> Multilingual settings
3. Click on the Variables tab
4. Select the variables that will be multilingual
5. Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".

Finally, this is what remains to be done (another quote from that same page):

> Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...

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


# Question
Title: What is the recommendation for mapping state?
The configuration in D8 is nicely mapped in config schema file so any developer knows what configuration changes can be made. But what about state? Is there a recommended way to map state? Or is it the same situation as with variables in D7?

Would it be a good idea to store default values for state as part of the config schema under some specific key, like "state"? Althoguh that would mean dependency on config(factory) in different places within the code.

# Answer
There is no mapping/schema for state nor for the underlying key value system.

This question can't be "answered" other than saying "None". Anything else would need to be in the form of a feature request and I'm not convinced this makes sense.
> 2 votes

---
Tags: 8, configuration
---


title: Remove links under main page

text:
# Question
Title: Remove links under main page
When I add a new 'Basic Page' or an 'Article', a link to the Home page appears under the 'Main Menu' and I have no idea how to remove it.

How can I remove these links?

# Answer
These links are navigation links, so called "breadcrumbs". They inform the site visitors where they are on the site.

You are using the Bartik core theme -- take a look at `/sites/themes/bartik/templates` -- there is a file `page.tpl.php`. On about line 176 the following code

```
<?php if ($breadcrumb): ?>
  <div id="breadcrumb"><?php print $breadcrumb; ?></div>
<?php endif; ?>

```

renders these breadcrumbs.

You *could* comment or remove these lines to avoid rendering navigation links. If you make changes to theme files remember to flush cache to see the changes.

But a better solution would be to create a Bartik subtheme (because each time you update the Drupal core, all your changes made to this file will be overridden, I would also not recommend to touch core files).

You could consider to choose another theme which has additional settings options like for displaying breadcrumbs.
> 1 votes

---
Tags: 7
---


title: Display only one book in Views

text:
# Question
Title: Display only one book in Views
I have several books with several pages on them. I want to create a view to display page from a specific book. I'm pretty sure View can dop it but I don't find the way to.

Do you have any idea ?

# Answer
You can add a filter on nid or title. If you want to, you can add a contextual filter (top right) and let the filter work with the url.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: Using views_embed_views() to generate content for an email message. How can I get it to insert images and urls correctly for this purpose?
I am using views\_embed\_views() to generate content for an email message. How can I get it to insert images and urls correctly for this purpose?

Or, asked another way, how can I put the contents of a view into an html email body?

# Answer
Use hook\_mail and drupal\_mail to send out e-mail. drupal\_mail at the place you want to send to mail, eg. hook\_cron. And hook\_mail to set the content. Use drupal\_mail to send parameters to hook\_mail.

As for the images, make sure that you use absolute url's in views (setting on the image field).
> 0 votes

---
Tags: views, emails, theming
---


# Question
Title: Restricting view access to a line Item field based on role
I have an order page that displays a set of line items.

>

However, my client wants me to remove the "Responsible Vendor" from display for authenticated users, but it should be displayed for administrators and store manager users.

I have tried the following, but I could not get the desired results.

1. Hide using Field Permission as described in https://stackoverflow.com/a/9187147/260665
2. Implementing `hook_field_widget_form_alter()` following https://stackoverflow.com/q/8009716/260665

I am using the following code.

```
function bricks_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_responsible_vendor') {
    // Users without the "administer nodes" permission should not see the
    // Responsible Vendor section
    if (!user_access('administer nodes')) {
      unset($element['#options']['field_responsible_vendor']);
    }
  }
}

```

This hook is never invoked for the *field\_responsible\_vendor* field which represents the *Responsible vendor* entity reference field.

Now, I tried to dig deep and see why this hook was never invoked for the field in which I am interested. I placed breakpoints in /includes/module.inc with some test code in it.

```
    // Raj:
    $gotIt = NULL;
    if (is_array($context1)) {
      if ($context1['field'] == 'field_responsible_vendor') {
        $gotIt = $context1['field']['field_name'];
      }
      if (is_array($context1['field'])) {
        if ($context1['field']['field_name'] == 'field_responsible_vendor') {
          $gotIt = $context1['field']['field_name'];
        }
      }
    }

```

I tried it with `$context2` too. The nearest I could get was the following.

>

I could never get to the *field\_responsible\_vendor* field to unset it based on the user roles.

Is there anything I am missing? How can I achieve what I am looking for?

As per @Darvanen's answer, I was able to remove the *Responsible vendor* value using this code.

```
function bricks_views_pre_render(&$view) {
  foreach ($view->result as $lineItem) {
    if (!user_access('administer nodes')) {
      unset($lineItem->field_field_responsible_vendor);
    }
  }
}

```

I have the following 2 problems.

1. This hook is invoked for all views, I would rather like to restrict either the invocation to this page / view alone, or provide a condition to check if it is the page where this code should be executed in order to make sure that performance is not impacted.
2. The column header is appearing though none of the line items will contain the value for it. I suppose I need to use another hook in order to address this?

>

# Answer
I would hide the column using a hook\_preprocess\_HOOK().

The item list is rendered by a view which is using `table` display and `views-view-table.tpl.php` so we just need to alter `$variables` which are passed to that template file; like this:

```
/**
 * Implemenets hook_preprocess_views_view_table()
 *
 * Removes a column out of order items table for non-admin users
 */
function MYTHEME_preprocess_views_view_table(&$variables) {
  if ($variables['view']->name == 'commerce_line_item_table') {
    if (!user_access('administer nodes')) {

      // name of the field that you want to hide
      $field_name = 'field_responsible_vendor';

      // Unset it from the table header
      unset($variables['header'][$field_name]);

      // Unset the value from each row
      foreach ($variables['rows'] as &$row) {
        unset($row[$field_name]);
      }
    }
  }
}

```

(This function should be placed in the `template.php` file in the theme folder and the word `MYTHEME` should be replaced by the theme name).
> 1 votes

# Answer
The hook method is a good one but you'll need a different hook.

The order page uses a view of line items, not a node display, so you should use a views hook.

I would try either hook\_views\_pre\_render or hook\_views\_pre\_view.

Use `dpm($view)` (needs devel module) to inspect the view and then modify it however you wish.

To figure out that it was using a view I went to the page, inspected the element in my browser and followed the chain up until I found either a form or a view:

---

Additional information:

1. You will definitely need to put an if statement around your code. Dig through the dpm results for a view id or some other identifier and do something like:

```
If ([address of view id] != [view id you want]){
  return;
}

```
2. To make the column disappear you'll need to unset the field itself, not just the value. Look in $view somewhere other than `->result`. Sorry, without the dpm output in front of me I can't be more specific than that.
> 1 votes

---
Tags: entities, commerce
---


title: Content type itself as entity

text:
# Question
Title: Content type itself as entity
I need to classify and mark my content types. As example I have three content types for group messages in OG, ten content types which used as UC products, etc. So I need to add taxonomy and fields to my content types (NOT for nodes of content types, but to content types!) and then filter them. As example I could show only OG message types, or only product types, or only products which are clothes etc. So I thing I need a module which turn content type to something like entity.

Is there any module which implements such feature?

It is hard to search such module, because if I search like "add fields to content types" I see results how to add fields to nodes of content types, which will be populated in node forms. But I need to add fields to content type form, to classify and mark content types, not nodes of content types.

# Answer
I don't know if it goes far enough for you, but the Content type groups module helps you categorise content types.

> Content type groups was designed to handle the use case when you need to populate select boxes or other interface elements with certain content types but not others. This module allows you to create an unlimited number of groups of content types through the UI. Once a group is created, it can be referenced in code using API functions and in Views.
>
> ### Example
>
> Let's say you're organizing your media collection. You have the following content types: *book*, *movie*, *audio*, *article* (for your blog about your collection), and *page* (for some static content).
>
> Create a content type group called *Media* and add the *book*, *movie* and *audio* types. You have just created a logical grouping between the content types to show that they are related. This makes it easier for future developers to understand the relationship between various content types.
>
> Now let's say you start collecting old magazines. You create a new content type called *magazine* and add it to the *Media* content type group. Any place where *Media* is referenced will automatically reflect the change; there is no need to track down all Views or lists.
>
> This module is being rewritten to turn content type groups into entities, with a dependency on Entity API. The 2.x branch is heavily under development and not ready for any site use.
> 1 votes

---
Tags: entities, taxonomy-terms, nodes
---


title: Profile2 view with all profile fields

text:
# Question
Title: Profile2 view with all profile fields
How can I create a view, where all profile fields are as columns of a table view, without having to add each profile field indivudally? Is this possible?

# Answer
> 0 votes
I could solve this, with a custom module:

```
<?php

/**
 * Implements hook_views_data().
 */
function profile2_all_fields_views_data_alter(&$data) {

  $data['profile']['profile_all_fields'] = array(
    'title' => t('All profile fields'),
    'help' => t('When rendered, this field will be replaced by all the fields on the profile. No configuration is required.'),
    'field' => array(
      'title' => 'All profile fields',
      'handler' => 'views_handler_field_custom',
    ),
  );

}

function profile2_all_fields_views_pre_view(&$view, &$display_id, &$args)
{
  // Replace the static field with dynamic fields.
//  dsm($view->display_handler);
//  dsm($view->display_handler->default_display, '$$view->display_handler->default_display');
  if ($view->display_handler->options['fields']) {
    $fields = &$view->display_handler->options['fields'];
  } else {
    $fields = &$view->display_handler->default_display->options['fields'];
  }

  foreach ($fields as $field_name => &$field) {
    if ($field['field'] == 'profile_all_fields') {
      $instances = field_info_instances('profile2', 'main');
      dsm($fields, '$fields');
      // Each field is added as a Views field.
      foreach ($instances as $key => $instance) {
        $newfield['id'] = $instance['field_name'];
        $newfield['table'] = _field_sql_storage_tablename($instance);
        $newfield['field'] = $instance['field_name'];
        $fields[$key] = $newfield;
      }
      unset($fields[$field['id']]);
      dsm($fields, '$fields');
    }
  }
}

```

# Answer
> 1 votes
I think it would work if you create a view that displays users as rendered entities, not fields.

You can then tweak the way user entities are rendered and show all fields.

---
Tags: views, users
---


# Question
Title: user_save adds values to the user, but they aren't "active"
I'm taking over a website that had a user import; it has a function that sets the value for some Boolean fields on the user.

```
$user->field_perm_connexion['und'][0]['value'] = (int)$permissions['perm_connexion'];
user_save($user);

```

When I edit the user, the value is correctly checked; when I execute code like the following, the value is wrong.

```
$user_perm = user_load($uid);
// don't judge the ['und'][0]['value']
if(!empty($user_perm->field_perm_connexion) && $user_perm->field_perm_connexion['und'][0]['value'] == 1){
    $is_allowed = TRUE;
}

```

I need to go to the user page (in the people menu) and save again, to get the correct values.

What could the problem behind this be?

# Answer
> 0 votes
It may be static cache, try:

```
$user_perm = user_load($uid, TRUE);

```

---
Tags: users
---


# Question
Title: How to construct a db_query() with complex criteria?
I'm getting into the database API and it's really interesting how it works. The function db\_query() makes querying the database very easy. However, I don't quite understand placeholders and the relationship between placeholders and $args parameter.

Example #1, the first comment on the doc page, can be written as: `$result = db_query('SELECT n.field1, n.field2, ... FROM {table} n
 WHERE n.field0 = :field0', array(':field0' => $field0value));
foreach ($result as $record) {
 // Data are in $record->field1, $record->field2, ...` The db\_query function has two parameters; the first is an SQL query and the second is an array definition. The two are related by ":field0", which is called a placeholder. The fields and table are also modified by something called "n"; I don't know what that is.

I found that the above code works. However, I also found that it works and yields the same results without the n's, without the placeholder, and without the array: (The function syntax says the default if the array is not provided is simply "array()".) `'SELECT field1, field2, ... FROM table WHERE field0 = ' . $field0value`

I tried this because I need to use complex criteria in which it is not clear what to do with the placeholder and array: `SELECT * FROM table WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"`

I ran this in phpMyAdmin and it works fine. It works by first looking at field1 and if there's something there, it uses that but if it's empty then it takes the value from field2. It then combines that with "value1" and selects records for which the result equals "value2".

So I put that in db\_query like so: `db_query('SELECT * FROM {table} WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"');`

which resulted in the message: `PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause': SELECT * FROM {table} WHERE concat(if(field1 = "", field2, field1), "value1") = "value2"; Array ( ) in include_once() (line 87 of ....php).`

Drupal does not seem to be complaining about the use of the concat and if functions, so it seems to be capable of handling them. The symbol between the words "column" and "in" above is a pair of single quotes. So it looks like Drupal is looking for a column designation somewhere and not finding one. My guess is it's looking for something in the empty array. Do I need to use one or more placeholders and some form of array construct in order to get this to work?

Thanks for your help.

# Answer
> 1 votes
The answer provided in the comment above did get the code to work, but according to Jaypan in the Drupal forums, using that solution is a security risk. The error was caused by not using placeholders and the associated array argument, and the purpose of those devices is to prevent SQL injection attacks. The solution of reversing the quotation marks was able to stop the error messages, but at the cost of leaving open a security hole in the code. Jaypan gave me the code to implement the complex criteria with placeholders:

```
<?php
db_query('SELECT * FROM {table} WHERE concat(if(field1 = :empty, field2, field1), :value1) = :value2',
array(':empty' => '', ':value1' => 'value1', ':value2' => 'value2');
?>

```

I've implemented that and it works. The pattern seems clear enough to be able to adapt it to other complex criteria in the future, although it would be nice if we had some documentation of placeholders and their syntax.

===============

Edit: It turns out there is some documentation of placeholders, although it's not comprehensive and the discussion with Jaypan (linked above) helped to clarify things.

# Answer
> 0 votes
Looks like you problem is within the `field1 = ""` ... Try to use single quotes and it should work.

Not sure why Clive did not post his comment as "the" answer (maybe he fears downvotes?), which is why I did so now ... So that NewSites has something to consider for "accepting" ...

PS: your new problem should be moved to a new question I think.

---
Tags: database
---


# Question
Title: Show View Pane in Node Template based on Taxonomy Term
I am trying to add a view pane to a node template. The node and the content type shown in the view panel both have a taxonomy term field, so it should be a simple matter to link them, but I can't figure it out.

My node template has the relationship Taxonomy term from Node. The view pane has context "has taxonomy term id" and has Argument Input from context. Unfortunately, I can't figure out what combination of selections I need to make in context and argument input to make it all work.

Under Argument Input, do I pick the field that contains the term or do I pick one of the choices under Taxonomy Terms?

Under Context filter value type, do I pick Term Name, Term from ID or something else (or nothing at all)?

I think I've tried all possible combinations, but I have the view showing up on nodes whether they contain the context or not. Any help would be greatly appreciated.

Drupal 7.37, Panels 7.x-3.5 and Views 7.x-3.11.

# Answer
> 0 votes
Ok, I finally figured it out!

To show a view in a panel where the view and panel are related by a taxonomy term (in my case Team Term (field\_team\_term), do the following:

1. Use the view content panes module to create a view content pane (How can I show a view in panel with argument in Drupal 7).
2. In the view content pane use contextual filter "Has Taxonomy Term ID". When Filter Value is not available: Hide View. When Filter Value is available - specify validation criteria - choose taxonomy vocabulary - Filter Value Type: Term Name converted to Term ID. (Some writers suggested checking the "Allow Multiple Values" box at the bottom of the window under More; I found that unnecessary.)
3. In the Pane Settings - Argument Input, select "From Context".
4. Under Required Context, select Name under Taxonomy Term.

That completes the views setup.

In the panel settings,

1. Set up a relationship"Taxonomy term from Node (on Node: Team Term \[field\_team\_term\])" in the case of my taxonomy term field.
2. In content, add the view pane, and select the taxonomy term relationship as the argument.

As near as I can tell, that is only combination of panel context and view arguments that will get the job done. I hope this helps someone.

---
Tags: views, taxonomy-terms, panels
---


# Question
Title: Creating, modifying and removing folders and folder structures in Drupal 7
I know that it is possible to delete files from the File Browser view, but is there a way to create, modify and remove folders in Drupal 7?

# Answer
If you're using 'file browser' than you probably have the IMCE file manager enabled. What you want to do then is enable the extension module IMCE\_mkdir to create directories and subdirectories (within folders your web user has permission to access):

> IMCE Mkdir allows users to create and delete sub-directories under directories assigned by IMCE.
> 1 votes

# Answer
Another relevant module, IMCE Tools: https://www.drupal.org/project/imce\_tools
> 1 votes

---
Tags: 7
---


# Question
Title: How do I prevent a "Page not found" error for URLs containing non-Latin characters?
I have a site that uses non-latin characters in URLs, e.g. http://example.com/drupal/новости. When the URL is copy-pasted, some browsers change the URL to http://example.com/drupal/%ED%EE%E2%EE%F1%F2%E8, and this causes an *Page not found* error.

How do I make Drupal understand both http://example.com/drupal/новости and http://example.com/drupal/%ED%EE%E2%EE%F1%F2%E8?

# Answer
> 3 votes
Consider trying the Transliteration module. Here is a quote from its project page:

> ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like `mydomain.com/последние-новости-в-Украине-и-мире` in something like `mydoamin/poslednie-novosti-v-Ukraine-i-mire`.

Other modules that might help to solve this question:

---
Tags: 7, uri
---


# Question
Title: Make Admin fieldset open by default when editing comment
As supplied by the core comment module when you go to edit a comment as an admin there is an Administration fieldset that lets you change the author and if the comment is published. When you load the page the fieldset is collapse and I'd like it to be open by default.

I found in the comments.module this bit of code:

```
// Display author information in a fieldset for comment moderators.
if ($is_admin) {
$form['author'] = array(
  '#type' => 'fieldset',
  '#title' => t('Administration'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#weight' => -2,
 );
}

```

Is there a hook or something I could use to manipulate this?

# Answer
> 1 votes
Use `hook_form_alter()`. Here's an example:

```
    function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'comment_node_YOUR_CONTENT_TYPE_form') {
        $form['author']['#collapsed'] = FALSE;
      }
    }

```

You can place this in a custom module, or in `template.php` of your your front end theme.

---
Tags: 7, comments
---


# Question
Title: How can I display the results of webform submission in a block and place it on front page?
So I'm using the Webform module to collect data, and I want to display the results in a Drupal block and place it in an appropriate theme region in my site.

Like for example the following: I want to display the analysis with the charts of my result (created with the Charts module) in the front page of my site.

Is that doable?

# Answer
There are 2 possible approaches to consider, as further explained below ...

## Approach 1: using the Charts modules

This is like rolling your own cookies. You create your chart (as you already seem to have done in the image above), using either the "Charts API" (= write some PHP code to populate the charts Array, whereas you put that PHP code in the content of your block) or using the "Views integration of the Charts module" (where you format the Views result as a block).

Disclosure: I'm a (co-)maintainer of the Charts module,
I hope this does not violate the site's policy on self-promotion.

## Approach 2: using the typical Webform related charting modules

If you want to create **charts** from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

* Webform Charts (used in about 350 sites), to display Webform results in a graphical manner using a charting library.
* Webform Chart (used in about 575 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).

## Note:

In both approaches you need to decide about which "Charting Library" (= engine) you want to use, either Google charts (easiest setup) or Highcharts (which might require a license also). At any time it should be pretty easy to swap between either library also (that is a key feature of the Charts module also ...).
> 3 votes

---
Tags: 7, blocks, webforms, charts
---


# Question
Title: Commerce - check if this very product in presented in user's previous orders
I use drupal commerce trying to build a website which sells content (nodes with restricted access). The thing is that, if user have bought the product once, he shouldn't have a possibility to do it again.

Currently i'm using `form_commerce_add_to_cart_form_alter` to check if user has already added this product to cart and if yes - hide "Add to Cart" button to prevent doing it twice and set a text that this very product is already in the cart. It works totally fine.

What I want to do next are two things:

**1)** to check if this current user has this product under active (not canceled and not complete) order, and if yes - hide "Add to cart button" and set a text that this product is under order processing at now.

**2)** to check if this current user has purchased this very product ever before and if he has, do the same trick - hide "Add to cart button" and set a text that User already owns this product.

My problem is that I'm very new to commerce and unfortunately totally don't understand how can I get all orders for the current user and check for some product IDs there... Will be very appreciated for any advice or a tip. Thanks a lot!

# Answer
> 3 votes
If you have the Entity API module installed, you can do it using entity\_metadata\_wrappers and EntityFieldQuery like this:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'commerce_order')
  ->entityCondition('uid', $uid);
$result = $query->execute();

if (isset($result['commerce_order'])) {
  $user_order_ids = array_keys($result['commerce_order']);
}

// Array for storing user's products.
$products = array();

foreach($user_order_ids as $user_order_id) {

  $o = entity_metadata_wrapper('commerce_order', $user_order_id);

  $line_items = $o->commerce_line_items->value();

  foreach ($line_items as $line_item) {
    $l = entity_metadata_wrapper('commerce_line_item', $line_item->line_item_id);
    $products[$o->status->value()][] = $l->commerce_product->product_id->value();
  }
}

```

This should give you a 2 dimensional array of products like this:

```
... (Array, 1 element)
  cart(Array, 2 elements)
    0 (String, 3 characters ) 203
    1 (String, 3 characters ) 158
  other_state(Array, 2 elements)
    0 (String, 3 characters ) 187

```

# Answer
> 1 votes
You can get a lot of the way there just by using Rules and Views, which is why we designed Commerce the way we did. So there isn't going to be a setting or a single feature module that meets all these needs at once, but you can do some things like the following:

1. You can prevent an item from being added to the cart by unsetting the product price for the item on the page using a product pricing rule. You'd do this by checking to see if the line item ID in the rule is 0, which means it's a temporary line item used to perform the price calculation. Then check to see if the product is already in the cart (or even purchased) and unset the price just like we do in the default pricing rule for when the product is disabled. That will automatically disable the button with the message "Product not available", so you'll likely want to do something to change that to a more meaningful message.
2. You can also update your product display to not combine line items in the cart in the event that the user is able to find an Add to Cart button for the same product. Then you can disable the quantity textfield in the shopping cart form View so the user can't edit it, or you can do something like is demonstrated in this post to turn the textfield into a plaintext rendering of the quantity. You can also use Rules to react to the add to cart process and ensure the quantity of any related line items is 1. There are drawbacks to using a pure UI approach. As I hinted in part 1, you're limited to what the button text can read. It should be different for different scenarios (already added vs. already purchased). Additionally, you don't have any way while users remain anonymous to inspect the orders in their session for products you know they've already purchased. That seems to me to be a fairly minor feature, though, as ideally they'd know they just purchased something - or else they could log in.

Ultimately, I think these needs would be best satisfied by a custom module that includes the code I mention from part 2 and supports configurable messages where applicable. I don't know of any such module or if these sorts of features are already extant in the 1.x of Commerce File.

The answer found here and it is written by Ryan Szrama.

---
Tags: commerce
---


# Question
Title: How to, in a View, get list of links up against each other (concatenated without line breaks when displayed)?
I have a Drupal 7 view that gives me a list of links to recently added content of a specific type. For what it's doing, it's working fine.

However, it puts every content item in a separate `<div>` causing it to appear on a line of its own. I'm using the *Unformatted list* output format with all fields set as inline.

*I want to simply list all the items concatenated.*

Currently the view renders as approximately the following HTML:

```
<div class="view-content">
        <div class="views-row views-row-1 views-row-odd views-row-first">

  <span class="views-field views-field-timestamp">        <span class="field-content">DATE1</span>  </span>       -
  <span class="views-field views-field-title">        <span class="field-content"><a href="LINK1">TITLE1</a></span>  </span>  </div>
  <div class="views-row views-row-2 views-row-even">

  <span class="views-field views-field-timestamp">        <span class="field-content">DATE2</span>  </span>       -
  <span class="views-field views-field-title">        <span class="field-content"><a href="LINK2">TITLE2</a></span>  </span>  </div>
...

```

I can get rid of the DATEs easily enough; that's just one of the fields being displayed. I was able to add the separating commas (using *Custom text*), and can easily use CSS to hide the last one if there's no better way. The problem is that I want the view to then basically render in the browser as something not entirely unlike:

> TITLE1, TITLE2, ...

for the specified number of entries, where each TITLE is a link to the relevant LINK, **the browser displaying them all in one normally-word-wrapped line.**

**How do I accomplish that?**

Seemingly no matter what I try, the newlines remain in the browser-rendered output. Google was decidedly unhelpful, although I'm not ruling out that I searched for the wrong terms.

Just in case it makes a difference, I am using the MAYO theme.

# Answer
I figured it out, with much thanks to No Sssweat's answer here as well as to another question. Since I had so much trouble figuring this out, I'm going to post the specific steps I took in an answer, for the benefit of future readers who want to do something similar.

First, have a view that gives the *data* you want to display. Start with the *Unformatted list* format and in its settings, check both *Add views row classes* and *Add striping (odd/even), first/last row classes*.

Then, add a separator using a *Global: Text* field to the view itself. I got some whitespace around it so changed from my original idea of a comma `,` to a separator character that worked better with whitespace on both sides, but I'm sure one could figure out how to remove the whitespace as well (perhaps using CSS `content` or margin trickery). It wasn't critical for my use case so I didn't bother. Add this separator text field as the last field to the view output.

At this point, the view preview will look rather odd, but that's okay. We'll fix it in place.

Then, add the view as a block and place it where you want it. If this isn't a fully isolated development environment, you may want to set it to only be visible to certain user roles for the time being, because it will look quite ugly at first. Once you can see the view on the page where it's going to be, use something like Firefox's *Inspect Element* feature on one of the output rows to obtain the ID of the `<div>` element corresponding to the *block*; you'll need that in a second.

Then, add some CSS (you might be interested in the CSS Injector module; no affiliation expressed or implied) like the second answer also linked above suggests. Specifically, try adding something like the following, substituting `block-views-your-view-block` as appropriate (use the `id` value of the block's `<div>` element):

```
div#block-views-your-view-block div.views-row,
div#block-views-your-view-block div.views-field
{
    display: inline;
}
div#block-views-your-view-block div.views-row-last div.views-field-nothing
{
    display: none;
}

```

The first rule causes the `<div>` elements of each result in the view to be displayed by the web browser inline rather than as blocks, and the second causes the last separator to not be displayed at all. If you have multiple fields in your view that have no corresponding data field, you may need to add a specific CSS class to the separator for this and use that class instead of `views-field-nothing`.

Save all this, and reload the page. Presto; **your view should now display as a list on a single line of text,** word wrapped by the browser as normal, rather than an all-out list.
> 0 votes

# Answer
Under **Format** click on **settings** and uncheck `Add views row classes` and uncheck `Add striping (odd/even), first/last row classes`

**Edit:**

You could use **html list** instead of unformated list.

Then use css to add the comas see JS Fiddle

or

since you added the commas's manually you could display inline or float left see this answer
> 1 votes

---
Tags: views
---


# Question
Title: How do other modules update elements using AJAX callbacks?
I have a block, of which I want to update the contents via AJAX. So the block is:

```
$block['subject'] = t('My Block');
$block['content'] = '<div id="block_wrapper"></div>';

```

And the form element AJAX part:

```
$form['select_element']['#ajax'] = array(
  'callback' => 'ajax_callback',
  'wrapper' => 'block_wrapper',
  'method' => 'replace',
);

```

The callback:

```
function ajax_callback($form, $form_state) {
  return views_embed_view('view_name', 'default', $form_state['values']['select_element']);
}

```

However when I change the form element the whole block content is replaced and the wrapper is replaced by a empty div, so subsequent alterations of the select element fail to update the block.

The wrapper documentation explains the entire div is replaced, not just it contents. But many modules (like for example Views) have dynamically updating form elements where changing a select element toggles other parts of a form, which keeps working no matter how often you change it. Do they insert the wrapper div again in the response? And how should I alter the response of views\_embed\_view to put the contents in a wrapper div?

# Answer
Thanks @Tasneem for directing me. I did it as follows:

```
function hook_form() {
  $form['select_element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_callback',
      'wrapper' => 'block_wrapper',
      'method' => 'replace',
    ),
  );

  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  return $form;
}

function ajax_callback($form, $form_state) {
  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  // Returning the entire $form here made the select element appear twice, so only return the wrapper element.
  return $form['block_wrapper'];
}

```
> 4 votes

# Answer
I think you must to create block\_wrapper in the $form before ajax as a container :

```
$form['select_element']['block_wrapper'] = array(
'#type' => 'container',
'#id' => 'block_wrapper',
'#attributes' => array(
  'class' => array('myclass')
  ),
);

```

to make ajax wrapper found it.
> 3 votes

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


# Question
Title: Using hook_form_alter on an existing form element
I'm using the Commerce module and in the checkout process I'd like to change the size of one of the input fields. I'm trying to use the following code but it doesn't seem to be working.

Am I doing this correctly? Or is there a better way to change the size of an existing form input field?

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'form-AyTG_90yQduNFHHSAwpVnMfNNXEt5iv_eUvptp_Ex7E') {
        $form['edit-account-login-mail'] = array(
            '#size' => 40,
        );
    }
}

```

# Answer
> 3 votes
Not sure which checkout form you try to alter, however, I've used `mytheme_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id)` and `mytheme_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id)` successfully.

And if I understand it correctly, the element 'edit-account-login-mail' already exists in your form. Therefore, I think you might want to add the size property instead of overwriting the form element, for instance:

```
$form['edit-account-login-mail']['#size'] = 40;

```

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


title: term_reference field is not created

text:
# Question
Title: term_reference field is not created
I set up the Services module as REST server, so I can create nodes with custom fields by REST client as in Services 3 - POST node.create with custom fields.

The settings of the Services module are the following.

```
Server => REST
Path to endpoint => "neoapi"
Session authentication => yes
Response formatters => json
Request parsing => application/json & application/x-www-form-urlencoded
Resource path => http://127.0.0.1/neoapi/node

Content type => mycontent
Term reference field => Autocomplete term widget (tagging)

```

And post next JSON data via Google Chrome Advanced Rest Client

```
{
"type":"mycontent",
"title":"The New Article",
"body":{
  "und":[ {
    "value":"This is the body of new article."
    } ] },
"field_neo_terms":{
  "und":[ {
    "tid":"3"
    } ] }
}

```

At REST client I receive "200. OK" NID and URI of new node. But in site i have new node with title and body, but without terms and error:

```
Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen()
(line 441 of C:\Program Files\VertrigoServ\www\includes\unicode.inc).
Warning: preg_match_all() expects parameter 2 to be string, array in   drupal_explode_tags()
(line 7254 of C:\Program Files\VertrigoServ\www\includes\common.inc).
Warning: array_unique() expects parameter 1 to be array, null given in drupal_explode_tags()
(line 7255 of C:\Program Files\VertrigoServ\www\includes\common.inc).
Warning: Invalid argument supplied for foreach() in drupal_explode_tags()
(line 7258 of C:\Program Files\VertrigoServ\www\includes\common.inc).

```

# Answer
> 3 votes
As the documentation you linked says, the structure for the fivestar field is the following.

```
{
  "field_fivestar":[{
    "rating":"100",
    "target":"0"
  }]
}

```

Probably you are missing "target"

Also, if you are using auto complete for taxonomy you should use the term id, tid, 3 times:

```
{
  "field_termins":[{
    "tid":{
      "tid":"[tid:26686]"
    }
   }]
}

```

Auto complete is the tricky part.

# Answer
> 3 votes
It appears that the format you send to Services is dependent on what widget you have selected for your taxonomy term reference field.

For example, I have a taxonomy term reference field, single value, with a select list widget. This is the data string to use when trying to update via a POST url and data string:

```
&node[field_tags][und][tid]=123

```

The equivalent for an autocomplete widget would be:

```
&node[field_tags][und]=Foo

```

The main difference is you have to use the term name instead of the term id when the widget is set to autocomplete.

If you're using JSON to and send it to services, then the JSON should be something like this for a select list widget:

```
{
  field_tags:{
    und:{
      tid:123
    }
  }
}

```

If the widget is an autocomplete:

```
"field_tags":{"und":"Foo"}

```

# Answer
> 0 votes
I tried and this worked for me , created user with term reference field with widget type select list. May be it also work for node.

```
        $scope.user.field_preferred_fee = {}
        $scope.user.field_preferred_fee['und'] = [];
        $scope.user.field_preferred_fee['und']= [tid1,tid2,tid3];

```

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


# Question
Title: How do I run Drupal SimpleTest example from Examples for Developers from the CLI?
I've been running tests from a helper\_module\_preprocess\_html function that I trigger on reload. I think I need to level up with testing. I have a vanilla installation of Drupal, downloaded and enabled Examples and SimpleTest modules, and for the life of me I can't figure out how to get the simple test example tests to run from the command line on Ubuntu 14.14. How do I use Drupal's testing system? I'm lost and the documentation on the internet isn't helping.

# Answer
It seems that SimpleTest requires a version number in the .info file. I added testing\_api = 2.x in the .info file and now it works.
> 1 votes

---
Tags: testing
---


# Question
Title: Change .gitignore file for sites/default/files/config
I'm checking out the new configuration management module for Drupal 7. It's effectively a back-port of the new configuration management that's in D8, and looks like it's going to be a great alternative to the use of Features for storing configuration.

https://drupal.org/project/configuration

I have a test github repository where I'm playing with the module. I'd like to put my code and configuration in this repo, and I'd quite like to keep the default location for the config files (sites/default/files/config).

I realise that this is more a question about `.gitignore` files than Drupal. However, how can I change my `.gitignore` file so that I can add the config files to my repo?

The current gitignore is here. (This is the excellent `.gitignore` file provided by github as a default for Drupal projects).

The simple change of adding `!sites/default/files/config/*` to the end of the file doesn't seem to help.

EDIT: I also tried this, with no luck:

```
!sites/default/files/config/*.inc

```

I'd be grateful for any tips on how others manage to solve this problem. Thanks!

# Answer
You can do that if you ignore the content in "sites/*/files/*" directory and not the directory itself "sites/\*/files/", I think this is not the best way to do it but that is what I have managed to find.

Ignore all the content in "sites/*/files/*" except for the config directory

```
# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config

```

or you can only ignore the config/\*.inc

```
# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config
sites/*/files/config/*
!sites/*/files/config/*.inc

```

remember to replace the default "sites/*/files" with "sites/*/files/\*" in the .gitigonre file.

---

Another way is to forcefully add the files you want to commit, this will add the files in the directory and track there changes, but will not detect new files added in the future.

```
git add -f default/files/config/

```
> 1 votes

# Answer
git doesn't ignore what has been tracked before. You can do `git rm --cached <file>`. Note that any repo which pulls this change will delete their local copy of that file. You can "bring it back" using `git checkout HEAD@{1} file` immediately after pulling / merging.
> 0 votes

---
Tags: version-control, configuration
---