title: Undefined index: db_type in custom code

text:
# Question
Title: Undefined index: db_type in custom code
I have created a module but my code gives me an error

> Undefined index: db\_type in student\_install()

How can I fix this?

Following are my three files

student.INFO FILE

```
name        = student
description = "Add/edit/save student data."
core        = 7.x
package = "students"

```

students.MODULE FILE

```
<?php

/**
 * Students - The text editor for the Internet - http://ckeditor.com
 * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
 *
 */

 function students_menu(){
 $items = array();
  // path location (<a href="http://www.url.com/foo/bar" title="http://www.url.com/foo/bar">http://www.url.com/foo/bar</a> )
  $items[] = array(
    //path
    'path'=> 'admin/settings/students',
    // page title
    'title' => t('Manage Students'),
    // describe the page for the menu system.  site visitors will not see this
    'description' => ('Add students'),
    // function that is called when visiting the new path
    'callback' => 'drupal_get_form',
    'callback arguments' => 'Students settings',
    // permissions required to view page
    'access' => user_access('access administration pages'),
  );
  return $items;
}
 function students_settings()
 {
    $form['name'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Name?',
    '#size' => 20,
    '#maxlength' => 20,
    '#required' => TRUE, //make this field required
  );
  $form['last_name'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Last Name?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => False, //make this field required
  );
  $form['email'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your email?',
    '#size' => 20,
    '#maxlength' => 20,
    '#required' => TRUE, //make this field required
  );
  $form['age'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Age?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );
  return system_settings_form($form);

 }
 function students_get_form($form_id,$form_values)
 {
    drupal_set_message(t("Submited"));
 }

```

students.INSTALL FILE

```
function students_install(){
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      // the {tablename} syntax is so multisite installs can add a
      // prefix to the table name as set in the settings.php file
      db_query("CREATE TABLE node_field_students_data (
          id int unsigned NOT NULL default '0',
          name varchar(32) NOT NULL default '',
          age int unsigned NOT NULL default '0',
          roll_num int unsigned NOT NULL default '0',
          PRIMARY KEY  (id)
        ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
      break;

    case 'pgsql':
      db_query("CREATE TABLE node_field_students_data (
          id serial CHECK (id >= 0),
          name varchar(32) NOT NULL default '',
          age integer NOT NULL default '0' CHECK (age >= 0),
          roll_num integer NOT NULL default '0' CHECK (roll_num >= 0),
          PRIMARY KEY  (id)
        )");

      // Pgsql requires keys and indexes to be defined separately.
      // It's important to name the index as {tablename}_fieldname_idx
      // (the trailing _idx!) so update scripts can be written easily
      db_query("CREATE INDEX node_field_students_data name_idx
                ON node_field_students_data (name)");
      break;
  }
}

function students_uninstall()
{
    switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      // the {tablename} syntax is so multisite installs can add a
      // prefix to the table name as set in the settings.php file
      db_query("DROP TABLE node_field_students_data");
      break;

    case 'pgsql':
      db_query("DROP TABLE node_field_students_data");

      // Pgsql requires keys and indexes to be defined separately.
      // It's important to name the index as {tablename}_fieldname_idx
      // (the trailing _idx!) so update scripts can be written easily
      break;
  }
}

```

# Answer
The `$db_type` variable no longer exists in Drupal 7. You need to use template code that was designed for Drupal 7.
> 1 votes

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


title: Append "node" to tab menu link

text:
# Question
Title: Append "node" to tab menu link
I have a view that display members for a group. The path for this view is set as node/%/members. When I go to group page, the menu works fine:

I can't find anyway to change these links.

# Answer
> 0 votes
This isn't a problem with the view. The url paths used for your tabs are using relative URLs (e.g. "node/$nid/group-forum") you need use absolute URLs (e.g. "/node/$nid/group-forum").

```
<ul class="tabs--primary nav nav-pills">
  <li class="active"><a href="node/1147" title="View"><i class="fa "></i>View</a></li>
  <li class=""><a href="node/1147/group-forum" title="Forum"><i class="fa "></i>Forum</a></li>
  <li class=""><a href="node/1147/members" title="Members"><i class="fa "></i>Members</a></li>
</ul>

```

You need to check the rendering logic in your theme templates to see where the problem lies.

---
Tags: views
---


# Question
Title: How to put page-title inside of my content's first panel?
Using a custom theme, pretty basic (so far):

```
<section id="content">
    <?php if ($title): ?>
        <h1 class="title" id="page-title">
            <?php print $title; ?>
        </h1>
    <?php endif; ?>

    <?php if ($tabs): ?>
        <div class="tabs">
            <?php print render($tabs); ?>
        </div>
    <?php endif; ?>

    <?php print render($page['content']) ?>
</section>

```

That standalone `<h1 class="title" id="page-title">` is the problem, though. I want it to appear inside the first panel of content (I'm using Panopoly), but since all the panels are generated by `render($page['content'])`, it's not clear to me how I should do this.

My first solution was to use CSS, positioning the title relatively and adding some padding to the first panel to give it room. However, this only works as long as the title is one line of text. So a pure CSS solution appears to be out.

# Answer
Given the theme's use of Panels, I would suggest looking into the default panels it uses and whether or not the title field can be manipulated in that way, so that the title could be placed in any given section you want.

**EDIT** from OP

"Just so. For future readers: I accessed Panopoly \> Pages under the admin menu to alter the default page templates. Then for the generic Content Page, set "Title type" to "No title" and edit the settings for the content panel to "Override title" as "%node:title", "h1"."
> 0 votes

---
Tags: theming, panels, distributions
---


# Question
Title: how to make relations link when editing taxonomy not show
When a user edits a taxonomy term, there is a link for "Relations" at the bottom. how can I make that link not show up for certain roles?

# Answer
got this answer on drupal.org

Yes, you can do it by hook\_form\_alter()

i.e. /\** * Implementation of hook\_form\_alter() * * Some code taken from https://www.drupal.org/node/2158985 \*/ function hide\_taxonomy\_fieldset\_form\_alter(&$form, $form\_state){ if($form\['#form\_id'\] ==='taxonomy\_form\_term') $form\['relations'\]\['#access'\] = FALSE; }
> 0 votes

# Answer
You may create your custom permission in the hook\_permission and then hide this part of the form in using hook\_form\_alter if user shouldn't have access to this element.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: How and when are commerce licenses created, and when does the state change to "active"?
I'm working on a module that attempts to tie commerce\_license in with the ACL (Access Control Lists) module.

I am attempting to sell access to an individual node. I have a product type, product, and product display which does this. I have a node reference field which allows an admin to select which node to license on product creation, and this reference field is being correctly referenced in my license class (the one in plugins/license\_type/ which extends CommerceLicenseBase).

In my save() function, I'm checking to see if the status is COMMERCE\_LICENSE\_ACTIVE before I add the license owner to the acl, but it appears that **the license never gets in this state**. I have gone through the checkout process, and even manually completed the order, but I don't ever see the license get to the "active" state.

I've also noticed that **the license seems to be created** (the save() function is called) when a product that is associated with a license **is added to the cart, and NOT on checkout**, as is stated in the documentation.

I think the real issue is in my **lack of understanding** of how the commerce license module works (and possibly how the ACL module works, but that's a different discussion). I've read through the documentation, watched a few tutorials, and looked through the example code, the commerce\_license\_role module, as well as the commerce\_license\_og and commerce\_file modules, and I'm still not sure what I'm doing wrong - I'm beginning to suspect that my error is not in the code itself, but rather in configuration.

**Here is my code:**

```
<?php

  public function save() {

    if ($this->uid && $this->product_id) {

      // Get the entity referenced
      // (this works fine - field is defined in the .module file)
      $node = $this->wrapper->product->commerce_license_acl_node->value();
      $acl_name = 'ACL_' . $this->product_id . '_' . $node->nid;

      // Get the acl associated with this node and product ID
      $acl_id = acl_get_id_by_name('commerce_license_acl', $acl_name);

      // If the ACL doesn't already exist, create it
      if(empty($acl_id)){

        // Create ACL if one is not already associated with this license
        $acl_id = acl_create_acl('commerce_license_acl', $acl_name);

        // Grant ACL users read access to this node
        $read   = TRUE;
        $update = FALSE;
        $delete = FALSE;
        acl_node_add_acl($nid, $acl_id, $read, $update, $delete, 0);

      }

      $owner = $this->wrapper->owner->value();

      // I realize a lot of this is redundant. I'm covering all the cases here for my benefit
      // in trying to understand what is going on.
      switch($this->status){
        case COMMERCE_LICENSE_ACTIVE:
          // *** This case is never true
          acl_add_user($acl_id, $owner->uid);
          drupal_set_message('license_acl set to active');
          break;
        case COMMERCE_LICENSE_CREATED:
          // **** This is the state that it always seems to be in
          drupal_set_message('license_acl created');
          break;
        case COMMERCE_LICENSE_PENDING:
           drupal_set_message('license_acl set to pending');
         break;
        case COMMERCE_LICENSE_EXPIRED:
          acl_remove_user($acl_id, $owner->uid);
          drupal_set_message('license_acl set to expired');
          break;
        case COMMERCE_LICENSE_SUSPENDED:
          acl_remove_user($acl_id, $owner->uid);
          drupal_set_message('license_acl set to suspended');
          break;
        case COMMERCE_LICENSE_REVOKED:
          acl_remove_user($acl_id, $owner->uid);
          drupal_set_message('license_acl set to revoked');
          break;

    }

    parent::save();

  }
  ?>

```

Is there any documentation out there which goes into depth explaining the workflow of commerce license creation and statuses? Thanks in advance.

# Answer
It looks the license is being activated when the "order paid in full" trigger fires, and I didn't have a payment system in place. I thought I had it configured to bypass this, but enabling the example payment system and the payment ui solved the problem.

However, the user still doesn't have access to the node associated with the ACL, so I need to figure that one out, as well.
> 1 votes

---
Tags: entities, chaos-tool-suite, commerce
---


# Question
Title: How to list taxonomy terms grouped by a field with Views
I have a taxonomy vocabulary called 'clients'. There's a field on that called 'category' which is a simple text list.

I want a view that results in something like:

> ## Category Foo
>
> (rendered term in category Foo)
>
> (rendered term in category Foo)
>
> ## Bar Category
>
> (rendered term in Bar category)

It seems I can group by a field, but only if I select fields as the output. Is there a way to have it **group by field** (for the headings) but use the **rendered terms** (with a particular view mode) within the grouping?

# Answer
> 0 votes
A-ha!

Tick the "Force using fields" option under the page style. This turns on the fields bit which you can then use to group by.

---
Tags: 7, views
---


# Question
Title: How to send variable value in POST Method in Drupal
How to send variable value to another page by using POST Method in Drupal?

# Answer
> -1 votes
It would just be a standard form with post as the method.

```
<form method="post" action="/other-page">
  <input type="text" name="yourfield" value="Value">
  <input type="submit" value="Submit">
</form>

```

---
Tags: 7, webforms
---


# Question
Title: Drush crashes after "command dispatch complete"
I have a custom drush script. This script loads, changes and saves ~10000 drupal commerce products.

After that I get the message

```
Command dispatch complete [1140.43 sec, 663.25 МБ]                                                                                [notice]
 Timer                Cum (sec)  Count  Avg (msec)
 page                 1140.368   1      1140367.61
 drupal_http_request  67.66      1032   65.562
Peak memory usage was 784.48 МБ [1140.43 sec, 663.24 МБ]

```

And AFTER that script hangs and consumes more and more memory. Finally, after long time, script reaches 1.5 G memory limit and dies.

```
PHP Fatal error:  Allowed memory size of 1610612736 bytes exhausted (tried to allocate 80 bytes) in /var/www/vhosts/mysite.ru/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc on line 302

Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 80 bytes) in /var/www/vhosts/mysite.ru/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc on line 302

```

All products which were processed by the script are sucessfully changed.

The question: why drush script hangs when dispatch is complete and what it makes for such a long time when all products are processed? Is it sort of a post-processing?

Denis

# Answer
I figured out why my script hangs after "Command dispatch complete".

The matter is that I have installed the "Search API" module. This module has

```
function search_api_track_item_change($type, array $item_ids)

```

method. In this method it calls **search\_api\_index\_specific\_items\_delayed** function, and in this function it registers shutdown function **\_search\_api\_index\_queued\_items**.

```
drupal_register_shutdown_function('_search_api_index_queued_items');

```

**\_search\_api\_index\_queued\_items** function calls **search\_api\_index\_specific\_items** and finally in this function search api loads into memory all changed products! (~10000)

```
function search_api_index_specific_items(SearchApiIndex $index, array $ids) {
    $items = $index->loadItems($ids);
    // Clone items because data alterations may alter them.
    $cloned_items = array();
    foreach ($items as $id => $item) {
    $cloned_items[$id] = clone $item;
    }
    $indexed = $items ? $index->index($cloned_items) : array();
    ...

```

And it happens not just one time, but several times for every index of my drupal installation.

Of cause I have not enough memory for 10000 products, so script dies.

**My solution**: I just disabled "Index items immediately" option in my search api indexes.
> 0 votes

# Answer
Drush is running out of memory.

In the case of re/indexing search data via Search API, the item in that issue queue for this is Better memory usage on indexing.

To work around these sorts of issues, you can increase the amount of memory used by Drush, without touching the memory limit used by your Web server. See Configuring php.ini for details.

In my case, in my drush.ini, I increased it from:

* memory\_limit = 256M

to:

* memory\_limit = 512M

...and it solved my Search API (re)indexing problem.
> 1 votes

# Answer
If you see code inside drush.php file ...

```
function drush_main() {
  $return = '';
  // Start code coverage collection.
  if ($coverage_file = drush_get_option('drush-coverage', FALSE)) {
    drush_set_context('DRUSH_CODE_COVERAGE', $coverage_file);
    xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
    register_shutdown_function('drush_coverage_shutdown');
  }

  if ($file = drush_get_option('early', FALSE)) {
    require_once $file;
    $function = 'drush_early_' . basename($file, '.inc');
    if (function_exists($function)) {
      if ($return = $function()) {
        // If the function returns FALSE, we continue and attempt to bootstrap
        // as normal. Otherwise, we exit early with the returned output.
        if ($return === TRUE) {
          $return = '';
        }
        drush_bootstrap_finish();
        return $return;
      }
    }
  }

  // Process initial global options such as --debug.
  _drush_bootstrap_global_options();

  $return = '';
  drush_bootstrap_to_phase(DRUSH_BOOTSTRAP_DRUSH);
  if (!drush_get_error()) {
    // Do any necessary preprocessing operations on the command,
    // perhaps handling immediately.
    $command_handled = drush_preflight_command_dispatch();
    if (!$command_handled) {
      $return = _drush_bootstrap_and_dispatch();
    }
  }
  drush_bootstrap_finish();

  // After this point the drush_shutdown function will run,
  // exiting with the correct exit code.
  return $return;
}

```

Seems like everything goes smooth till

```
$return = _drush_bootstrap_and_dispatch();

```

where it logs

```
drush_log(dt('Peak memory usage was !peak', array('!peak' => drush_format_size(memory_get_peak_usage()))), 'memory');

```

So, A good starting point for you to debug is analyse below functions with log statements

```
  drush_bootstrap_finish();
  drush_shutdown(); // In includes/bootstrap.inc

```
> 0 votes

---
Tags: drush
---


# Question
Title: How to use an external jQuery plugin with Drupal's no-conflict jQuery
I'm using drupal\_add\_js() to load some external js:

```
drupal_add_js('http://jquery-accordion.googlecode.com/svn/trunk/jquery.accordion.js', 'external');

```

This produces 'TypeError: $ is not a function' errors because Drupal uses jQuery in no-conflict mode.

So I think the only solution is to copy the code, wrap it in this function and call it locally:

```
(function ($) {
  // Original JavaScript code.
})(jQuery);

```

I wondered whether there was a trick to still be able to directly use external js?

# Answer
> 0 votes
In Drupal 7, if you a certain that the external scripts are attempting to use "$" as an alias for jQuery, and you can't get the script author to patch their code, and you aren't loading any other JavaScript libraries, then in your template\_preprocess\_page, place the following drupal\_add\_js before the set of all drupal\_add\_js that reference external files. All scripts in the header region that use "$" as an alias will then refer to jQuery:

```
drupal_add_js('var $ = jQuery;', 'inline');

```

If your external javascript is added in another region, for example, the footer, then use something similar to the following instead:

```
drupal_add_js('var $ = jQuery;', array('type' => 'inline', 'scope' => 'footer'));

```

---
Tags: 7, javascript
---


# Question
Title: What is the memcache report screen telling me?
I'm experimenting with memcache and installed it via these instructions on a dev box. I *think* I have it working.

The config file is mostly left at default:

```
# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

```

My Question: What am I looking at here? How do I know how "effective" this set up might be? For example, when the **sets** row says "0.14/s; 773 sets (29.97%) of 2,579 commands", does that mean 29.97% of insert/updates where cached?

I'm having difficulty reading this report.

# Answer
> 3 votes
Those are operations on your memcached server.

* **Sets:** Data placed into cache by sets/second; by absolute number (by % of total commands); and a display of total number of commands. Sets are expensive (it represents needing to retrieve from your DB or other slower data sources) so you want this to be as low as possible, relative to gets.
* **Gets:** Data requested from cache by gets/second; by absolute number (by % of total commands); by absolute number of cache retrievals (by % of total gets); by absolute number of cache misses (by % of total gets). Gets are the entire reason you employ memcache (to retrieve from fast memory rather than a slower disk/network) so you want this to be high as possible, relative to sets.
* **Counters:** The number of increment/decrement operations performed on memcached counters.
* **Transferred:** The ratio of read to written data. Since it's in absolute data amount, it gives you an idea of how much you're saving in reading from slow disk/network storage.
* **Per-connection average:** The average amount of data and memcache operations made in a Drupal connection by gets/sets. The should give you an idea of how much memcache is employed on a Drupal request.
* **Available memory:** The amount of memory used / available on the server. This is another metric showing how much you're utilizing memcache.
* **Evictions:** The number of evictions or cached data removals from your memcached server.

---
Tags: caching
---


# Question
Title: How to override a view template in Bootstrap sub-theme
I'm using a Bootstrap sub-theme and am using the `templates` directory to override the templates for specific pages and is working ok.

I'm looking at this page in order to override the template file for a specific view, have added the file with my view name inside the template folder but its not working. Neither I can find the Bootstrap original `views-view-unformatted.tpl.php` in the bootstrap folder.

Can anyone point me in the right direction?

# Answer
This is how I template my views in bootstrap sub-themes with or without the bootstrap views module b/c sometimes you need to change those as well :)

First - In my sub-theme's for Bootstrap I make a folder called 'views' in the 'templates' folder (this is for sanity and structure, I think it works without the folder but don't quote me on that). There's only one view template in the bootstrap theme, for a responsive table so you can template anything however you want using the normal views templates.

You can also use the bootstrap views module mentioned in the other answer but you may still want to template those again in your subtheme so you will need the above folder '/templates/views' and now the documentation page you mention has some of the templates but views comes with a way to accomplish this without that page in the UI.

Loose instructions for views templates.

* open a view in the admin view UI screen
* look on the left hand column for advanced, expand if needed.
* look to the very bottom of that column and you will see Theme: Information
* click that link, pop up appears
* this is your views theming information, you will see that the current template being used is in bold.
* I usually go find that template beg used, copy that into my subtheme's '/templates/views' folder and choose from the list in the popup what I need to name the file, like for a view named "repair" I wouldn't want to use views-view.tpl.php and overwrite all the views display output, I would want to use views-view--repair.tpl.php so I name my file that and change something subtle.
* then I go hit the rescan templates files button in the popup and my new template will be in bold.
* I save the view and go make sure I did something productive.
* don't forget to clear cache if you aren't seeing what you want to see, it usually pops up after that, if not double check your naming of the file.

Hope that helps, views templates rock and I use them a pretty good bit just let me know if that doesn't work.
> 3 votes

# Answer
Maybe you should consider using the Views Bootstrap module? Here is an excerpt from its project page:

> ... enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Show advanced search form outside fieldset
When I search for a keyword in core Drupal search, it shows a results page with a link named *Advanced search* that hides a fieldset with more form options. I want it to be shown in the basic search form, not only on search result page, and it should be expanded by default.

Note: I want all this with core search in Drupal 7.

# Answer
> 0 votes
take a look at the Advanced Search Module:

> This module alters the default search box in many ways. If you need to have options available like in advanced search, but directly in the search box, this module is for you.
>
> Basic options The module adds options to select:
>
> which content type(s) to search, which specific module search to use (node, help, user or any module that implements search), which input type to use (with Elements), advanced criteria For all these choices, there are options to switch between a select box, checkboxes or radio buttons, and also customize the selector label and the default - Any - text.
>
> Advanced options There are also options to:
>
> change the default search box label, add a default text in the search box, add advanced search criteria, change the default submit button text, use an image instead of the submit button, change the order of all the elements, include some elements in a popup block, add a filter to the results page, show/hide basic and/or advanced search in the results page, show/hide meta data in the results page, multiple search paths

---
Tags: 7, hooks, search, forms
---


# Question
Title: Sending a file in e-mail message body using Views Send
I have a drupal site that holds thousands of client details. What I want to do is to create an emailer to send out campaigns to the clients.

So far I have a view set up to filter clients by company and using Views Send I can send all selected an email.

What I would like to do is to send a file in the email. Either that or be able to paste the data from the file into the email. The file is stored in my drupal site within a content type.

Does anyone know how I would be able to do this? To be able to select from a list which file to send in the e-mail message body?

# Answer
> 0 votes
take a look at the Entity Email Module:

> The Entity Email module lets users create their own email templates which can be used to send emails. Emails sent can also be recorded in the DB if needed. Emails can be sent programmatically or by the mean of the Rules module.
>
> Main features:
>
> Built on top of the amazing entity API
>
> Allow token substitution
>
> Templates can also contain attachments (PDF, TXT...)
>
> Rules module support, so email actions can be triggered by any Rules
>
> Supports the MimeMail module for HTML emails.
>
> Build with the fields API Emails sent\> can be recorded in DB

I don't know that it will integrate with Views on it's own, but you may be able to manually make it work the way you want.

---
Tags: views, emails
---


# Question
Title: How to see an overview of the download statistics of all modules on drupal.org?
At the moment the usage overview page on drupal.org gives an idea of the number of sites using a certain module. However as noted this includes information from only sites that include the update status module which means it is biased toward newer sites, is there a way to see an overview of the download statistics of a module as well in a similar view?

# Answer
As you mentioned, d.o. has an API from which you can retrieve project information. For your purposes, you can retrieve module downloads with the following URL:

```
https://www.drupal.org/api-d7/node.json?type=project_module

```

The JSON output has a property called `list` which is an array of node objects for each module project. Each node object contains a property called `field_download_count` that contains the project's download count.

Note: results are paged (100 per result) from the web service so you'll have to iterate through 307 pages of results to get all module projects (the JSON output contains a `first`, `last`, `prev`, `next` property with URLs that let you navigate through the pages)
> 2 votes

# Answer
You can get information about a particular module in both `XML` and `JSON` format by accessing URL:

**Eg: (For Views Module) :**

*XML format:*

https://www.drupal.org/api-d7/node.xml?field\_project\_machine\_name=views

*JSON format:*

https://www.drupal.org/api-d7/node.json?field\_project\_machine\_name=views

---

Reference: https://www.drupal.org/api
> 3 votes

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


# Question
Title: How to remove 'Main Menu' from my mobile view (using Superfish)?
I am using Bootstrap Business theme and I put Superfish module in my theme.

The problem is when it appears in Mobile View the title of *"Main Menu"* appear.

I would like to remove that title. However, I don't know how to make that.When click on the menu, it also involve that title.

Any suggestions?

# Answer
> 1 votes
Go to **admin/structure/block** and look for **Main Menu** (should be in the Superfish region).

Click **configure** and set the title to not display. As the instructions for the **Block title** field say:

> Override the default title for the block. Use `<none>` to display no title, or leave blank to use the default block title. This field supports tokens.

# Answer
> 1 votes
I also tried configuring the block title to `<none>` but it didn't work.

Instead, the title comes from the menu settings. Go to **admin/structure/menu** (D7) and **edit menu** and change **Title**.

You can't leave it blank so you may be able to enter some whitespace characters. For me, I instead edited the title to just "Menu".

---
Tags: navigation
---


# Question
Title: Allowing users to choose between two sort options in a view
I have a view of user accounts.

I want to allow visitors to the site to choose to **sort**this view by login date or by account creation date in a view (Views 3, Drupal 7).

It's easy to expose the sort operator to users, but is there a way to let users select which sort is applied first (creation date or login date)?

I thought about just cloning the view, and then changing the sort on the second view and linking them together, but if possible I would like to avoid duplication.

# Answer
> 1 votes
You can do that with Better Exposed Filters. I've combined two sorts together that way before, one selected with Ajax refreshing sort, then having the secondary sort tied in with the same. I would checkout the handbook links on that page for more direction, they have some pretty extensive recipes there that you could use as a base to start from.

handbook page for further reference

---
Tags: views, users
---


title: Direct Link to a Quick Tab

text:
# Question
Title: Direct Link to a Quick Tab
Is there a way for me to create a direct link to a Quick Tab? I have a taxonony term page with two tabs one contains some view result and the other is specific page of site like quiz take url(node/23/take).

# Answer
If you want to find the link to load a tab, just hover over the tab and copy the link of that tab. You will notice that the link has an argument appended on the end that looks something like:

?qt-myquicktab=1#qt-quicktabs

```
      Note: The # sign and anything after that in the argument above is not actually required.
      You should change it to ?qt-myquicktab=1

```

This tells Quicktab to load the second tab (Quicktab starts counting at 0) in the third Quicktab block that you have created (a Quicktab ID of 3).

All you need to do is,place this URL argument on the end of any link that you want to load the alternative tab as the default and you are done.
> 4 votes

---
Tags: blocks
---


# Question
Title: How to embed a quicktab instance in a page?
How do I can embed a qiucktab instance in page? I'm not going to create a region and assign the quicktab into that region. is there anyway to do such thing without using region?

# Answer
You can use QuickTabs Field Collection module. Module page says :

> The Quick Tabs Field Collection module provides a field formatter for rendering field collections as Quick Tabs.

**Usage :**

> 1. Go to the Manage Display page for any Entity that contains a field-collection field.
> 2. Change the formatter to QuickTabs
> 3. Click the gear icon on the right to access the formatter settings.
>
> (REQUIRED) Enter the machine-name of the field to use for the tab values.
>
> (REQUIRED) Enter the machine-name of the field to use for the tab contents.
>
> Optionally tick the box to strip all HTML tags from the tab content.
>
> Optionally add custom classes that will output in the field-collection wrapper div.
>
> Optionally configure the available QuickTabs options.
> 4. Adjust formatter settings for each of the fields in the field-collection.
> 1 votes

# Answer
After creating the quicktabs, you can render the quicktab programatically from the template file of that page.

Please put the below code inside your template file:

```
  $quicktabs = quicktabs_build_quicktabs('myquicktab');
  print render($quicktabs);

```
> 3 votes

---
Tags: 7, blocks
---


title: Embed form within a form

text:
# Question
Title: Embed form within a form
I am building on an existing site, adding / modifying functionality to it.

There is a form, which is a part of a (sort of a) multi-step form which I need to alter, and add another form to it.

So, I added the following to the existing form:

```
// Some form elements above this.
$form['new_form_element']['search'] = drupal_get_form('MY_PROJECT_search_form');
// Some form elements after this

```

And the `MY_PROJECT_search_form` function returns the form, which is then embedded in the original form. The form is rendered properly.

However, when I submit the form, I get the following notice :

> The form has become outdated. Copy any unsaved work in the form below and then reload this page.

I believe that is because the two forms are getting submitted at the same time, and the submission of one of them is failing.
I have tried adding `$form_state['rebuild'] = TRUE` to the submit functions, but it did not work.
I have also tried adding an `markup` type field and embedding form in as
`'#markup' = render(drupal_get_form('MY_PROJECT_search_form'));` But, I am not able to implement AJAX in the embedded form after that.

Is there any other *better* way to embed a form?

**Note:** There is no other option then to embed a separate form to the current form.

# Answer
Nesting forms in other forms is not valid in html. see this post html nesting forms in forms

You can always try calling the form directly via the actual form function instead of via drupal\_get\_form since the function returns a valid array of form elements. you'll have to somehow compensate for the missing `hook_form_alter` and `hook_form_FORM_ID_alter`.

Note I haven't actually tried this, so I'm not sure how it will react on the empty $form/$form\_state params.

That already gets you all the fields in a dynamic way. Perhaps you can build a similar work around calling the submit/validate handlers directly too.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How do you load a select field with pre-selected items when the Chosen module is installed/enabled?
How do you load a select field with pre-selected items when the Chosen module is installed/enabled?

I am using the following code.

```
$my_list = array('item1' = 'item1', 'item2' = 'item2', 'item3' = 'item3');
$form['list_info']['my_list'] = array(
  '#title' => t('Select a list to manage:'),
  '#type' => 'select',
  '#options' => $my_list,
  '#default_value' => $my_list,
);

```

The select field shows up empty. Clicking it reveals the items and I can select them, but I need the field to show up with the items selected.

# Answer
> 0 votes
Your select field is currently only accepting one selected option. This is why it won't allow an array as a default value. (It expects a string or an integer).

The following select field allows more than a selected option.

```
$form['list_info']['my_list'] = array(
  '#title' => t('Select a list to manage:'),
  '#type' => 'select',
  '#options' => $my_list,
  '#default_value' => $my_list,
  '#multiple' => TRUE,
);

```

---
Tags: forms
---


# Question
Title: php in views contextual filter for different user roles
I am attempting to filter a view based on a php contextual filter, however the filter needs to come from different sources depending on the users role:

administrators - from a query string
all other roles - from an entity reference field on the user

I am using draggable views which prevents me from using two separate views.

So far I have:

```
global $user;

    if (in_array('administrator', array_values($user->roles))) {
        $query= $_GET['query'];
        return $query;
      }
    else{
        $user_uid = user_load($user->uid);
        $myfilter = $user_uid->field_custom['und']['0']['target_id'];
        return $myfilter;
    }

```

The else filter works great but it is failing to filter for the administrator role.

# Answer
You could also use `user_access()` to see if a user has the rights do to something.
If you use some core administrative tasks, you can be sure that it will trigger only for administrators

E.g.

```
global $user;
if (user_access('administer site configuration')) {
  $query = $_GET['query'];
  return $query;
}
else{
  $account = user_load($user->uid);
  $myfilter = $account->field_custom['und']['0']['target_id'];
  return $myfilter;
}

```

Note: I used `$account` instead of `$user_uid` to store full user object; most of the contributed modules and core name the variable this way.
> 0 votes

---
Tags: views
---


title: Two commands won't work with drush

text:
# Question
Title: Two commands won't work with drush
I try to run typical commands like `drush cc all` or `drush pm-uninstall` while in the folder of my local site (in my pc, win 7 sp3), and yet I get error say:

> 1. "'mode' is not recognized as..."
> 2. "There were no modules that could be uninstalled".

I've never seen the first error in windows 7, and I do have modules to uninstall, so why won't I see a list? thanks,

# Answer
Based on this comment https://github.com/drush-ops/drush/issues/58#issuecomment-23716869 it has something to do with your PATH variable. Fix it and the error should go away.

> Added C:\Windows\System32;C:\Windows\SysWOW64 to PATH in Environment Variables. Both errors gone the 'mode' one and the other one about console window width.
> 2 votes

---
Tags: drush
---


# Question
Title: Is there any Russification of the Simple MCQ Drupal 7 module?
Is there any Russification of the Simple MCQ Drupal 7 module? How to translate it?

# Answer
> 2 votes
It looks like it is partially translated: Translate Simple MCQ to Russian.

To import the translation that exists into your own site, enable the core **Locale** module and add **Localization update**. You can now use the standard Drupal translation site interface to translate the bits that are not translated.

Please help the community by adding your own translations to Localize.Drupal.org

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


# Question
Title: Content Field Type For Video, Images and Text
I'm trying to decide what the best method would be for creating a new Content Type who's field type would allow me the flexibility to use ANY type of content inside of it. Almost like a blank HTML container. I'd like the flexibility to manipulate the content in that space to a video, rotating image, static image or text based on my needs. Would there be an appropriate field type to manage all of this?

Or would the appropriate answer be to create three separate content types that live one after the other in the area that I want them to be, then have them hide if no content is visible in them?

Apologies if this question has been answered in the community to date, but I've yet to come across a straight answer.

Thanks in advance!

# Answer
The best result for me actually came from creating a new field type similar to my body tag and altering information inside of it using the html view. Worked exactly as I needed it. The Conditional Fields option was far more than I needed.
> 0 votes

# Answer
I think that the best solution is to use Conditional Fields module.
You can manage dependencies between fields.
So you should have one field **type** and all type fields separately and display them depend to **type** field.
> 1 votes

---
Tags: entities, nodes, files
---


title: Feed import breaks due to ajax error

text:
# Question
Title: Feed import breaks due to ajax error
When I tried to do a feed import, I got the following error.

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: /batch?id=1726&op=do
> StatusText: OK
> ResponseText \[Omitted text\]

(There are quite a few similar errors on the web, for example https://www.drupal.org/node/1125060.)

When I changed the author field to 'site-admin' (see attached image), auto-complete seems running and popup the following error.

> An AJAX HTTP error occurred.
> HTTP Result Code: 200
> Debugging information follows.
> Path: http://site-prod.local/user/autocomplete
> StatusText: OK
> ResponseText: my\_site\_name | my\_username
>
> \[url1\]
> \[url2\]
> \[url3\]
> \[Search form\]
> \[Primary tab: View (active tab)\]
> \[Edit\]
> \[Shortcuts\]
> \[Broken links\]
> \[Devel output\]
> \[My username\]
> \[Email\]
> \[Omitted text\]

The log message is the following.

> Warning: Cannot modify header information - headers already sent by (output started at /var/aegir/platforms/production/drupal-7.27/includes/common.inc:2700) in drupal\_goto() (line 703 of /var/aegir/platforms/production/drupal-7.27/includes/common.inc).

If I put `exit()` right after `drupal_json_output()`. The related problem seems resolving itself.

When I run `drush -d -v search-index`, the indexing stuck at around 61%. This indicates some problems with a node.

>

# Answer
> 0 votes
By using xdebug and vdebug (plugin for vim), I am able to step into the code and ping point the issue.

In https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_cron\_run/7

I put a watchdog: `watchdog('bug_cron', '<pre>'. print_r($module, true). '</pre>');` inside.

```
// Iterate through the modules calling their cron handlers (if any):
foreach (module_implements('cron') as $module) {
      // Do not let an exception thrown by one module disturb another.
      try {
        // NOTE: put a watchdog and look at your log message.
        // You should able to see which module causes issues.
        watchdog('bug_cron', '<pre>'. print_r($module, true). '</pre>');

        module_invoke($module, 'cron');
      }
      catch (Exception $e) {
        watchdog_exception('cron', $e);
      }
    }

```

It is the search module causes issues. Disable it, then uninstall the setting via **the drupal menu GUI**, then it is fixed, but I am not sure why search module causes issues.

**Updated at 2015-05-26**

It turns out my module uses hook\_url\_inbound\_alter + drupal\_goto caused issues. It is not easy to debug, because there are couple of side effects.

---
Tags: feeds
---


# Question
Title: Views - Edit, view, delete node in dropdown
In facebook, on every post, there is a little arrow in the corner with content about that post.

Is there a Drupal module which allows me to achieve this?

What I want to do is:

I have different content types which a user can add. I want to add the 'edit node', 'delete node' and 'view node' link into a small dropdown which allows the user to choose any of these options by clicking on the icon.

# Answer
This can be achieved through contextual links. You can add new links through a custom module or with the Custom Contextual Links module (CCL).
> 2 votes

---
Tags: views, navigation
---


title: Adding background color to table rows

text:
# Question
Title: Adding background color to table rows
I was wondering if it is possible to change the background color of a table row.

I want to display certificate files, and if that certificate is going to expire in longer than 30 days the color green would be good. If it is less then 30 days color orange and if it's expired color red.

I tried finding it on the internet but I can't find anything like this.

This is how my current column data looks like.

```
'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),

```

I already tried adding '#class' =\> array('bgcolor' =\> '#ffffff'), or just 'bgcolor' but that doesn't work.

Thanks in advance!

Complete code

```
$qry = db_select('push_notifications_api', 'n');
$qry->join('push_notifications_certificates', 'u', 'n.ios = u.cert_id');
$cert_table = $qry
->fields('n', array('app_name', 'ios'))
->fields('u', array('cert_id', 'cert_name', 'upload_date', 'expiration_date'))
->OrderBy('u.expiration_date', 'ASC')
->execute();

$form['certificates']['table'] = array(
 '#theme' => 'table',
 '#header' => array(t('Application'), t('Certificate'), t('Uploaded'), t('Expiry Date')),
 'rows' => array(),
 '#weight' => 30,
);

foreach($cert_table as $key => $val) {

$form['certificates']['table']["#rows"]["'r$key'"] = array(
    'c1' => array(
        'data' => array('#type' => 'item', '#markup' => t('@app_name', array('@app_name' => $val->app_name))),
    ),
    'c2' => array(
        'data' => array('#type' => 'item', '#markup' => t('@cert', array('@cert' => $val->cert_name))),
    ),
    'c3' => array(
        'data' => array('#type' => 'item', '#markup' => t('@uploaded', array('@uploaded' => date('d-m-Y', $val->upload_date)))),
    ),
    'c4' => array(
        'data' => array('#type' => 'item', '#markup' => t('@expiry', array('@expiry' => date('d-m-Y', strtotime($val->expiration_date))))),
    ),
);
}

```

# Answer
> 1 votes
You can add class for the row and add background for this class via the css

```
$row = array(
  array(
    'data' => array(
      array( 'data' => 'cell1'),
      array( 'data' => 'cell2'),
      array( 'data' => 'cell3' ),
    ),
    'class' => array('my-class'),
  )
);

print theme('table', array('rows' => $row));

```

---
Tags: forms
---


# Question
Title: Commerce Node Checkout free option skip cart/checkout/payment
I am working on a free/paid listing site. I setup Commerce Node Checkout with Node Checkout Expire and have a free version(14 days) and a paid "featured" option (30 days). The paid option should go to cart-\>checkout-\>payment while the free option should act and behave as if Drupal Commerce wasn't installed.

I was looking around rules but I can't seem to find the proper events/conditions/actions to basically treat free listings as regular drupal nodes. I don't really want to track orders for free listings, but I also don't want to mess Drupal Commerce's reporting up either.

Can rules do this? And if so, what would be the proper events/conditions/actions to bypass Commerce all together and just publish the node if "free listing" is selected under listing options for Node Checkout.

Thanks

# Answer
You can write a custom module that implements hook\_node\_submit() and that sets

```
$form_state['values']['commerce_node_checkout_skip'] = True;

```

if the free version is selected.
> 1 votes

# Answer
Here is the code that worked for me:

```
function custom_node_submit($node, $form, &$form_state) {

```

global $user;

if (in\_array('administrator', $user-\>roles)) { $form\_state\['values'\]\['commerce\_node\_checkout\_skip'\] = True; $node-\>status = 1; }

return $form;

}
> 0 votes

---
Tags: 7, commerce
---


title: webform2pdf blank page

text:
# Question
Title: webform2pdf blank page
I am using webform2pdf. I'm having an issue with the download PDF button; it goes to a blank page when it goes to a path like **/node/3/webform-results/downloadpdf**. Does anyone have a fix for this?

# Answer
what PHP errors do you get when errors are set to be shown on the website from your php.ini or htaccess file. webform2pdf has a dependency on TCPDF library and they often become out-of-sync with one another. So as a developer you need to be sure you're using the recommended versions of the required dependencies.
> 1 votes

# Answer
I actually went on a long shot and downloaded the tcpdf straight from http://www.tcpdf.org and created a folder named /sites/all/libraries/ from there I took the tcpdf folder and dropped it in that directory. Fixed everything. The Drupal module for TCPDF does not work.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How to add custom content before hook_form()
Form uploads image and if image is uploaded I'd like it to be displayed before the form. What is the right way to do this?

# Answer
> 2 votes
You can use hook\_form\_alter() to add a 'markup' element to the form, with a negative weight so that it floats to the top. For example:

```
mymodule_form_alter(&$form, &$form_state, $form_id) {

  // Only act on my module's form.
  if ($form_id != 'mymodule_form') {
    return;
  }

  $form['top'] = array(
    '#type' => 'markup',
    '#markup' => 'This will be at the top of the form!',
    '#weight' => -100,
  );
}

```

---
Tags: forms
---


# Question
Title: Spam registrations even after adding domain to Mollom blacklist
I have a problem with spambots from itregi.com and drupaler.org that registers accounts on my clients Drupal site. I have Spamicide and Mollom installed and I have also added the domains to Molloms blacklist in the following format: Author e-mail contains itregi.com

But they still get accounts with these domains as email. I don't know what to do more or if I am using the blacklist wrong? Any suggestions?

# Answer
Try using Honeypot, it's a module specially designed for spambot filtering...
> 4 votes

# Answer
I was having the same problem in the last few days and every time i delete the created account by the spammer or block it, the spammer re-register again.

At my website the spammer@drupaler.org did create too many nodes using the (Forum Module).

**Solution in my case** was to use User restrictions module

I am using User restrictions module now for 2 days without any problem and the spammer can not post any node and can not even register.

Advice: The module send an error message that the email (e.g. spammer-email@example.com) that is used to register is not allowed, may be you change this message to something tricky like (the email syntax is not correct), in case it is a human spammer not machine spammer.

I hope this can help.
> 1 votes

# Answer
I know this does not necessarily answer the question as such but it might aid you. If you use something like Captcha during registration (https://www.drupal.org/project/captcha) it will prevent loads of the spambots to successfully register. You can then set your permission to deny posting unless registration was completed.
> 0 votes

# Answer
A site we just inherited also just got hit last night. Around 11pm I got an alert mail for the account using a bit more than expected bandwidth. Quickly saw that the site was being overrun with spam. New registrations with the same (and more) domains as OP.

I blocked new user registrations and disabled new content creation permission. Then added fail2ban with a few filters to pick up the problem botnet attempts and block them and went to bed (not a critical time for this site).

Today we tweaked the fail2ban filters and also added BOTCHA. When we removed the spam accounts we also took note of the account names the botnet created.

The new Fail2Ban filters apply to three jails, one for failed login attempts by the botnet's previously created accounts (now deleted), one for BOTCHA and one for incorrect CAPTCHA (for log entries from before today when we used Honeypot).

PS: I can only guess that it's a botnet - the IPs change all the time and still hit the site now with thousands already blocked.

I prefer not using off-site services like Mollom or reCAPCHA. But BOTCHA will work with them too if you want.
> 0 votes

# Answer
Thanks @LarS for pointing me in the right direction. I've removed the evil core hack. Here's the code for the same functionality using hooks if it's helpful to anybody.

This code can be used in the template.php file of your theme or in a custom module, however it should be put in a custom module because it is functionality, not visuals. If you were to change your theme you would still want to keep this.
Replace THEME\_OR\_MODULE\_NAME with your own theme or module name.

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the user registration form to add custom validation.
 */
function THEME_OR_MODULE_NAME_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom validate function.
  $form['#validate'][] = 'THEME_OR_MODULE_NAME_user_validate_form';
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the user edit form to add custom validation.
 */
function THEME_OR_MODULE_NAME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  // Add a custom validate function.
  $form['#validate'][] = 'THEME_OR_MODULE_NAME_user_validate_form';
}

/**
 * Custom validation for the user register and edit forms.
 */
function THEME_OR_MODULE_NAME_user_validate_form(&$form, &$form_state) {
  $mail = $form_state['values']['mail'];

  if (!THEME_OR_MODULE_NAME_user_validate_mail_not_spam($mail)) {
    form_set_error('mail', t('The e-mail address %mail is not valid.', array('%mail' => $mail)));
  }
}

/**
 * Validate an email address against known spam domains.
 *
 * @param string $mail
 *   The email address to validate.
 *
 * @return boolean
 *   Returns TRUE if the email passes validation and FALSE otherwise.
 */
function THEME_OR_MODULE_NAME_user_validate_mail_not_spam($mail) {
  if (preg_match("/@tattooideas1.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@saccatalyst.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@cowgirljules.com/i", $mail)) {
    return FALSE;
  }
  if (preg_match("/@drupaler.org/i", $mail)) {
    return FALSE;
  }
  return TRUE;
}

```
> 0 votes

# Answer
Instead of a custom module, I simply created a rule using the Rules module.

---

**Rules**
> +Add new rule

(call it whatever you want. Registration Blacklist maybe?)

**Events**

> Before saving a user account
>
> After saving a new user account

**Conditions**

> Text comparison
>
> Parameter: Text: \[account:mail\], Matching text: drupaler.org

(Make sure it is set to "contains")

**Actions**

> Block a user
>
> Parameter: User: \[account\]
>
> Delete entity
>
> Parameter: Entity: \[account\]

---

If a person wanted to, they could setup the action to ban the IP address instead or in addition to blocking the user.

The reason for the two events is because you can't delete the account until after it's been saved. Ideally, I wish Rules would simply kick them out and not even create an account period, but that's beyond my knowledge at this point.

If a person wanted to have some fun, they could setup a page redirect and send the bot/user to some funky webpage, ideally a redirect loop page. For example, I setup another action rule that redirects the dupraler.org people to a page that will cause a modern browser to hang: http://www.neocodex.us/forum/topic/118146-redirectshtml-pranktroll-page/
> 0 votes

# Answer
I wrote a little module to help me with this: Its not on Drupal.org at this time but it is available on GitHub here: https://github.com/coralnexus/regstop

RegStop is very straightforward to use - though it is fresh - like 2 days old ;-)

If anyone has suggestions for improvements, let me know.

Thanks, Derek
> 0 votes

# Answer
Not to step on Derek's toes, but I was also working on a module for the very same issue. I did not see this until now though, but do plan on adding even more validation to the user registration form down the road.

It started as a project for a client of mine, he was getting hammered with at least a dozen human spam registrations a day from the drupaler.org and yandex.com e-mail domains. Put this together for him this week, so it is pretty young as well.

Registration validation
> 0 votes

---
Tags: users, advertising
---


# Question
Title: How to make labels of fields selectable?
Does anybody know if there is a module to make labels of fields selectable, for instance Field course:

* Abc in DCT
* 123 today
* listening pop

so if I select 123 today, in my content display I would have:

**course:** 123 today

but I would like to change **course:** by **workshop:** at the visualization of the content and have "course" for the other two (Abc in DCT and listening pop). So maybe there is a module that allows label selection, I haven't find it yet.

# Answer
> 0 votes
You'll have to make a custom field formatter with a settings form where you select the label and then output it accordingly.

Like in this tutorial about field formatters

# Answer
> 0 votes
There are a couple of modules you can try:

Besides these modules, you can do it in code using custom formatters like Suranga said or implementing theme preprocessors.

# Answer
> 0 votes
What you are describing is actually two fields. One is the "label" (a textfield limited to a select number of otpions, or a taxonomy term), the other is the description.

You can do this a bunch of different ways, depending on your needs:

* Entity References (allows multiple)
* Field Collections (allows multiple)
* Field Groups/Fieldsets (only one)

If I understand correctly, you want to be able to click on the description and the label will automatically show up. To do that, I would predefine the labels and descriptions by creating them in a separate entity. Then, you could select these from a list of descriptions by using the Entity Reference module.

---
Tags: nodes, entities
---


# Question
Title: Users cannot log in to new site in multisite
I am working with the Drupal multisite functionality. I have been asked to implement the following architecture:

mysite is a Drupal site with several angular pages. mysite/backend is a separate site with a separate user store that mostly acts as a headless Drupal system. For political reasons, it is very important that the users in mysite/backend not be stored in the same database as the users in mysite .

Anyway, from what I have read about Drupal multi-sites, I have taken the following steps.

1. I started with a working site and performed the following steps to add a second one
2. Create a symlink, making the /backend a symlink to the web root:

```
ln -s backend .

```
3. Add entries to my sites.php (because with our deployment workflow, the site name cannot always match with the domain name. Also allows us to test with xip.io).

```
$sites['mysite.dev'] = 'mysite';

$sites['mysite.dev.backend'] = 'mysite.backend';

```
4. I created a directory named mysite.backend .
5. In mysite.backend, I created a directory corresponding to all directories in mysite.
6. In mysite.backend, I created the following settings.php file:

```
$databases = array (
   'default' =>
   array (
     'default' =>
     array (
       'database' => 'XXXXXX',
       'username' => 'XXXXXX',
       'password' => 'XXXXXX',
       'host' => 'localhost',
       'port' => '',
       'driver' => 'mysql',
       'prefix' => '',
     ),
   ),
 );

 $update_free_access = FALSE;
 $drupal_hash_salt = 'k_vtgGjzCyq0mp0dsxDk1gILuEs6G5ODP5aJuQsAUuc';
 $base_url = 'http://mysite.dev/backend';  // NO trailing slash!
 ini_set('session.gc_probability', 1);
 ini_set('session.gc_divisor', 100);
 ini_set('session.gc_maxlifetime', 200000);
 ini_set('session.cookie_lifetime', 2000000);

```
7. I go to `/backend/install.php` and go through the install process. Everything goes smoothly
8. I click the link to view the new site, and enter the admin login credentials (for the new site. I made it a point to have separate logins for each site)

My problem is that when I go to the /backend directory of my test site and log in with my credentials, I get the standard authentication error behavior if I login with an invalid username or password, but when I supply the correct credentials, I get redirected to /backend/node, but I see no indication of being logged in. If I try to go to the admin pages, I get an access denied error. I still see the login block. If I click the reset password link, I get a one-time login link in my email, but when I click it, I get a message that says that the link has expired.

Forgive me if this is too verbose or missing details. This seems to be a messy problem. Has anyone run into similar issues with Drupal?

# Answer
This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

```
RewriteRule . index.php [L]

```

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that browser you are able to login, then it's probably a cookie problem (in your original browser).
> 0 votes

# Answer
I solved the problem by deleting my cookies and trying again. After doing so, I was not able to reproduce the issue. I tried logging in to the front end and then logging in to the backend (I was able to log into both sections as different users), and I tried it in the reverse order (logging into the /backend first and then the front end). In both cases, I was able to log in correctly.
> 0 votes

---
Tags: 7, multi-sites, users
---


# Question
Title: Save my link configuration with drush or else?
I just modified my database so I can translate 2 link from a block that I made.

The translation won't show up until I go here `admin/structure/menu/item/1022/edit` and press Save.

I would like to know if it's possible to do this with Drush or something else. Im in a Multisite environnement with more than 100 site, I would like to automate that task.

I tried to make a custom module to try and save my configuration but it doesnt seems to work. I followed these steps : http://www.jpstacey.info/blog/2014-08-05/programmatically-creating-drupal-menu-link-item

# Answer
Block translation is difficult, as mentioned also in this interesting article about Successful multilingual sites in Drupal7.

Maybe you want to consider using the BEAN module combined with the Entity Translation module?

PS: How make your Drupal website multilingual is another related article.
> 0 votes

---
Tags: blocks, drush, navigation
---


title: 7 - Download file and generate page

text:
# Question
Title: 7 - Download file and generate page
I've got a form that gathers some data. The data is then modified and should be passed to the user as a file. To manage this I did the following:

```
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: text/out');
header('Content-Disposition: attachment; filename="file.out"');
echo $file;
module_invoke_all('exit');
exit();

```

What I need now is to somehow display some additional info to the user without losing the input data. In other words, when user submits a form, it should let him download the file and then, for example, print out a success message, contents of the file downloaded or another form. Is there any way to do that?

# Answer
> 0 votes
You need to isolate that code out of your form submission handler. When you set the `Content-Disposition: attachment` header it's going to override the browser behavior of loading a new page.

Instead, you should have your form handler save the output file & generate a success page containing a download link (in case your user doesn't have JS support) and run a JS `setTimeout()` function that will trigger a download after X seconds. See this SO post for an example.

The download link path can be generated with `hook_menu()`. Its callback function will use your code snippet above. Depending on the content of the download (e.g. sensitive personal data), you may need to protect this path. This can be done in a variety of ways.

---
Tags: 7, forms, files
---


# Question
Title: Bootstrap THEME_menu_tree() on a new menu
I'm using Drupal 7 and the Bootstrap theme. In the template.php file, I am successfully theming the primary menu (main menu) to enable extra list styles with the following code.

```
function MYTHEME_menu_tree__primary($variables) {
  return '<ul class="custom-style">' . $variables['tree'] . '</ul>';
}

```

I would also like to theme a new menu (menu-banner), but I can't access it as expected, with the following code.

```
function MYTHEME_menu_tree__menu_banner($variables) {
  return '<ul class="custom-style">' . $variables['tree'] . '</ul>';
}

```

The new menu is successfully defined in `MYTHEME_preprocess_page()` in the template.php file.

```
$menu = menu_navigation_links('menu-banner');
$vars['banner_nav'] = theme('links__menu_banner', array('links' => $menu));

```

I'm able to render it as *banner\_nav* in the page templates.

Is there something I'm missing, or is there something specific to Bootstrap that is different from what reported from `theme_menu_tree()` documentation?

# Answer
This isn't related to Bootstrap. In your preprocessor you're using `theme_links`, which is unrelated to menus. Your "menu" isn't being output as a menu at all.

If page preprocessing is necessary, you can try:

```
function THEMENAME_preprocess_page(&$vars) {
  $menu = menu_tree_all_data('menu-banner');
  $vars['banner_nav'] = menu_tree_output($menu);
}

```

Or you can render the menu block (these are automatically generated if you have the Blocks module enabled):

```
function THEMENAME_preprocess_page(&$vars) {
  $block = block_load('menu', 'menu-banner');
  $vars['banner_nav'] = _block_get_renderable_array(_block_render_blocks(array($block)));
}

```

In page.tpl.php:

```
<?php print render($banner_nav); ?>

```

Either will work.

If you don't need to preprocess the menu, you can simply position it via the Blocks admin UI.

I hope that helps!
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to configure the toolbar in CKEditor?
I've installed CKEditor in my drupal instance and all seems to work well until I realized, I can't change the text size (missing drop down). I went to `admin/config/content/ckeditor` and selected and saved `Toolbar` `full` from the examples, which feature a `Size` dropdown as shows in the "current toolbar' preview. I did this for both existing profiles, `Advanced` and `Full`. However, if I then go to `admin/structure/block/add` to add a new block, `CKEditor` still does not show a size drop down so that I could change the text size. Why not, what am I missing?

**EDIT 1**

I went to http://ckeditor.com/download and downloaded the **full package** which I then just copied to my existing `sites/all/modules/ckeditor/ckeditor` overwriting the existing **standard package** copy. I've reset the cache\`, however what I'm seeing now is this:

The *Size* drop-down is visible but other buttons have failed to load their icons.

Any suggestions?

# Answer
It's possible you are using a version of CKEditor (the editor, not the drupal module) that doesn't have the font size and family plugin.

See the different versions at http://ckeditor.com/download (click the "Compare packages" link to see what is included in each package).

On that page you can see that only the full version has the "Font Size and Family (font)" package, so if you are using one of the other version then it won't have that package.

It is also possible to use the "Or let me customize CKEditor" option to create a custom version of CKEditor that contains just the plugins you require. If using that make sure you include the "Font Size and Family (font)" package.

There is an issue here on Drupal.org regarding messages to the admin to notify them of missing plugins.
> 3 votes

# Answer
I "fixed" it by completely reinstalling CKEditor as described on http://docs.cksource.com/CKEditor\_for\_Drupal/Open\_Source/Drupal\_7/Installation that worked just fine!
> 1 votes

---
Tags: wysiwyg, toolbar
---


# Question
Title: Why are foreign language registrants redirected to home page after registration?
When someone registers an account in English (default language) the registrant is redirected to the Login page with a message: "A welcome message with further instructions has been sent to your e-mail address."

So far, so good.

But when a registrant select a foreign language on the registration page (like **es** for Spanish,) he is redirected to his profile page after submitting his registration.

Anyone knows how to fix this bug so that it behaves like the English registration? Or a workaround?

# Answer
> 1 votes
I wonder if your issue could be related to the language specific homepage (frontpage).

The relative URL to display as the front page is specified within admin/config/system/site-information. Make sure you specify a value for it that is different for each of the site's languages. To do so, you have to make it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

For more details about this, refer to my answer at How to make content translation available for front page?

---
Tags: 7, users, i18n-l10n, redirection
---


# Question
Title: Does the Services module implement caching on GET requests?
Before I build a REST server with the Services module, I'd like to know if the responses to the GET requests are being cached? I searched Google and it seems that caching wasn't implemented, however, those articles are from 2011 and 2012.

# Answer
No, the Services module does not support caching on GET requests:

http://cgit.drupalcode.org/services/tree/resources/node\_resource.inc?h=7.x-3.x#n253

As you can see, each time the resource's callback function is invoked, it makes a call to `node_load()`. You can use the Services API to preprocess/overwrite the resources to implement caching though:

http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x
> 2 votes

---
Tags: caching, services
---


# Question
Title: What are some examples of filter Correct faulty and chopped off HTML?
In Drupal one of the text filters that is enabled by default is the filter **Correct faulty and chopped off HTML**. As I understand it must fix HTML bugs.

Can anybody please give some example(s) of situations, where it can help?

I am confused, because if I do not close some tag (for example `DIV`), and save the result, then I get the same result in both cases (= it doesn't matter if that filter is turned on or off).

# Answer
In Drupal, there is rule that a text filter should *never* change anything that the user saves. The "Correct faulty and chopped off HTML" follows this rule. That is why you don't *see* any changes in the body field when you edit.

However, the filter will fix your HTML when the text in the body field is *rendered* (i.e. displayed to the user).

For instance, if you use the Drupal 6 or 7 "Filtered HTML" text type (which makes use this filter) and put the following faulty and chopped off HTML in the body (this is *all* you put in the body of a node):

```
<ul><li>xyzzy

```

and examine the *rendered* HTML in your browser (for instance using Ctrl-U or *Firebug* in Firefox), you'll see that it is corrected to:

```
<ul><li>xyzzy
</li></ul>

```

## Screen shots

Text in editor:

>

Rendered text, as displayed by *Firebug*:

>
> 2 votes

# Answer
Refer to these 3 issues that contain a reference to that "Correct faulty and chopped off HTML" filter.

In these cases it has to do with the usage of some 3rd party library that generates something (like SVGs), which occasionally may produce xHTML that is not 100 % correct. Refer to this issue comment for an illustration of how I ever got in XML parsing errors, because of such HTML filter issues ...

So if you're a module (co-)maintainer using a 3rd party library that has such issues, then this faulty-work around is about the only thing you can do to address that somehow.
> 0 votes

---
Tags: input-formats
---


title: Check if node is displayed as page?

text:
# Question
Title: Check if node is displayed as page?
In Drupal 6 to check if node is displayed as page we can use:

**Select the condition to add** \- \> `Check a truth value`

**Truth value** \- \> `<?php echo $page ?>`

How to do this in Rules 2.x for Drupal 7? I don't see the condition with name `Check a truth value`

# Answer
Assuming I have interpreted what you're trying to do, try adding the Event "Content is viewed", with the Condition "Content is of type" and configure the Condition to be of node type: 'Page'. If you could explain exactly what you're trying to achieve I may be able to suggest a better solution!
> 2 votes

# Answer
I did it this way

EVENT: Content is viewed of type \[...\]

Conditions: **Execute custom PHP code: "return $view\_mode == 'full';"** (without the quotes)

Actions: Unflag, flag and so on...
> 0 votes

---
Tags: 7, rules, database
---


# Question
Title: Could someone explain the 'hit' and 'miss' status in memcache per page output?
I've instructed memcache to append stats to each page. Someone did an excellent job explaining the memcache reporting page. However, I've since stumbled upon this appended information shown below and am curious.

Specifically what are miss and hit status?

(enlarge picture)

# Answer
> 4 votes
The hit/miss statuses are the result of the cache being touched as the result of the operation. For the given operations:

* **Get:** (for a single key) **Hit:** data was retrieved from the cache; **Miss:** data was found not in the cache.
* **Set:** **Hit:** data was stored in the cache; **Miss:** data was not stored in the cache.
* **GetMulti:** (for multiple keys) **Hit:** data was retrieved in the cache; **Miss:** data was found not in the cache.
* **Delete:** **Hit:** data was removed from the cache; **Miss:** data was not removed (for a missing key) in the cache.

---
Tags: caching
---


# Question
Title: Drupal fails to send password reset mail
Drupal (7 and 8) does not send mail from password reset form and I can not find any bug or failure. More interesting is that it *does* send mail notification that there is new drupal version.

I have checked following with *positive* results:

* send mail from system
* send mail from PHP CLI
* send mail from PHP CLI as wwwrun user
* send mail from php script in standard php webpage with mail() function.

I have separate /etc/msmtprc config file for apache and only apache can read it.

Apache php.ini contains:

```
error_log = /var/log/php_errors.log
sendmail_path = "/usr/bin/msmtp -C /etc/msmtprc_apache -t"
mail.log = /var/log/php_mail_errors.log

```

settings.php contains

```
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
$conf['error_level'] = 2;

```

Successful mails are logged in mail log. No failures. Apache error log and php log shows *no errors*. There are no significant entries in drupal database log.

If I change something in apache msmtprc configuration *none* of the mails from php are successful. Msmtp correctly relays on gmail with tls.

There is absolutely no indication of error. It seems that everything is OK from the system side but drupal still fails to send the password reset message. (Message is not in the spam nor sent items folder.)

Probably important note is that drupal is migrated to fresh openSUSE installation and that mail worked on old installation for all drupal sites (2x d7 and 1x d8). SELinux and AppArmor are currently not enabled.

Any help is appreciated...

# Answer
Long answer in short: ***mod\_rewrite was not active*** in apache :(

Failure drove me crazy so I finally started to think outside of the box :) Misleading point was initial error with msmtp configuration (owner of the config file must be wwwroot (in openSUSE case))...
> 2 votes

---
Tags: emails, users
---


# Question
Title: filter to remove external links from text
Do you know about a way to automatically remove external links after user submits node? I want to keep only internal ones. I am not able to find any text filter or module which does that. Thank you for advice.

# Answer
> 1 votes
You can create your own filter and use function url\_is\_external

As an example you can check filter "filter\_url" in module filter (available in drupal core)

---
Tags: 7, input-formats
---


title: synchronize two webform select options

text:
# Question
Title: synchronize two webform select options
In my webform page I have two select options components:

Item number: 20 | 20 , 35 | 35 , 40 | 40

Price List: 100 | 100 , 200 | 200 , 300 | 300

I need these two select options components synchronized. If one selects Item number (35) the price list also moves to (200).

Is there any module available to do that, or how can I get the synchronization of the two select options.

# Answer
I do not need to synchronize, but combine (merge) them in one list.
In Webform Views Select I can also combine by using Rewrite Results,

field "Item Number", exclude from display

field "Price List", Rewrite Result: \[value\] - price \[value\_1\]

Then I can get in a single select option list:
20 - price 100
35 - price 200
40 - price 300
> 0 votes

---
Tags: webforms
---


title: Submit not executed

text:
# Question
Title: Submit not executed
Why is my submit function never been executed?

```
/**
 * Implements hook_menu().
 */
function simpleexample_menu() {

  $items['simple-example-page'] = array(
    'title' => 'Simple Multi-Step Form',
    'page callback' => 'create_request_custom',
    'access callback' => TRUE,
  );

  return $items;
}

function create_request_custom() {
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('request');

  $form['simpleexample'] = array(
    '#type' => 'value',
    '#value' => simpleexample_get_session(),
  );
  $form['actions']['submit']['#submit'][] = 'create_request_custom_submit';

  return $form;
}

function create_request_custom_submit($form, &$form_state) {
  // never executing that
  $params = array(
    'nid' => $form_state['values']['nid'],
    'session_id' => $form_state['values']['simpleexample'],
  );
  .....

}

```

# Answer
Forms need to be called via `drupal_get_form()` that processes your $form array into a form. Including the submit handling. So it should look like more like this:

```
/**
 * Implements hook_menu().
 */
function simpleexample_menu() {

  $items['simple-example-page'] = array(
    'title' => 'Simple Multi-Step Form',
    'page callback' => 'drupal_get_form', // Tell drupal to use the drupal_get_form function.
    'page arguments' => array('create_request_custom'), // Pass the form function as argument for the page callback.
    'access callback' => TRUE,
  );

```

Also you'll probably want to add the `$form` and `&$form_state` variables to the form function.

```
function create_request_custom($form, &$form_state) {
  // Your form function
}

```
> 2 votes

---
Tags: forms
---


# Question
Title: Template file for Views exposed filter block
Views has a great feature where you can expose the exposed filters as a block (**Exposed form in block** under **Exposed form**).

So what's the "standard" way to theme these? Is there a Views template for this (I couldn't find one), or do I theme it with a renamed block.tpl.php?

# Answer
> 3 votes
Actually, although the exposed filter block does not have any template file in the list under **Theming information**, you can theme it with a views template file like this:

`views-exposed-form--MYVIEWNAME.tpl.php`

There is an example `views-exposed-form.tpl.php` in the Views module theme directory.

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


title: How to call a javascript function?

text:
# Question
Title: How to call a javascript function?
I have included in my theme a new javascript library(Easy-Responsive-Tabs-to-Accordion) which converts horizontal tabs to accordion. So I have included in my .info theme scripts\[\] = js/Easy-Responsive-Tabs-to-Accordion/js/easyResponsiveTabs.js

Then,according to the instructions,I have to call the javascript function $('#demoTab').easyResponsiveTabs();

My question is:Where to add this javascript function? thanks

# Answer
> 2 votes
You can continue `easyResponsiveTabs.js` as normal JS and add your function call. Also you can call this function almost anywhere (like tpl.php file), even in the block/node (where you are using this script for conversion) wrapped in the `<script>` tag like:

```
<script>
$('#demoTab').easyResponsiveTabs();
</script>

```

I would go with drupal\_add\_js in `template.php` file of your theme.

# Update

Using drupal\_add\_js you can do it like this:

```
drupal_add_js('jQuery("#demoTab").easyResponsiveTabs();', 'inline');

```

# Answer
> 1 votes
Easy way of adding JavaScript/jQuery is by using JSinjector module. Enable the module and goto `Admin -> Config -> Development -> JS injector`, add your jQuery. In JS injector body section, place your script using the function call as:

```
(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {

          // your script goes here
$('#demoTab').easyResponsiveTabs();

}
};
})(jQuery);

```

Then, you can select inline/preprocessor type.

---
Tags: javascript, blocks
---


title: Flag not updating on user profile?

text:
# Question
Title: Flag not updating on user profile?
I'm using panels to display user profiles and each profile has a 'follow' flag (non global). I've used a view called 'follow-users' to capture few users and one of the field within that View is the same 'follow' flag link.

When someone flags a user within 'follow user' view the flag on user profile still stays unflagged

Can anyone please help to figure out why it’s happening?

Thanks

# Answer
I would take a look at the flag set up in each of your displays, and make sure you are using the same Flag - it's an easy oversight if you have multiple types of Flags and can cause this sort of behaviour.
> 0 votes

---
Tags: 7, views, panels, users, flags
---


title: Pagination in search results

text:
# Question
Title: Pagination in search results
I have installed search configuration module to alter pagination on search results. I've set the pager limit in *Configuration \> Search settings \> ADDITIONAL NODE SEARCH CONFIGURATION \> RESULTS* to 3 (which should trigger pagination), but no pagination is appearing when I am logged in whereas when I am logout, it is showing pagination having 2 items per page instead of 3.

# Answer
> 0 votes
This is, presumably, by design. If you look at Search Config's query alter function, you can see that the function returns (without limiting results) if you're you're the superuser. Hence, when you're logged in with UID = 1 you will not see the pagination.

---
Tags: 7, search
---


# Question
Title: Field sharing between translations of a node?
Assume I have a content type which I want to be translated to 5 languages! And assume that my content type has 10 fields, with 7 of them being some numbers and 3 of them are text.

There is absolutely no need for these 7 fields to be translated to each language. But when I translate each content I should spend a lot of time on filling same values for each language.

# Answer
How about storing the 7 fields in a 1st content type and the 3 remaining fields in a 2nd content type. And then use the References module to connect them to each other? That way you'd only have to "translate" the content type with the 3 fields.

A variation of this could be using entities, whereas you'd then use the Entity Reference module instead. And probably also the Entity Translation module, for which quite some Community Documentation is available to get you started.

Drupal 7's new multilingual systems compilation contains an interesting set of posts about multilanguage websites ...

PS: You may also want to look at Node translation vs. Entity (field) translation for a lot of extra info/details about both variations of translations.
> 2 votes

---
Tags: 7, nodes, entities, i18n-l10n
---


title: Remove language prefix from base URL

text:
# Question
Title: Remove language prefix from base URL
I've installed the Internationalization module in order to make a multilingual site, I've set italian as default language, but there's a problem, the front page is always in english. I've checked the base URL and I've noticed that there's a language prefix, is it possible remove?

# Answer
> 1 votes
Sometimes I think people do not know how to use search in our time. You can find the answer on `stackoverflow`, similar question has already been asked. Have a nice day.

# Answer
> 0 votes
I think you're mixing a few things here, and I also think that the comment in the question (which should actually have been posted as an answer ...), is only like a partial fix or workaround. What, IMHO; the real issue seems to be here, is that the URL of the homepage has not been defined as a "multilingual" variable, as further explained below.

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.

For more details about how to get this done, refer to my answer to How to make content translation available for front page?.

---
Tags: i18n-l10n
---


# Question
Title: Deleting field collection bundle programmatically from core
I have a field collection bundle that I want to remove from my site. I was googling how to do that and came upon these instructions, but they seem to be from the ECK module, and only apply to entities created by eck. The company I work for has a module review process and this module doesn't have a stable release yet.

So, ideally there would be a way for me to do this from core, or at least the field collection module, without extra modules. Is there?

*Edit* "No, you can't" is a perfectly acceptable answer. If that's the case I would like to stop chasing down blind alleys.

# Answer
> 2 votes
So apparently what I needed was `field_delete_field()`, and then a `field_purge_batch()`.

# Answer
> 0 votes
Did you try solution described in this blog post? http://gix.my/blog/programmatically-creatingdeletingmodifying-field-collection-item-node

# Answer
> 0 votes
It seems to me that "*this module doesn't have a stable release yet*" is a slightly incorrect statement for the ECK module. It should rather be something like "*this module doesn't have an official release yet*".

Below are some qualifications that should help to proof that the 7.x-2.0-rc7 version of ECK is pretty stable:

If you're looking for even more of such qualifications, then you may want to check if there are any other applicable criteria as described in the "Maintenance Scorecards" (which can also be applied to ECK).

For all these reasons, I think the "RC7" part of the version ID is rather a matter of "What's in a name". Consider using these types of arguments to try to get an exception to your company's policies (review process).

# Answer
> 0 votes
https://www.drupal.org/node/2384323

this patch will help you. it worked for me.

---
Tags: entities
---


# Question
Title: Passing Node Variables to Content and Blocks
I'm really struggling with how to get variables created in page.tpl.php and node.tpl.php in rendered content and blocks. I hope I'm just missing something simple.

Basically, I'm trying to have a unique ID number passed around the site. To do that (as far as I know) I need to add it to all the links, IE **/?a\_uid=123456**.

I'm generating the random ID in success\_preprocess\_page (full code is below).

```
function success_preprocess_page(&$variables, $hook) {
  //echo '<pre>'; print_r($variables); echo '</pre>';\

        if (isset($_GET['utm_campaign']))
            $adkey = $_GET['utm_campaign'];
        elseif (isset($_POST['utm_campaign']))
            $adkey = $_POST['utm_campaign'];
        else
            $adkey = NULL;

        if (isset($_GET['a_uid']))
            $a_uid = $_GET['a_uid'];
        elseif (isset($_POST['a_uid']))
            $a_uid = $_POST['a_uid'];
        else
            $a_uid = NULL;

    if ($adkey != NULL)
    {
        $a_uid = "123456";
    }
    $variables['adkey'] = $adkey;
    $variables['a_uid'] = $a_uid;

   if(isset($variables['a_uid'])){
    // add the flag to the node to say it's been set and there is only a single node to display
       if(isset($variables["page"]["content"]["system_main"]["nodes"]) && count($variables["page"]["content"]["system_main"]["nodes"]) == 2){
            $keys = array_keys($variables["page"]["content"]["system_main"]["nodes"]);
           // Set a new variable called sidebar_first equal to true on the node.tpl level
           $variables["page"]["content"]["system_main"]["nodes"][$keys[0]]['#node']->a_uid = $a_uid;
      }
    }
}

```

Any links that are in page.tpl.php, ex:

```
<a href="programs/?a_uid=<?php echo $a_uid; ?>">Programs</a>

```

Display the correct **$a\_uid** variable result of 123456.

And if I try to echo **$a\_uid** in node.tpl.php, ex:

```
<?php $a_uid = $node->a_uid; ?>
<?php //echo 'A_UID: '.$a_uid.'<br><br>'; ?>

```

Also displays 123456 fine.

But if I try *anything* like this in my content pages (even with them set as PHP Code Text Format, which correctly processes other PHP code), everything result is blank.

For instance, I currently have a content page that has this in it, trying to hit all the marks I can think of:

```
<?php echo $a_uid; ?>
<?php print $a_uid; ?>
<?php echo $node->a_uid; ?>
<?php echo $content->a_uid; ?>
<?php print $node->a_uid; ?>
<?php print $content->a_uid; ?>
<?php print ($page['a_uid']); ?>
<?php print ($node['a_uid']); ?>

```

Not a single one of those displays anything.

As far as I can tell it seems like the variable is just not getting passed to the content? I just don't understand why, or how to fix it.

I assume this is standard, but this is how my content is being called in node.tpl.php:

```
print render($content);

```

I am also having the same problems in my header and footer blocks. Those are being called from page.tpl.php as:

```
<?php print render($page['footer']); ?>
<?php print render($page['header_button']); ?>

```

Any help with this would be greatly appreciated. Thanks! Oh and 123456 is just a placeholder in here for my random unique ID generator code :)

# Answer
> 0 votes
PHP Code format is executed in isolation from other codes, so it is not in the domain of any preprocess function, So by using PHP Code format, there is no way get data from preprocess functions, Even the `hook_preprocess_block`.

About the variables, try to set them in `hook_preprocess_node`, because as far as I know Drupal builds components in the manner of inside to the outside, so first the node.tpl and node preprocess function get called then page.tpl and page preprocess function.

To display the variable in the block, you can also build global variable. How do I add a new Global Variable? explains how to do it.

# Answer
> 1 votes
Apparently I was just looking at my process wrong this morning. I went back to it after reading what you wrote and realized I could just use in my html.tpl file and it would handle everything I need it to do.

But thank you for answering! I'm not sure how but what you posted led me in the right direction after I was reading your links :)

---
Tags: nodes, 7, theming
---


# Question
Title: Where do you edit the css of a basic bootstrap theme in Drupal 7?
I've download the latest release of the original Bootstrap theme for Drupal 7, and Installed it, and yet it is unclear to me where could I change it's css?

I need to RTLize the template, i.e make it RTL instead of the default LTR, and for this I need to flip some properties in the template's Style.css file (or whatever main css file) of this template as I did in the past with almost any other template...

I tired to search a bit in the theme's folder and just couldn't find such file... The following image display my navigation (at least the most logical part of it):

# Answer
Bootstrap for Drupal 7 requires a lot more setting up than ordinary themes. Make sure you read and follow the instructions about installing and sub-theming Bootstrap.

If you intend to change the CSS, it is strongly recommended that you create a sub-theme with all the Bootstrap 3 source files. This method is the most dynamic and will grant you the ability to change the variables and utilize the mixins provided by Bootstrap. It entails downloading and extracting the latest Bootstrap source into your sub-theme and place it in a folder named *boostrap*. Note that you will need to uncomment the lines under "METHOD 1: Bootstrap Source" in your sub-theme's `.info`-file if you want to use this method for sub-theming.

If you've done all this correctly, the folder structure of your sub-theme (here called `my_bootstrap`) should look like this:

Bootstrap CSS is generated by means of the CSS preprocessor less, so you do not edit the CSS directly. Instead look up the file `my_bootstrap/less/overrides.less`. You add your CSS overrides to this file. Then, to make your overrides effective, you can compile the file `less/style.less` (which includes `overrides.less`) to CSS with this CLI command (provided you're in the `my_bootstrap` root directory).

```
lessc less/style.less > css/style.css

```

If you want a simpler, but less flexible method, you may use a Bootstrap CDN. It utilizes CDN Bootstrap via the base theme, but will still allow you to override the existing CSS styling in the sub-theme.

If you choose the CDN method, to override the default Bootstrap base theme settings, you copy the settings you want to change from the base theme into the sub-theme's .info-file. To override CSS, you edit the provided `css/style.css` with your own overrides.

As always, after changing the CSS, remember to clear the cache to make your changes effective.
> 3 votes

---
Tags: theming
---


# Question
Title: How to not let users remove the entity reference once they added
I'm using D7.
I have one content type, let's say Content-A. And, the Content-A has a field whose field type is Entity Reference. Content-A's authors can reference other user with the content through the Entity Reference field.
I want to make authors be unable to remove the entity reference between the content and other users who he already referenced. Does anybody know how to do it? Any advice will be appreciated.

# Answer
> 0 votes
Using `Hook_form_FORM_ID_alter` on the node form and disabling the field for users that are not the initial author should work.

Code is untested but shows the general idea behind the solution

```
HOOK_form_FORM_ID_alter($form, &$form_state){
  global $user; // Get the current logged in user information
  if($user->uid != $form_state['node']->uid){ // Is the current user not the original author of this node?
    $form['FIELD_REFERENCE']['und'][0]['#access'] = 0; // Restrict access to this field (You'll have to check where exactly in the tree to place this).
  }
}

```

# Answer
> 0 votes
You could use the field permissions module for this, give access to add but not edit their value. https://www.drupal.org/project/field\_permissions

---
Tags: entities
---