# Question
Title: Appending multiple tables in drupal 7 module
I am appending three new tables in my custom module using `hook_update`, but it is throwing below error when I try to run `update.php` file

```
PDOException: SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'schema_version' at row 206: UPDATE {system} SET schema_version=:db_update_placeholder_0 WHERE (name = :db_condition_placeholder_0) ; Array ( [:db_update_placeholder_0] => 71000 [:db_condition_placeholder_0] => pemedia_library ) in drupal_set_installed_schema_version() (line 181 of H:\xampp\htdocs\brandenglish\trunk\includes\install.inc).

```

**Here is my code**

```
//my module install file
    <?php

    /**
     * @file
     * Install, update and uninstall functions for the pemedia_library module.
     * https://www.drupal.org/node/876250
     */
    /*
     * *Implementing hook schema
     */

    function pemedia_library_schema() {
        /*
         * Photographic page table
         */
        $schema['pemedia_gallery_table'] = array(
            // Example (partial) specification for table "node".
            'description' => 'Table for storing information about image media.',
            'fields' => array(
                'imid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator image ID.',
                ),
                'image_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the media.',
                ),
                'low_res_path' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for low resulution images.',
                ),
                'medium_res_path' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for medium resulution images.',
                ),
                'high_res_path' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for high resulution images.',
                ),
                'description' => array(
                    'type' => 'text',
                    'not null' => TRUE,
                    'size' => 'big',
                    'description' => 'Description of the image',
                ),
                'bussiness_channel' => array(
                    'type' => 'varchar',
                    'length' => 60,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Type of bussiness channel.',
                ),
                'user_right' => array(
                    'type' => 'varchar',
                    'length' => 60,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Type of user right.',
                ),
                'geography' => array(
                    'type' => 'varchar',
                    'length' => 60,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Geographic location.',
                ),
                'expiry_date_timestamp' => array(
                    'type' => 'int',
                    'not null' => FALSE,
                    'description' => 'Expiry date of image items, as a Unix timestamp.',
                ),
                'usages_restriction' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'information about usages restriction.',
                ),
                'owner' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Information about the owner.',
                ),
                'copyright_information' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Copyright information about the image.',
                ),
                'other_information' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'other information about the image.',
                ),
                'status' => array(
                    'description' => 'status field for the images',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('imid'),
        );

        /*
         * Illustration page table
         */

        $schema['pemedia_illustration_table'] = array(
            // Example (partial) specification for table "node".
            'description' => 'Table for storing information about custom media.',
            'fields' => array(
                'mid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator custom media ID.',
                ),
                'media_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the custom media.',
                ),
                'illustration_file_path_1' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for first illustration file.',
                ),
                'illustration_file_path_2' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for second illustration file.',
                ),
                'illustration_file_path_3' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'CDN url path for third illustration file..',
                ),
                'description' => array(
                    'type' => 'text',
                    'not null' => TRUE,
                    'size' => 'big',
                    'description' => 'Description of the custom media',
                ),
                'bussiness_channel' => array(
                    'type' => 'varchar',
                    'length' => 60,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Type of bussiness channel.',
                ),
                'user_right' => array(
                    'type' => 'varchar',
                    'length' => 60,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Type of user right.',
                ),
                'owner' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Information about the owner.',
                ),
                'file1_size' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'size of the file1.',
                ),
                'file2_size' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'size of the file2.',
                ),
                'file3_size' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'size of the file3.',
                ),
                'status' => array(
                    'description' => 'status field for the custom media',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('mid'),
        );

        /*
         * table schema for application page table
         */
        $schema['pemedia_application_page_table'] = array(
            'description' => 'Table for storing information about static media asset of applicaton page .',
            'fields' => array(
                'appid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator static media asset ID of application page .',
                ),
                'app_content_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the static media asset of applicaton page',
                ),
                'app_content_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => 'application',
                    'description' => 'Media Type for static media asset of applicaton page.',
                ),
                'status' => array(
                    'description' => 'status field for static media asset of applicaton page',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('appid'),
        );
        /*
         * table schema for product logos page table
         */
        $schema['pemedia_product_logos_page_table'] = array(
            'description' => 'Table for storing information static media asset of product logos page .',
            'fields' => array(
                'plogosid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator ID for  static media asset of product logos page .',
                ),
                'plogs_content_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the  static media asset of product logos page .',
                ),
                'plogs_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => 'product_logos',
                    'description' => 'Media Type for static media asset of product logos page .',
                ),
                'status' => array(
                    'description' => 'status field of static media asset of product logos page . ',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('plogosid'),
        );

        /*
         * Table for User content downloads
         */
        $schema['pemedia_user_content_table'] = array(
            'description' => 'Table for storing information about User content downlaods.',
            'fields' => array(
                'uid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator ID for User content downlaods.',
                ),
                'content_id' => array(
                    'type' => 'int',
                    'size' => 'big',
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Content Id of contents downloaded by user.',
                ),
                'content_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Media Type of contents downloaded by user.',
                ),
                'status' => array(
                    'description' => 'status field of contents downloaded by user.',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('uid'),
        );
        return $schema;
    }

    /**
     * Create new database table for static contents {pemedia_application_page_table, pemedia_product_logos_page_table, pemedia_user_content_table}.
     */
    function pemedia_library_update_71001() {
        /*
         * Table for application page
         */
        $table1 = array(
            'description' => 'Table for storing information about static media asset of applicaton page .',
            'fields' => array(
                'appid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator static media asset ID of application page .',
                ),
                'app_content_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the static media asset of applicaton page',
                ),
                'app_content_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => 'application',
                    'description' => 'Media Type for static media asset of applicaton page.',
                ),
                'status' => array(
                    'description' => 'status field for static media asset of applicaton page',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('appid'),
        );

        /*
         * Table for product logos page
         */
        $table2 = array(
            'description' => 'Table for storing information static media asset of product logos page .',
            'fields' => array(
                'plogosid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator ID for  static media asset of product logos page .',
                ),
                'plogs_content_title' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Title of the  static media asset of product logos page .',
                ),
                'plogs_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => 'product_logos',
                    'description' => 'Media Type for static media asset of product logos page .',
                ),
                'status' => array(
                    'description' => 'status field of static media asset of product logos page . ',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('plogosid'),
        );

        /*
         * Table for User content downloads
         */
        $table3 = array(
            'description' => 'Table for storing information about User content downlaods.',
            'fields' => array(
                'uid' => array(
                    'type' => 'serial',
                    'not null' => TRUE,
                    'description' => 'Primary Key: Unique aggregator ID for User content downlaods.',
                ),
                'content_id' => array(
                    'type' => 'int',
                    'size' => 'big',
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Content Id of contents downloaded by user.',
                ),
                'content_media_type' => array(
                    'type' => 'varchar',
                    'length' => 255,
                    'not null' => TRUE,
                    'default' => '',
                    'description' => 'Media Type of contents downloaded by user.',
                ),
                'status' => array(
                    'description' => 'status field of contents downloaded by user.',
                    'type' => 'int',
                    'length' => 1,
                    'not null' => TRUE,
                    'default' => 1,
                ),
            ),
            'primary key' => array('uid'),
        );

        db_create_table('pemedia_application_page_table', $table1);
        db_create_table('pemedia_product_logos_page_table', $table2);
        db_create_table('pemedia_user_content_table', $table3);
    }

```

Can some one help please. Thanks

# Answer
1. Change hook\_update function name to `pemedia_library_update_7001` (remove first occurrence of `1`)
2. If you want to add tables with hook\_update place it in `hook_schema`, than try like in example below. That is much cleaner way.

```

    function yourModule_update_7001() {
      $schema = module_invoke('yourModule', 'schema');
      db_create_table('table_name_1', $schema['table_name_1']);
      db_create_table('table_name_2', $schema['table_name_2']);
      db_create_table('table_name_3', $schema['table_name_3']);
    }

```
> 1 votes

---
Tags: 7, hooks, updating
---


# Question
Title: How do i get the node id using menu_hook
Hi I try to get the node id when user edit the node by the code below:

```
       function test_plugin_menu(){
            $item = array();
            $item['node/%/edit'] = array(
                'page callback' => 'test_plugin',
                'page arguments' => array(1),
                'access callback' => TRUE,
                'type' =>  MENU_LOCAL_TASK,
            );
            return $item;
        }

        function test_plugin($node_id){
              dpm($node_id);
         }

```

I get into a blank page when i edit a node. Please help, thank you !

# Answer
Although you pass a node id into the url, it get's converted to a fully loaded node by the time your callback function is called. You could read up on it on the documentation page for hook\_menu, under section `Auto-Loader Wildcards`.

In `node.module` you will see this menu item for node edit:

```
$items['node/%node/edit']

```

Now, the path you are trying to register already exists in the node module, so that is where the WSOD comes from. You need to do a hook\_menu\_alter on it, or perhaps hook\_form\_alter if all you want to do is alter the node edit form.
> 1 votes

---
Tags: routes
---


# Question
Title: Filter after Custom Field Type in Custom Filter
I'm facing a problem with a custom field type in a custom filter. The field type isn't showing up in my filter-criterias in views. Do I have to tell the fieldtype somehow that it is filterable? Or is this a problem with my filter? I suppose the error is somewhere here:

```
function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $this->view->init_style();

    // Allow to choose all fields as possible.
    if ($this->view->style_plugin->uses_fields()) {
      $options = array();
      foreach ($this->view->display_handler->get_handlers('field') as $name => $field) {
        $options[$name] = $field->ui_name(TRUE);
      }
      if ($options) {
        $form['fields'] = array(
          '#type' => 'select',
          '#title' => t('Choose fields to combine for filtering'),
          '#description' => t("This filter doesn't work for very special field handlers."),
          '#multiple' => TRUE,
          '#options' => $options,
          '#default_value' => $this->options['fields'],
        );
      }
      else {
        form_set_error('', t('You have to add some fields to be able to use this filter.'));
      }
    }
  }

```

This is from my filter where it should show all fields, but does show only a few.

# Answer
If you create a new field type, you need to tell Views about it. The hook in question is https://api.drupal.org/api/views/views.api.php/function/hook\_views\_data/7

Through entries in this hook you tell views how to build its SQL queries and render the results. Once you have implemented the hook you'll need to clear cache and hopefully you'll see your fields appearing in the list of filters. If the query/render requirements are not addressed by Views' existing handlers, you'll need to write your own. https://api.drupal.org/api/views/views.api.php/group/views\_handlers/7
> 0 votes

---
Tags: views, entities
---


title: Basic template - new drupal project

text:
# Question
Title: Basic template - new drupal project
I would like to hear how other Drupal developers / companies are dealing with the following issues:

1. Suppose that as a company you often have to make small Drupal websites with minor changes everytime. Example: change theme, customize content types , add banner, ... . Do you use a "standard project" with standard modules , configuration, ..? And if so, how do you do this?
2. There are often security updates in Drupal. Suppose you have 20 drupal websites online and they all need the update. How can you automate this? Or how are you guys handling this?
3. If you have a staging and a production environment. How can you easily synchronize between those two? (dabatase-wise)

# Answer
Drush can do all of this:

> Suppose that as a company you often have to make small Drupal websites with minor changes everytime. Example: change theme, customize content types , add banner, ... . Do you use a "standard project" with standard modules , configuration, ..? And if so, how do you do this?

Look at Drush Makefiles (Drush itself now includes makefile support) or Provision as tools to easily spin-up very similar Drupal sites.

> There are often security updates in Drupal. Suppose you have 20 drupal websites online and they all need the update. How can you automate this? Or how are you guys handling this?

Again Drush and specifically using `Drush Aliases` and scripting a maintenance task such as `drush @alias up --security-only` using Bash and Cron come to mind.

> If you have a staging and a production environment. How can you easily synchronize between those two? (dabatase-wise)

Drush has a command `sql-sync` which syncs databases. `Drush aliases` can have `Groupings` and so typically for a site you will multiple aliases, 1 per deployment of the website. There is a Drupal documentation page discussing syncing deployments via Drush. issue something like:

`drush sql-sync demosite.drupal6.local @peer`

to sync 2 locations of a website (such as Dev and Production).

TLDR: Drush! Drush! Drush! :D
> 1 votes

---
Tags: 7
---


# Question
Title: Drupal Commerce cart page to enter items
I have a website I am working on, and I want to have a shopping cart page that is basically like a purchase order entry form, where a customer can enter the products he wants and then save it or post it, etc. In other words, so you don't have to go through the whole site selecting the products you want like a shopping cart, but rather just enter the item codes like you were writing out a purchase order. The website is for a producer basically and the customers are distributors.

I need to be able to enter products by item code or UPC (need both), and it would be a bonus if each user account could have a list attached to it where the customer could enter their own item codes for our products.

I hope this makes sense, can someone point me in the right direction?

# Answer
Check out the module Commerce Add to Cart Extras. This got me started. Also, the module Views Field View I used to show the quantity that was ordered last time.
> 0 votes

---
Tags: commerce
---


title: Enabled SSL - Login Doesn't work

text:
# Question
Title: Enabled SSL - Login Doesn't work
Followed the instructions on enabling SSL on Drupal 7 installation.

The SSL loads fine, all pages/links work but I'm unable to login.

When I try to login the screen just resets, go back to http and all works fine.

Any ideas what I may have missed?

Tried following the instructions twice now.

Regards,

Richard

# Answer
> 0 votes
It was a cookie issue. When I deleted all the cookies from browser it was fine.

---
Tags: users, ssl
---


# Question
Title: Architecture Guidance: Many off-the-shelf templated sites
I typically work on larger custom projects, but have found I have a lot of requests for projects at a lower price-point. I think I can serve this audience by creating a core Drupal installation profile, supplementing it with features, and installing one of a dozen or so custom themes I'll make.

I'd like this process to be as plug-and-play as possible. Right now I have an installation profile so all I need to do is 'git clone' the repo for that and then 'drush make' and 'drush install' to get up an running really quickly. This profile does some really basic things (sets admin theme, sets a development theme, installs an 'image gallery' feature which includes a content type and a taxonomy, etc).

So far I'm stumped on how I should develop things like layout (panels, display suite, theme templates?) and default content (devel generate?) during installation. Should I develop a base theme (I use a custom inuitCSS framework) and write sub-themes for it?

Has anyone else put anything else similar together? Do you have suggestions?

This has become a pretty complex endeavor and I'm wondering if it would be better to just build a site for each theme, zip it up and export the database.

# Answer
> 0 votes
I've made an infrastructure close to what you're describing, where we launch sites in 24h after a customer orders it.

Basically the architecture is:

* Aegir on a VPS. This allows us to spin up websites, service them, migrate them and sometimes clone them without messing on the server.
* An aegir platform with an install profile for our use case
* A generic zen subtheme for our use case with a bundle of front-end code
* Sweaver CSS for the layout customization of the specific site
* A basic features module that is installed by the install profile and multiple optional feature modules with extra views and content types, layouts managed by contexts, that administrators toggle using Feature Sets.
* Some additional optional contrib-space modules for things like node access customization

I try to avoid Panels as much as possible because of how much complication it adds. If you absolutely want your users to create fancy layouts, that may be a good choice, but at low price points the users have little tolerance for complicated usage. You might just be creating a lot of failure demand on yourself.

If you're going to just zip up sites, at least give Aegir and site cloning a chance first. You're going to save yourself a lot of work.

---
Tags: theming, drush, features, distributions, installation-profiles
---


# Question
Title: Restrict node to be shown only in a view and not by its url?
I created a node which has an entity reference to select a user. Then, I created a view to show the node only to the user referenced in the node.

This works fine, but the problem is that the node can be viewed directly through its URL. I need to restrict the node to be only shown through the view and not by its URL.

How can I do this?

# Answer
> 1 votes
The purpose of the Rabbit Hole module is exactly that, even if it doesn't apply just in the view case.

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

The module has a version for Drupal 7 and Drupal 8, although the later is still a beta version, on December, 2019.

# Answer
> 0 votes
See the Node access user reference module. It provides access permissions to users referenced from nodes.

From the project page:

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

Regarding the redirect itself - try using `hook_init()` or `hook_page_alter()`, checking the node type and then redirecting to appropriate page. Have a look at this answer as well.

# Answer
> 0 votes
You could do one of the following:

* create redirect rule to redirect from node page to view page (Redirect module),
* use Rules module to create a rule (when user is showing specific content, show permission denied page),
* create `hook_menu` and page callback to refuse access on specific criteria,
* hide fields on for node Display or use Field Permissions module to restrict access to specific fields

# Answer
> 0 votes
Elaborating Kenorb answer you can simply implement hook\_menu\_alter to change page\_callback or access callback for node urls something like below.

```
mymodule_menu_alter(&$items){
  $items['node/%node']['page callback'] = '_mymodule_my_content_type_redirection_rule';
}

/**
 * Page Callback for node/view page
 */
function _mymodule_my_content_type_redirection_rule($node) {
  if ($node->type == 'my_content_type') {
    drupal_goto('view_path');
  }
  else {
    return node_page_view($node);
  }
}

```

or if you want user to redirect to page not found you can do something like

```
mymodule_menu_alter(&$items){
  $items['node/%node']['page callback'] = '_mymodule_my_content_type_redirection_rule';
}

/**
 * Page Callback for node/view page
 */
function _mymodule_my_content_type_redirection_rule($node) {
  if ($node->type == 'my_content_type') {
    return(drupal_not_found());
  }
  else {
    return node_page_view($node);
  }
}

```

If you want to block the access for the node page

```
mymodule_menu_alter(&$items){
  $items['node/%node']['access callback'] = '_mymodule_node_access_rule';
}

/**
 * Access Callback for node/view page.
 */
function _mymodule_node_access_rule($node) {
  if ($node->type == 'my_content_type') {
    return FALSE;
  }
  else {
    return TRUE;
  }
}

```

---
Tags: views, nodes
---


# Question
Title: How to print the raw value of a custom user field in comments
I want to print a custom user field of the commenters. It is an Link field (https://www.drupal.org/project/link). Some users have that field completed and other not.

I've read a lot of posts related to this and tried several solutions. The only code that seems to nearly work OK is the following (found in https://drupal.stackexchange.com/a/129222):

```
<?php print render(field_view_field('user',user_load($comment->uid), 'YOUR-CUSTOM-USER-FIELD'));?>

```

The field shows, but there are 2 problems:

1) It causes 2 errors of "*Strict warning: Only variables should be passed by reference en include() (line 73 of .../templates/comment.tpl.php).*"

2) It shows the entire field, including its label and the complete link with the settings of the field. I only want the "raw" value of the field, the text that users introduce in the field.

Thanks for your help!

# Answer
You can use the field\_get\_items() to get all values for this field, after use field\_view\_value(). Example below:

// user\_uid\_optional\_load() will load the user object with all custom fields

$account = user\_uid\_optional\_load($comment-\>uid);

$items = field\_get\_items('user', $account, 'field\_name');

// as a example I'm using the number 0 as delta $value = render(field\_view\_value('user', $account, 'field\_name', $items\[0\]));
> 0 votes

---
Tags: 7, comments
---


# Question
Title: User automatically redirected to main language page
In my website I have the users automatically redirected to the main language page.

If for example: node/2 is the translation of node/1 when I type: www.mywebsite.com/node/2 I'm immediately redirected to www.mywebsite.com/node/1

**Note that it happens only for the anonymous users**

What's that? How could I check which module is redirecting the user?

# Answer
You can check your admin's modules page, for some module related to translation or the locale module.

But some modules can cause this behavior, such as Translation redirect module, part of the Internationalization (i18n) package.
> 0 votes

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


title: Port database queries

text:
# Question
Title: Port database queries
I have inherited a Drupal 6 site with some custom modules, all of which are making use of `db_query()`. Now I'm porting the site with all its modules to Drupal 7, and consequently have to adjust most of the database queries to work with the new DBTNG abstraction layer.

That's fine, but a very tedious task. Is there any automated way to do this, or a module to at least help you on the way?

# Answer
The closest thing I know of to take a string `db_query()` value would be the Query Coder module.

Be aware of its known issues:

**Known issues (taken from project page 01-29-2015):**

* INSERT queries must be specified in form "INSERT INTO table\_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
* Not support "-\>expression()" conditions for UPDATE queries.
* All tables and fields in SELECT query must be specified with aliases, in other (UPDATE, INSERT, DELETE) queries without aliases Example: RIGHT: "SELECT * FROM users u" NOT RIGHT: "SELECT * FROM users"
* All combining conditions in SELECT queries must be specified with aliases. Example: RIGHT: "SELECT COUNT(*) AS user\_count FROM users u" NOT RIGHT: "SELECT COUNT(*) FROM users u".
> 1 votes

---
Tags: 7, database
---


title: Character limit of field machine name?

text:
# Question
Title: Character limit of field machine name?
Is the machine name of a Drupal 7 field limited to 32 characters (including `field_`)? When I'm creating a new field, the UI seems to cut me off there, but I wonder if this can be circumvented.

I'm using prefixes to map certain fields to others, and the fact that my prefixed fields are getting cut off is going to make my matching logic slightly more complex.

# Answer
> 8 votes
Yes the length of the field name is hard-coded to 32 characters. It's most likely because the maximum length for a table name in MySQL is 64 characters, and the field API creates tables with names like `field_revision_field_name`. I imagine the core developers were erring on the side of caution.

It looks like you could squeeze an extra 17 characters out of the field name (`64 - 32 - len('field_revision_')`), but to do that you'll need to alter the `field_config` and `field_config_instance` tables in the database to increase the length of the `field_name` column (I guess to 49 characters).

I would imagine you'll also need to hook into the field UI forms to increase the `#maxlength` of appropriate text fields.

It might be easier to re-think your matching logic :)

# Answer
> 1 votes
I'm a bit late in here, but you may be interested to know that we came across this limit too and I created a module to strip the field\_ prefix off all fields created in the Field UI.

https://www.drupal.org/project/field\_name\_prefix\_remove

We've used this on various sites in a variety of circumstances with success.

Although this doesn't directly help you with your original question about the field length limit, it should go some way to give you an additional 6 characters to play with.

---
Tags: entities
---


title: Add field to existing content entity

text:
# Question
Title: Add field to existing content entity
I am trying to add a hidden field to all nodes in my module (for any node type even new ones being created later on). Would this be the correct code?

```
$field_storage = FieldStorageConfig::loadByName('node', $field_name);

if(empty($field_storage)){
  $field_storage = entity_create('field_storage_config', array(
    'field_name' => $field_name,
    'entity_type' => 'node',
    'type' => 'string',
  ));
  $field_storage->save();
}

 // Add the field, if needed.
$field = FieldConfig::loadByName('node', $node_type, $field_name);

if (empty($field)) {
  $field = entity_create('field_config', array(
    'entity_type' => 'node',
    'field_name' => $field_name,
    'field_storage' => $field_storage,
    'bundle' => $node_type,
    'label' => $label,
  ));
  $field->save();
}

```

I am just not sure which hook I should put it in. Most are giving me different errors… Also I want the field to be updated when the title field of a node is changed, which hooks would be the best to get the new title the user types? Or ist there some kind of event one could subscribe to?

# Answer
> 2 votes
Edit:

Your small edit changes this question more than you might think.

You have two ways to solve this.

1) Implement hook\_node\_type\_insert() and create your field config there. You need to be aware of a few things, like config sync, so you need to check $node\_type-\>isSyncing() before making any changes. Note that core stopped doing this for the body field. We do no longer add it automatically to all node types, only when one is created in the UI, as it had undesired side effects.

2) If you really want your field to always exist, no matter the node type, you can add it as a base field, which means it will work similar to the node title for example. See `entity_schema_test_entity_base_field_info()` for an example or see how content\_translation now works which is also using this approach. Be aware that this changes how the schema for your field is then created, it will be part of the node\_field\_data table and you need to run update.php after installing your module to update the table.

Old answer:

The only hook that you could use for this is hook\_install(), so that the field is created when the module is installed.

However, what you really want is to export them as default configuration of your module, I recently explained that in detail here: How to extend the basic user object upon installation?.

I'm going to actively ignore the second question because it has nothing to do with the first one. Create a separate question for that.

---
Tags: nodes, hooks, entities, 8
---


# Question
Title: Simpletest fails to create the field_config table
I'm only just getting into TDD with Drupal and unfortunately run into trouble right away. For some reason the simpletest####field\_config table isn't being created, and I don't get why; many other tables do get created. The (seemingly) relevant part of the error I get is:

> Base table or view not found: 1146 Table 'mcdonalds.simpletest405637field\_config&#039

coming from `/modules/field/field.crud.inc` (that is the project's root modules folder, NOT the modules folder in any theme or something).

I'm a bit stuck here, so I hope someone can tell me how to debug this, or even how to solve, that would be great of course;) Thanks!

# Answer
The issue is definitely related to cache backends.

Disable cache backends if you are testing using Simpletest classes.
> 5 votes

# Answer
It's not that the table doesn't get created, it's that something is reaching for field info before the table is there. That's not unheard of. What you need to do is use a debugger or `file_put_contents('/tmp/log', print_r(debug_backtrace(), TRUE));` and take a good look of where field info gets called. Something leaks into the install that simpletest runs.
> 0 votes

# Answer
I was having the same issue. Following the discussion above I found that while I had File Cache disabled, I still had $conf\['cache\_backends'\] and $conf\['cache\_default\_class'\] defined in my settings.php file. Commenting out those lines fixed the issue.
> 0 votes

---
Tags: database, testing
---


# Question
Title: Is it possible to show notification in MacOSX or Safari?
I'm using Drupal latest version with lot of modules. As you know, websites can Show notification in Notification center and/or Safari in Mac OSX. I see that, Wordpress has a module for this.

Is it possible to do it for Drupal?

# Answer
I dont know what the Wordpress module does.

But for the server running the website you can send notifications to the OS using Drush Notify (built into Drush version 6).

From the readme it has a few example functions:

* drush\_notify\_send(): Send a message to notifications center and audio.
* drush\_notify\_send\_text(): Send a message to notification center.
* drush\_notify\_send\_audio(): Send a message to audio system.
> 0 votes

---
Tags: views
---


# Question
Title: Redirect user to checkout if there is a product in cart
I'm using commerce checkout redirect module in my commerce site, but in the same time I enabled email verification to register, so the user is redirected to user profile page after he log in.
I want to automatically redirect him to checkout page, I created a rule 'when the user logged in - if order is a cart - then redirect to checkout'.
It always redirect the user even if the cart is empty.
What condition I should add to my rule to do that?

I tested a new condition suggested by Channel Islander, it's not working also in my site :

**My new rule:**

```
{ "rules_redirect_to_checkout_after_login" : {
"LABEL" : "redirect to checkout after login",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "checkout", "morad" ],
"REQUIRES" : [ "commerce_rules_extra", "rules" ],
"ON" : { "user_login" : [] },
"IF" : [
  { "commerce_rules_extra_compare_line_item_count" : {
      "order" : [ "site:current-cart-order" ],
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [ { "redirect" : { "url" : "[site:url]\/checkout" } } ]

```

} }

**Log when user log in**

> Information de débogage de Rules :
> " Reacting on event L'utilisateur s'est connecté.
> 0 ms Reacting on event L'utilisateur s'est connecté.
> 12.51 ms Evaluating conditions of rule redirect admins to dashboard after login. \[edit\]
> 13.394 ms The condition user\_has\_role evaluated to FALSE \[edit\]
> 13.403 ms AND evaluated to FALSE.
> 13.433 ms Evaluating conditions of rule redirect to checkout after login. \[edit\]
> " Reacting on event Calcul du prix de vente d'un produit.
> 0 ms Reacting on event Calcul du prix de vente d'un produit.
> 0.245 ms Evaluating conditions of rule Calculer les taxes : Sales tax. \[edit\]
> 0.254 ms AND evaluated to TRUE.
> " Rule Calculer les taxes : Sales tax fires. \[edit\]
> 0 ms Rule Calculer les taxes : Sales tax fires.
> 0.112 ms Evaluating the action commerce\_tax\_calculate\_by\_type. \[edit\]
> 1.159 ms Rule Calculer les taxes : Sales tax has fired.
> 1.478 ms Evaluating conditions of rule Calculer les taxes : VAT. \[edit\]
> 1.484 ms AND evaluated to TRUE.
> " Rule Calculer les taxes : VAT fires. \[edit\]
> 0 ms Rule Calculer les taxes : VAT fires.
> 0.079 ms Evaluating the action commerce\_tax\_calculate\_by\_type. \[edit\]
> " Executing rule Calculer TVA Maroc 10%. \[edit\]
> 0 ms Executing rule Calculer TVA Maroc 10%.
> 0.179 ms Evaluating conditions of rule Calculer TVA Maroc 10%. \[edit\]
> 0.188 ms AND evaluated to TRUE.
> " Rule Calculer TVA Maroc 10% fires. \[edit\]
> 0 ms Rule Calculer TVA Maroc 10% fires.
> 0.094 ms Evaluating the action commerce\_tax\_rate\_apply. \[edit\]
> 0.686 ms Added the provided variable applied\_tax of type commerce\_price \[edit\]
> 0.703 ms Rule Calculer TVA Maroc 10% has fired.
> 0.931 ms Finished executing of rule Calculer TVA Maroc 10%.
> 2.55 ms Rule Calculer les taxes : VAT has fired.
> 4.065 ms Evaluating conditions of rule add ka par options price. \[edit\]
> 5.286 ms The condition entity\_has\_field evaluated to TRUE \[edit\]
> 5.294 ms AND evaluated to TRUE.
> " Rule add ka par options price fires. \[edit\]
> 0 ms Rule add ka par options price fires.
> 2.376 ms Looping over the list items of commerce-line-item:field-options \[edit\]
> 4.179 ms Evaluating the action commerce\_line\_item\_unit\_price\_add. \[edit\]
> 6.962 ms Evaluating the action commerce\_line\_item\_unit\_price\_add. \[edit\]
> 8.387 ms Evaluating the action commerce\_line\_item\_unit\_price\_add. \[edit\]
> 8.746 ms Rule add ka par options price has fired.
> 14.085 ms Evaluating conditions of rule add ku pro options price. \[edit\]
> 14.208 ms The condition entity\_has\_field evaluated to FALSE \[edit\]
> 14.215 ms AND evaluated to FALSE.
> 14.283 ms Evaluating conditions of rule Annuler le prix pour les produits désactivés dans le panier. \[edit\]
> 16.268 ms The condition data\_is\_empty evaluated to FALSE \[edit\]
> 16.403 ms The condition entity\_has\_field evaluated to TRUE \[edit\]
> 16.963 ms The condition data\_is evaluated to FALSE \[edit\]
> 16.97 ms AND evaluated to FALSE.
> 16.99 ms Finished reacting on event Calcul du prix de vente d'un produit.
> 51.739 ms The condition commerce\_rules\_extra\_compare\_line\_item\_count evaluated to FALSE \[edit\]
> 51.746 ms AND evaluated to FALSE.
> 51.76 ms Finished reacting on event L'utilisateur s'est connecté.

# Answer
Install and use Commerce Rules Extra and use the condition "`Total quantity of product line items in the cart`".
> 1 votes

---
Tags: rules, commerce
---


# Question
Title: Can relationships be used to show Content and linked content in the same view
I'm trying to display content in a view and, beneath each entry, show a teaser of other content to which it is linked via Node Reference.

Here is roughly what I'm trying to show in my View:

```
Classroom A (title with link)
  L Teacher A (teaser)
  L Teacher B (teaser)

Classroom B (title with link)
  L Teacher B (teaser)
  L Teacher C (teaser)
  L Teacher D (teaser)

```

I've tried using Relationships and Contextual filters, but find them quite confusing and unintuitive.

The best I've managed is showing the same Classroom A link multiple times, one for each Teacher...

# Answer
* create a view filtering by classroom node types
* add a relationship like "Entity Reference: Referencing entity", it is related to teacher nodes that are referencing the classroom node.
* after this, add the classroom node fields and using that relationship, add the teachers fields.
* in the format views settings, you can choose a field to grouping this nodes, so, choose the node reference field.

This view configuration, it will works only if the node reference field is in teacher node.
> 0 votes

# Answer
What you need to do is to use the views\_field\_view module in combination with the entity reference module to build this. Enable both modules.

In your teacher content type create a entity reference field which reference the class that they teach (let call this field\_relate\_class).

Then you need to create a view of teachers as child view with a contextual filter using field\_relate\_class. The setting of the contextual filter should be following: When the filter value is NOT available -\> Provide default value -\> Content ID From URL When the filter value IS available or a default is provided -\> Specify validation criteria -\> Basic validator.

Then you need to create views of classes. Add the Content id field and add a Global Views field(views\_field\_view provide Global View). Make sure content id field is on top of Global Views field.

Once the Global Views field is added. Click on this field, the UI will populate setting for you to select the Views you want to display in this field. Select teacher views you created. There is a Contextual Filter Text box on this setting just fill the token of Content ID. Then Click Save. You are done.

Let me know if you find it difficult in this process.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Why does Drupal say I need to upgrade to 8.0.0 beta 6 when I'm already checked out on that tag?
I followed the git instructions at: https://www.drupal.org/project/drupal/git-instructions to get Drupal 8 :

```
git clone --branch 8.0.x http://git.drupal.org/project/drupal.git .

```

I then checked out the tag for 8.0.0 beta 6:

```
git checkout tags/8.0.0-beta6

```

And this command confirms I'm on that tag:

```
$ git name-rev --tags --name-only $(git rev-parse HEAD)
8.0.0-beta6

```

I then prepared for the install: set up a blank database and user and then used this drush command to do the install:

```
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://d8:d8@localhost/d8

```

When I go into the admin - admin/reports/status - I'm told that I'm using 8.0.0-dev and that Unknown release date (version 8.0.0-beta6 available) is available.

But why? when I was already on 8.0.0-beta6 branch *before* I ran the install.

# Answer
> 9 votes
update.module doesn't know about git.

It only understands .info(.yml in D8) files. And .info.yml files only get their version as part of the package building process. If you look at your system.info.yml, it doesn't say anywhere that it is beta6.

There is a module called git deploy, that is trying to fill that gap and extracts version information from git and tells update.module about it, there is a Drupal 8 release but I don't know if it works with the current version.

---
Tags: 8, updating, installation
---


# Question
Title: Rules- how to perform processing on cancelled accounts?
I have my site configured to allow users to cancel their accounts, in which case the account is blocked and the content is unpublished. I made a rule to act on the **Event** *after a user account has been deleted*, but my actions are not performed when a user cancels his/her account.

# Answer
For this kind of configuration, you need to use the **Event** *After updating a user account* with the conditions *User is blocked* (account) and *NOT User is blocked* (account-unchanged).
> 0 votes

---
Tags: rules
---


# Question
Title: Adding additional fields on user registration page (first name, last name)
In Drupal 7, what methods are there to add additional textfields to the user registration page at /user/register? I mainly want to also get their first + last name during registration. There doesnt seem to be a way via the interface to add these extra fields as required for sign up.

What is the quickest way of adding these extra text fields on sign up?

# Answer
> 0 votes
You just need to goto:

**Administration » Configuration » People » Account settings » Manage fields**

---
Tags: 7, users, forms
---


title: Strict warning: Creating default object

text:
# Question
Title: Strict warning: Creating default object
I am getting this error on my website.

> Strict warning: Creating default object from empty value in theme541\_preprocess\_html()

I found a patch https://www.drupal.org/node/1242362 by Damien McKenna but I don't know how to apply the patch that fixes the error.

# Answer
Applying patches is not actually a drupal specific issue and would be better on stack exchange, however there is a drupal documentation page so...

Check out the applying patches documentation.

However having said that, if you read that issue then you can see that patch was committed to that module 3 years ago and if you are using the latest release of the boron module (7.x-1.4) then that patch is already in there.

If you are applying the patch to something that isn't the boron theme then it will likely not work.
> 0 votes

---
Tags: 7
---


# Question
Title: How to hide language selector dropdown on node add page for a role?
I would like to hide the language selector dropdown on node add pages of multilanguage enabled content types.

What would be the best way? A jquery selector perhaps?

# Answer
Don't use jQuery for this. Better use `hook_form_alter`.

Check if user has target role. Print out your `$form` and find language select in printed array. Than hide language select.

There are 2 options for hiding:

1st:

```
$form['language']['#access'] = FALSE;

```

2nd:

```
$form['language']['#prefix'] = '<div class="element-invisible">';
$form['language']['#suffix'] = '</div>';

```
> 3 votes

# Answer
Depending on your needs, the default block settings configuration page may be all you need.

Go to `admin/structure/blocks/manage` and edit the language selector box. At the bottom of the screen, under **Pages**, set to show the block on *All pages except those listed* and then set the path to `node/*/edit`. If you need more fine-grained control, you can use the PHP code option.
> 1 votes

# Answer
First :

```
function myModule_form_alter(&$form, &$form_state){
 ....
 $form['#after_build'][] = 'my_custom_form_after_build';
}

```

Second:

```
function my_custom_form_after_build(&$form, &$form_state){
 $form['language']['#access']=FALSE;
}

```
> 1 votes

# Answer
you can disable it from drupal go to admin/config/regional/i18n/select

just tick "Hide content translation links"
> 0 votes

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


# Question
Title: Is there a postcode for deliveries checker module for drupal 7?
I'm thinking about using Drupal for a take away (delivery) ecommerce site and was wondering if there is a module that could calculate the the distance between the postcode added by the user and the shop locations (a few) and if its within a certain radius go ahead and allow the user to place the order. Is there such module available for drupal? if not, is there a similar module(s) that could be adapted to it?

Thanks

# Answer
There's no single module for this, but you can use a suite of modules. For example, you can take addresses stored in the Address Field module and then use Geocoder to geocode them and save the results in a Geofield. You can then use Rules to check the distance.

That said, there is no simple way to do this. In fact, there's an entire book about Mapping with Drupal.
> 2 votes

# Answer
There is a Commerce Postal Code Filter module

> Postal code (US ZIP codes, UK postcodes etc) filtering functionality for the Drupal Commerce checkout process. This module provides 2 main modes (whitelisting and blacklisting) which allow shop owners to restrict the areas of a country that they deliver to:
> 1 votes

---
Tags: commerce
---


# Question
Title: Filter menu parent dropdown by language for multilingual site?
I am working on a multilingual site that has about 60+ pages per language. When an admin user wants to add a page to the navigation menu its becoming quite the task because literally every single link (from all languages) is listed in Main Menu. Its even more confusing because the site has some cases where French and German are in the menu twice because the site has Canada-French and France-French as a language.

Is there any way to manage the navigation menu better? Like if I select German for the language could the menu dropdown automatically filter itself to just show the German nav items? Right now we have a list of about 300+ items in the dropdown :(

# Answer
> 1 votes
This seems to be the issue page for this problem: https://www.drupal.org/node/1242288. There are patches but as Jose Reyero points out, it would be only a partial solution.

There is a https://www.drupal.org/project/content\_menu which enables you to first deal with the menu and then with the content instead of vice versa. Haven't tried but seems nice. This combined with Fixed language menus (provided by Menu Translation at admin/structure/menu/manage/menu-mymenu/edit, Multilingual options - Translation mode) could clean up the menu interface nicely.

Personally, I usually just don't bother dealing with the Parent item, I just head to the menu interface after creating a node, and drag my item, which will be at the bottom, to its place.

# Answer
> 0 votes
You should use Entity translation which has a submodule called Entity Translation Menu to achieve the desired menu. On the menu itself you need to select:

"Translate and Localize. Menu items with language will allow translations. Menu items without language will be localised."

Instead of having different links for different languages you can then create a menu link in one language and translate it into another language.

# Answer
> -1 votes
Enable the Multilingual Select module. The very same thing had happened to me years ago.

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


# Question
Title: drush Invalid argument supplied for foreach() backend.inc:709
I have aegir setup, I'm trying to cache clear on all the sites in remote platform machine but failed with below error.

```
drush @sites cc all
You are about to execute 'cc all' non-interactively (--yes forced) on all of the following targets:
Continue?  (y/n): y
Invalid argument supplied for foreach() backend.inc:709
```

Would be great if some one had any idea to overcome.

# Answer
> 3 votes
The cause of above error is that @sites is returning no sites.

Try `drush sa @sites` too, and see what it says.

Note, however, that @sites refers to all of the sites in a multisite install; it does not refer to all of the sites in your aliases.drushrc.php. If you rename your aliases file to foo.aliases.drushrc.php, then @foo will reference all of the aliases in that file.

Else check this as well: https://www.drupal.org/node/1031170

Reference:
https://www.drupal.org/node/161698

---
Tags: drush, multi-sites, aegir
---


# Question
Title: How to create a email notification to subscribers and the author who posted a comment programmatically in drupal 7?
I want that if a user subscribe to a comments & post that has been posted by an author, so how i can send mail notification to both the author and the subscriber at the same time. I want that author should get a notification that he has some comment on his post. and the subscriber that author has posted some status or post.

```
    <?php
/*
 * Implement hook_menu()
 */

function comment_notification_menu(){
  $items=array();
        $items['admin/customize'] = array(
          'title' => 'Send Comment notifications',
        'discription' => 'Admin will send notification to user about updates',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('comment_notification_form'),
        'access arguments' => array('access adminstration page'),
        'access callback' => TRUE,
          );

  return $items;
}

/**
 * Form Structure
 */

function comment_notification_form($form, &$form_state){
  $form=array();
  $form['send_mail_from']=array(
    '#title' => 'Send Mail From',
    '#discription' => 'To whom you want to send form',
    '#row' => 5,
    '#columns' => 10,
    '#type' => 'textfield',
    //'#required' => TRUE,
    '#default_value' => variable_get('send_mail_from'),
    );
//here the admin can wite subject for the mail.
  $form['mail_subject']=array(
      '#title' => 'Subject',
      '#discription' => 'the purpous of this mail',
      '#type' => 'textfield',
      '#size' =>149,
      '#maxlenght' =>200,
      '#required'=>TRUE,
      '#default_value' => variable_get('mail_subject'),
    );
  $form['mail_body']=array(
      '#title' => 'Body',
      '#discription'=>'the body of your mail.',
      '#type' => 'textarea',
      '#row' => 20,
      '#columns' => 50,
      '#required' => TRUE,
      '#default_value' => variable_get('mail_body'),
    );
   $form['mail_bcc']=array(
      '#title' => 'BCC this mail to all',
      '#type' => 'checkbox',

    );

   $form['help'] = array(
        '#theme' => 'token_tree',
        '#token_types' => array('node') ,
     );

  return system_settings_form($form);
}

/**
 * Implement hook_comment_insert().
 */

/*
 *Implement token_replace(). , variable_get()
 */

function comment_notification_comment_insert($comment){

if ($comment->field_comment_notification['und'][0]['value'] == '1') {
      global $user;
      if ($user->uid == 1){

        $user_mail = $user->mail;//user has login
        //dsm($email);
  }
  else{

       $user_mail = $comment->mail;//uesr has not login
  }

      $to = $user_mail;
       // $to = 'm.nikhilanant@gmail.com';
      $message = token_replace(variable_get('mail_body')); // Body of your email here.

$subject = token_replace(variable_get('mail_subject')); // subject of e-mail
$body = token_replace(variable_get('mail_body')); //it might be any variable from the form eg. $form_state['values']['your_field']

//params is the array passed to hook_mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
    );
      $message = drupal_mail('comment_notification', 'loaded',
        $to,language_default(),
        $params,$to, TRUE);
    }

}

function comment_notification_mail($key, &$message, $params) {
/*dsm($key);
dsm($message);
dsm($params);
*/
  switch($key) {

    case 'loaded':
      $message['subject'] = token_replace(variable_get('mail_subject'));
      $message['body'][] = token_replace(variable_get('mail_body'));
      break;

  }
}

```

# Answer
I do not see a way to allow users to subscribe to comment notification, is that your issue?

In case it is you might have to do something like Create a menu item as 'Subscribe to comments' check this link to ajaxify for menu item. On page callback of your custom menu subscribe the current user(`global $user)` to the comments, to hold the data you can simply use a custom table let's name as `mymoudle_comment_subscription` with columns as `record_id|uid|comments_on_type|flag` update this table in the subscription menu callback,

Rest is what you have covered in your code, i.e. implement hook\_comment\_update to notify on existing comment update, hook\_comment\_delete notify user on comment delete, hook\_comment\_insert notify user on new comment is added. In your hook Implementation query your custom table '`mymoudle_comment_subscription`' fetch all uids get user mail by uids or in case you do not allow user to change emails you can store email directly in your custom table and use drupal\_mail as your code shows to mail all users.
> 0 votes

---
Tags: 7
---


title: Theming stuff in Drupal 8?

text:
# Question
Title: Theming stuff in Drupal 8?
How do you theme stuff in Drupal 8? In 7, for example, if you had some data items you could call item\_list, via the theme function, pass in a render array and get your markup back.

This is a great resource for those interested: Render API, but no examples that I can see.

How do I do this in Drupal 8? For example, how do I theme an image? Sure, I can probably construct my render array, but does it then have to go off to a twig template or something. Are there any examples yet?

Thanks.

# Answer
It seems to be similar to D7. Just use a render array:

```
$list = array('apples', 'peaches', 'pears');
$render_array = array(
  '#theme' => 'item_list',
  '#items' => $list,
  '#title' => t('Argument Information'),
);
return $render_array;

```

I searched *'#theme'* in *core\modules* to find examples. Not sure if this is the 'correct' way though?
> 8 votes

---
Tags: 8
---


# Question
Title: A Drupalogical question about Slider captions
Take a Slider module, no matter which one of them. If a Caption is based on a Body field, and There are **many** images and only **one** body field, How would you make different captions per every image?...

Thanks,

# Answer
> 1 votes
You would use the file entity module to allow you to add fields to files, then when uploading an image you can add data to whatever extra file entity fields you have added.

Then you can use that data in your views (most slideshow modules use views I would say).

# Answer
> 2 votes
Using the Media module, you can add fields to images, such as description or caption. https://drupal.org/project/media

Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.

---
Tags: views, javascript
---


# Question
Title: How to alter drupal views filter by start date query
I need to display only future events with start and end date greater than or equal to today's date. I am using drupal with oracle. When i am trying in views UI, its giving me an SQL error.

# Answer
> 1 votes
Try this module Views between dates filter I suppose this may help you

---
Tags: views
---


title: Drush: Make site alias read only

text:
# Question
Title: Drush: Make site alias read only
I like having site alias defined for easy Drupal management for backing up, syncing dev site with live etc.

But I am afraid of having great loses if I mistyped the drush command having order of site aliases interchanged.

```
drush sql-sync @dev @live

```

Instead of:

```
drush sql-sync @live @dev

```

Other possibilities include:

```
drush rsync @dev @live

```

Is there any option that I can set while defining site aliases that make a site ready only in drush commands? I tried to find one, including drush source code, but didn't succeed.

Of course, outside of drush I can create separate user account that only have ready only access to the site. Also extra database user with no `CREATE`/`UPDATE` permissions.

# Answer
Should be able to do it with `drush_hook_COMMAND_validate()`.

Example: https://github.com/Lullabot/drupal-boilerplate/blob/master/drush/commands/policy.drush.inc
> 1 votes

---
Tags: drush
---


# Question
Title: Changing color of form html with Javascript
I have some custom HTML and CSS added to a form module I've created. It looks fine; the css is styling it correctly with a drupal\_add\_css() stylesheet. But I also want to add some Javascript using drupal\_add\_js() so that when a user is on the first page of the form it changes the text color in the HTML I set up. But I can't get it to work!

Here's the Javascript in step-one.js:

```
document.getElementById("step-one").style.color = "#769EDD";

```

Here's the code it will be changing:

```
    $form['progress bar'] = array(
        '#title' => t('Module Tool'),
        '#prefix' => '<div class="progress-bar" id="progress-bar">
<span id="step-one">Experience Level</span> <span id="arrow1"> > </span>
<span id="step-two">Primary Role</span> <span id="arrow2"> > </span>
<span id="step-three">Topics of Interest</span> <span id="arrow3"> > </span>
<span id="recommendations">Recommendations</span></div>',
    );

```

And I'm trying to add the javascript call ABOVE the previous code, right after I do the drupal\_add\_css() call (which works). Note that this is all within my module\_form() function. Here's the relevant code:

```
function modulename_form($form, &$form_state) {
      drupal_add_css(drupal_get_path('module', 'modulename') .'/modulename.css');
      drupal_add_js(drupal_get_path('module', 'modulename') .'/step-one.js');
      // more code around building the form itself...until eventually
      I get to my $form['progress bar'] = array( // see code above.

```

Any ideas why this might not be working?

# Answer
You can try like this (thats's step-one.js file):

```
(function ($) {
  Drupal.behaviors.yourModule = {
    attach: function (context, settings) {
      $('#step-one').css('color', '#769edd');
    }
  };
})(jQuery);

```
> 1 votes

---
Tags: forms, javascript, theming
---


title: Single view on multiple pages

text:
# Question
Title: Single view on multiple pages
1) I created a content type **Portfolio-Item**. In this type a text field **Project-Url** was defined.

2) I created a **view** containing a gallery using jQFX module displaying content of **Portofolio-Item** elements which where published.

I wan't to add this **view** to different pages containing different projects portfolios.

a) *Is it possible to add a "**filter criteria**" or "**contextual filter**" that would compere the **Project-Url** field with page URL and filter available **Portfolio-Item**'s to display only proper one's.* ?

b) Is there any easy way to achieve this?

c) Can **contextual filter**'s be used with **regular expressions**?

# Answer
Install the sandbox project Views arguments in filters (download it via Git)

With this module you can move a contextual filter down into the normal filters so that everything that you can do with normal filters can then be applied to the contextual filter.

> **How to use this module**
>
> To make use of this module, configure your view as usual, but use the following steps when adding arguments.
>
> * Use the argument "Global: Null" to denote the input arguments your view will make use of. This argument not alter your query in any way, but you can still use validators and actions if no argument is
> present as usual. And title, breadcrumbs, et cetera. Sweet.
> * Add a filter, and instead of adding a filter value manually, you enter %1, %2, et cetera to filter on the first or second input
> argument. That's it!
> 0 votes

# Answer
I would recommend you to use a Viewfield or the EVA Module. With both of them you can attach a view to an entity and add arguments. I personally prefer EVA to do stuff like this. Very handy and allows you to use the same in different contexts without exposing it to the site admin directly.
> 1 votes

---
Tags: entities, views
---


# Question
Title: drush sql-dump with --gzip from remote to local machine
I can use drush sql-dump to get the production db from my remote server and save it to my local machine no problem using:

> drush @site-live sql-dump \> /home/backups/my\_db\_backup.sql

but i want to enable the --gzip option to make the process faster which i've tried with

> drush @site-live sql-dump --gzip \> /home/backups/my\_db\_backup.sql.gz

but i get this error from archive manager in Ubuntu:

> gzip: /home/backups/my\_db\_backup.sql.gz: not in gzip format

For starters...can i actually use --gzip with sql-dump?

UPDATE: the problem appears to be that "stdin: is not a tty" is being appended to the first line of the file whether it is a plain .sql or a .sql.gz file

# Answer
> 0 votes
OK i managed to solve this, the first thread in this question made me check my centos server to see if the mesg y was still in any of the bashrc files and i found the culprit in /etc/bashrc on my centos box. I was logging in from a terminal to whm from Ubuntu (whether Ubuntu made a difference i'm unsure).

# Answer
> 0 votes
Here are few checks you should do:

* make sure that your gzip program is in your $PATH (just check if you've `gzip` command),
* disable any drush verbose messages to avoid printing any extra lines from terminal which could break the compression,
* temporary use `-vd` to check how the command look like (`Executing` or `Backend invoke`) and make sure you've `--gzip` in your argument list, if it's not - you're getting the plain version of it for some reason (so you can redirect to `.sql` file instead)

If your `--gzip` is not invoked, even you're specifying one and `gzip` is configured correctly, then it's probably a drush bug. I think this could depend on PHP version which you're using as I've the same problem with PHP 5.5.

# Answer
> 0 votes
From a quick search this seems to be a ubuntu(debian?)-specific issue, as it doesn't by default open a tty for a remote ssh session (your command worked fine for me on CentOS). Try adding `--tty` as an ssh option to your drush command.

Maybe of use: https://www.drupal.org/node/1783330

---
Tags: drush
---


# Question
Title: How can I redirect users after they cancel their accounts?
Is there a way redirect users after they cancel their accounts? I've configured my site to allow users to cancel their accounts without e-mail confirmation, but I want to be able to redirect them to a "goodbye" page to reassure them that their account was in fact cancelled.

In `user_cancel()`, though, account cancellation is performed with the Batch API. I tried adding a `drupal_goto()` after the call to `batch_set($batch)`, but this forces the goto and the batch processing is not performed.

How can I redirect non-admin users after they cancel their accounts?

# Answer
There are two fine ways to do it :

1. With Rules : If you have installed it already then you must use this. Select the event "After a user account has been deleted". Check the conditions you want and add action "Page Redirect".
2. With Hook : Write a hook\_user\_delete and add drupal\_goto in your condition.
> 1 votes

# Answer
You mention batch and the profile/cancel form.

Taking a look at the Batch API docs, we see that when called via form, FAPI will handle the redirect. Leading to the conclusion that you could add a submission handler with `hook_form_FORM_ID_alter` for the cancellation form and set `$form_state['redirect']`.

This would probably be advantageous over `hook_user_delete` &| `drupal_goto`, as higher weighted modules may get ignored. You could use rules but unless you're already using it elsewhere that's a bit overkill.
> 0 votes

# Answer
If I am not wrong user\_cancel\_confirm\_form\_submit() tries redirecting user to profile page after account cancelation which might end up throwing page not found. Looks like $form\_state\['redirect'\] needs to be overridden in custom submit handler.
> 0 votes

---
Tags: redirection
---


title: Huge variations on page load times

text:
# Question
Title: Huge variations on page load times
I've build a website using Drupal 7 (7.34 now) and used quite a lot of modules (CiviCrm, Views, Panels, Webform, etc). I recently put this site live at my hosting provider and now I'm experiencing huge variations in page load times (Time to first byte).

When I enable caching for anonymous users, the page load times are pretty stable (200ms). But when I turn of caching the load times are varying from 1.5 sec to 30 seconds. These huge variations seems to come in periods over time,with a couple of minutes interval.

I've already tried several things to find the problem:

* My first suspicion was the performance of my hosting provider, but I'm pretty sure this is not the problem. I've created a PHP benchmark script and executed this while the responses for my website were slow. But the benchmark did still return the same results.
* I've used the Profiling module to see if I could find a bottle neck, but it looks like all things are taking more time and not only 1 part.
* I've used the Devel module to check the SQL queries, but there wasn't any taking a longer time then normal, when I experienced the slow response.
* I've disabled the Update manager, as this could stall page loads, but without success.
* I've checked for not properly (un)installed modules, but they are all OK.

It is also not related to any specific page, but all page requests are slowed down when it happens. I never saw any (PHP )error and finally the page will always load properly, but only with a huge delay.

When the slow down period occures, it looks like there is something holding up every page request. Maybe some locks on something??

As the site also has to perform for users logged in, caching for anonymous users is not a good solution. Of course there are several other caching solutions possible for logged in users, but I want to solve the cause of this problem. And not using work-arounds....

Can anyone advise me or has suggestions to find and solve this problem?

Thanx!

# Answer
Seems to be too broad to answer, few pointers that may help you.

Root Cause of problem might be at

1. Custom module level which can be drill down with profiling tools as devel profiling which you have already used, another tool can be XHPROF.
2. Ensure all your custom queries are optmised.
3. Uninstall all modules which you are not using.
4. Try to have a comparison of site performance on your local and server, your server might not be allocating required resources.

As per my experience when you have long list of modules installed it causes performance issue especially panels, to overcome you can use caching provided by views module and for panels check if this module does the trick for you.

Having said that Authenticated User Page Caching mdoule will be worth looking at.

Views and panels provide caching
> 1 votes

---
Tags: caching, performance
---


# Question
Title: View showing Teasers - getting path for full content in teaser template
I have created a simple view to list teasers of a particular content type.

I'm then using a simple view template, modified to suit the layout needed. In the content type set-up there is not an option to display the path/URL to the full content. I can set the image if output to link to the original content, but I can't seem to find an option to just get the URL for the full content so I can link the whole teaser block to the full article.

Any clues? Know this should be easy - but can't seem to find it.

# Answer
Normally, you can access nid with `$row->nid` in your template.

From that, you can easily build the link to your node content with `node/ . $row->nid` path.
> 2 votes

---
Tags: views, uri
---


# Question
Title: How to show language specific search result in Solr search
We have configured solr search in one of our site.The site is multilingual and having 5 languages content in it.

The problem we are facing is, when user language is selected as french and any searches are performed then the search result is not showing french content at top.

We want the users current language content to be populated at top. Any module or solr settings which we missed.

# Answer
> 0 votes
I haven't done this in a while but this should help Apache Solr Multilingual

> The goal of this project is to cleanly extend Apache Solr Search Integration to provide:
>
> * better support for non-English languages
> * support for multilingual search cross-language information retrieval (CLIR)
> * an easy-to-use administration interface
>
> Apache Solr Multilingual does not replace Apache Solr Search Integration but is based on it.

# Answer
> 0 votes
use entity translation ...Regarding Entity Translation introductions:

* Enable language fallback
* Display shared labels
* Select which entities can be translated: Node;Commerce product
* Details for Commerce product: Selected Author's language and no checkboxes at all

Languages selection/detection (admin/config/regional/language/configure):

* Selected/added all necessary languages, still leaving English as default, manually added en prefix for English default, to make clear separation, as I am using prefix for language separation
* User interface text language detection: URL; Default
* Content language detection: Interface (moved to top manually); URL; Default

Commerce product type settings (admin/commerce/products/types/product/edit):

* Enabled via Entity Translation

admin/commerce/products/types/product/fields
* Replaced regular Drupal Title field with Title module, and in this field settings checked, that this is the only field in Product type I'm going to allow translation.

Product display node content type settings from admin/structure/types/manage/{your-display-type}
* Published options \> Multilingual support - selected: Enabled, with translation (NOT Enabled, with field translation, as I'm going to use i18n for language and node separation).
* My title field in this display node, which is overridden by Title module is left for field translation, as these are per field settings, not per content type.
* There are no any other fields let for entity translation in product display node, even product reference field (used with inline entity form).

Basically that's all. Taxonomy term translation is handled by i18n modules and Taxonomy vocabulary has Translate... (NOT Localize...) settings - different name for each language tied into translation sets.

---
Tags: search
---


title: How do I output XML schema?

text:
# Question
Title: How do I output XML schema?
I have set the REST server with the Services module.

Also I've installed the Services Views module, created a new view that outputs the desired fields into XML.

That's working fine.

How can I add XML schema to that output, so the XML will look like:

```
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
.....

```

# Answer
> 0 votes
You'll need to hook into the rest server module's formatters. This is untested but I think it'll work:

```
function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['xml']['formatter class'] = 'MyServicesXMLFormatter';
}

...

class MyServicesXMLFormatter extends ServicesXMLFormatter {

  public function render($data) {
    // This is the default code from ServicesXMLFormatter::render(),
    // manipulate this to add your schema and return the saved doc as normal
    $doc = new DOMDocument('1.0', 'utf-8');
    $root = $doc->createElement('result');
    $doc->appendChild($root);
    $this->xml_recursive($doc, $root, $data);
    return $doc->saveXML();
  }

}

```

# Answer
> 0 votes
Besides retrieving content as XML, do you need any other functionality provided by the Services module? If not, it might be overkill.

One simple alternative might be to write a module that implements hook\_menu() to define a menu item for a wildcard path such as node/%/xml, which then, in its page callback, outputs the XML in your specified format.

```
    <?php

function mymodule_menu() {
  $items['node/%nid/xml'] = array(
    'page callback' => 'mymodule_xml_view',
    'page arguments' => array(1),
  );
  return $items;
}

function mymodule_xml_view($nid) {
  drupal_set_header('Content-Type: text/xml');

  echo '<?xml version="1.0" encoding="UTF-8"?>';
  echo '<ngd:mediafile ...>';
  echo '<nid>' . $nid . '</nid>';
  // ...
  echo '</ngd:mediafile>';

  drupal_exit();
}

```

Then, after enabling the new module, you can retrieve XML content by simply fetching, for example, URL http://example.com/node/42/xml .

---
Tags: views, services
---


# Question
Title: How can I replace a node reference field with a node edit form?
I have two content types - parent and child. There is a one to many relationship (many children to one parent). I am migrating this content, and the current situation is that that node reference field is on the child, pointing to the parent. However, I may be able to change this to have a node reference field on the parent set to an unlimited number of items (though its probably better if I keep the existing "schema" to avoid problems after migration).

I would like to create a node edit form for the parent. In this node edit form, I want to have the child node edit form embedded on the same page, either as a replacement for the node reference field, or as a view displaying node edit forms of existing children of parent. I will create an interface that displays the child node edit form(s) when the user clicks on an accordion-like button at the top of the form, and beneath the form, a "Add another", which creates a new child node add form.

My first thoughts are to over-ride the template of the node reference field to embed the node edit form in the theme. However, this method seems to have potential side effects that have to be dealt with, as the current "schema" is the child nodes pointing to the parent nodes, which I prefer to keep.

My ideal solution is to use panels, but after playing with panels and doing some googling, I haven't found a solution that is specific to my needs.

How do I embed the form (either an existing node edit form or a node add form with a node reference field pre-populated) using panels? Is that even possible? If not, what is the best way to accomplish this?

# Answer
You can achieve this by Installing Entity Reference and Inline Entity Form
> 6 votes

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


# Question
Title: How to reset my password if I forgot it?
I forgot the admin user pass for my site. Then I followed the process to recover my password. I get an email with a link (available for 24hs) which allows me to login in my site. I go to 'user/1/edit' to create a new password, but the old one is a REQUIRED field. This is wrong, I forgot my password, then I can't fill this field.

Am I missing something here??

# Answer
While you can change admin password either by drush or by running mysql query if you have access to database if you do not have direct access to your mysql server, install devel and wrap the mysql query with drupal query wrapper functions and run it at /devel/php page.

You may want to consider having nocurrent\_password module which removes the current password field and you can directly update your passwords, NOTE: this behaviour will be same for other users as well.
> 2 votes

# Answer
If you can see user/1/edit then you must be logged in, right? Log out and use the link in the email and it will ask you to reset your password. Then there should only be two fields in a non-logged in page for you to fill in.
> 0 votes

---
Tags: users
---


title: Add # in menu items

text:
# Question
Title: Add # in menu items
I want to add menu items like 'projects#recent' and 'projects#featured' where both links redirects to same page but different sections. how can I do this ?

# Answer
> 1 votes
You need to follow these steps.

> 1. Decide a target location on the page.
> 2. Assign an ID to the HTML element occupying that location. That element could be a h (header) tag, a paragraph etc.. This is the exact code I use to assign an ID to the bottom of this post: `<p id="postbottom">You’ve reached the bottom> of the post</p>` You can add an id attribute to any element -`<div>,
>  <span>, <p>, <a> , <img>` etc.
> 3. If you don’t have an element there (i.e. you are jumping into a middle of a long paragraph), just create one -enclosed a word with a … tag and add in the id.

Resource

After that you can go to the menu link and add the name of the page and the name of your id. In this case your ids are going to be recent and featured.

---
Tags: 7, routes
---


# Question
Title: Shipping line items not displaying with [commerce-order:line-items]
I have Commerce and Shipping and Flat Rate installed and working correctly. Shipping is added to an Order and charged to the customer.

But when I go to display the shipping line items, e.g. in a order receipt email, they are missing.

My Rule uses this:

```
Order Details:
[commerce-order:commerce_line_items]

Total Price: [commerce-order:commerce_order_total]

```

This correctly displays each product line item, and the order total, including shipping line items, but does not display the shipping line items.

I read about a filter in the View at `admin/structure/views/view/commerce_line_item_table/edit/default` and I see that it is set to only display product line items. But I don't want to mess with that View unless I know what I am doing.

Can I Add a new View display? If so, which kind (Data export?) How to call that display in my Rule?

Thank you.

# Answer
> 1 votes
If you enable the Token module (maybe you already have?), you are given a new view mode on all fieldable entity types called *Tokens*. You need to enable this in the *Custom display settings* fieldset on the *Manage display* page for order types (found under **Administration \> Store \> Configuration \> Order settings**). Once you've done this, you'll be able to choose any eligible View you want for rendering the line item field's tokens, so if you add another display to the default View and remove that line item type filter, you can use that just for rendering the token.

You can read more w/ screenshots here: https://www.drupal.org/node/1299662

---
Tags: views, tokens, commerce
---


# Question
Title: Replacing initial view of a panel with a content view
I have a Panel that is supposed to show initially a **Taxonomy view** and a set of filters for a **Content view**. If the user hits any of these filters, my taxonomy view fades out and shows my content view.

Is it there any easy way of doing this, without having to create a personalized template file with some *javascript* under the hood?

# Answer
I Finally ended up showing both views, and having them hidden depending on the status of the exposed filters via Jquery.
> 0 votes

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


# Question
Title: Including Google Maps in my custom module
So, to set the stage, I'm working on a small database project that will handle a company's order handling. So far, I have a fully working client part where users can get a full list of all the clients and can edit/delete/add clients at will.

The next think that I'm trying to implement, is that each client will also have it's own details page, where more details of the client will be displayed. It should display all the data in the database regarding the specific client, but it should also incorporate a Google Map based on the client's address.

I've looked around and found a dozen of Google Maps modules, but they only seem to work with article types that have fields that contain an address.

My current line of thinking was just to render the detail page with a render array after getting all the client's info from my database.

1) Is this the correct way of doing it? If not, how should I approach this?

2) If yes, how can I then implement a google map?

EDIT:

The thing is, I'm not exactly working with a content type at the moment. I'm using hook\_menu for all my pages, and an example callback function for displaying a full list of all the clients is

```
function expoline_clients_overview() {
    // Table settings.
  $attributes['datatable_options'] = array(
    'bFilter'   => TRUE,
    'bInfo'     => TRUE,
  );
  // Define table columns
  $header = array(
    array(
      'data' => t('Column 1'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => FALSE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
    array(
      'data' => t('Column 2'),
      'datatable_options' => array(
        'bSortable' => TRUE,
        'bSearchable' => TRUE,
      ),
    ),
  );

  /*
   * Fetch all clients from the database and insert them into the array of rows
   * that will be rendered in the table
  */
  $query = db_query("SELECT * FROM {expoline_clients}");
  foreach ($query as $currentclient) {
    unset($client);
    $client[] = $currentclient->name;
    $client[] = $currentclient->street;
    $client[] = $currentclient->street_number;
    $client[] = $currentclient->postal_code;
    $client[] = $currentclient->city;
    $client[] = '<a href="clients/' . $currentclient->cid . '/edit"><button type="button">Edit</button></a>';
    $client[] = '<a href="clients/' . $currentclient->cid . '/delete"><button type="button">Delete</button></a>';
    $clients[] = $client;
  }
  $rows = $clients;

  // Render the Datatable
  $variables = array(
    'attributes' => $attributes,
    'header' => $header,
    'rows' => $rows,
  );
  $output = theme('datatable', $variables);

  return $output . '<a href="clients/add"><button type="button">' . t('Klant toevoegen') . '</button></a>';
}

```

Thanks a bunch!

# Answer
> 1 votes
I didn't dig into the exact methods you are using, but if all you want to do is embed a very simple map graphic you could use something like this:

```
if (isset($currentclient->street_number) && isset($currentclient->street)) {
      $address_var = $currentclient->street_number . " " . $currentclient->street;
      if (isset($currentclient->city)) $address_var .= "+".$currentclient->city;
      if (isset($currentclient->state)) $address_var .= "+".$currentclient->state;
      if (isset($currentclient->postal_code)) $address_var .= "+".$currentclient->postal_code;
      $address_var = str_replace(' ', '+', $address_var);
      $output = "<a href='https://maps.google.com?daddr=".$address_var."'><img style='float: right; ' src='https://maps.googleapis.com/maps/api/staticmap?center=".$address_var."&zoom=15&size=300x150
&markers=color:blue%7Clabel:*%7C".$address_var."' /></a>";
    }

```

Or, I suppose a render array would simply change the `$output=` line above to be something like this:

```
$output =  array(
    'map' => array(
      '#type' => 'markup',
      '#markup' => '<a href="https://maps.google.com?daddr='.$address_var.'"><img  src="https://maps.googleapis.com/maps/api/staticmap?center='.$address_var.'&zoom=15&size=300x150
    &markers=color:blue%7Clabel:*%7C'.$address_var.'" /></a>',
    ),
);

```

# Answer
> 0 votes
OK, My suggestion is you can create a Full HTML text in your content type and get your client's address (postcode or address). Then render values form DB with url from google to generate an embed map iframe, then assign the iframe's mark up to your FULL HTML text field. Please refer to Google Developer API to find out how to generate embed map. You can use hook\_node\_presave or hook\_form\_alter to do this. It's seem your thinking is in right direction.

---
Tags: 7, google-maps
---


# Question
Title: Understand message before updating a module
If I go to admin/reports/updates I see modules that need to be updates.

I just need to know what is the difference between the message "Recommended version:..." and the other message with red background. I mean what are the risk of not updating them?

# Answer
The message on red background are critical or security fixes means the module is insecure or has known vulnerabilities. It's important to you to update flagged (red highlighted) modules as soon possible so you can prevents hacks.

A recommended module means your modules are many version(s) behind the current release, the module is known to be secure, and simply not up to date with features the current module offers.
> 1 votes

---
Tags: updating
---


# Question
Title: Showing two colorbox windows side by side...or within one main frame?
I have a site that I've created for some fellow musicians to learn new songs. Generally we have a link to a Youtube video of a song then a link that opens up the tab (chords, lyrics, etc) for the song. Right now I have links that open those things up individually in colorboxes. Works fine.

What I'd like to do is have one colorbox, or frame, or iframe, etc -- that opens up and in the left side I have the Youtube video and on the right side the tab colorbox ... so as I listen to the song I can scroll down at the same time and look at the tab. Here is a link to the site: http://practice.3cnorth.com/?q=all-songs

Thanks for any ideas.

ER

# Answer
One simple approach would be to just create a content type that includes both items. For instance, "songs". Then, you could:

1. Embed each youtube video within their corresponding tabs node.
2. Then, you could use a module such as Display Suite to display one next to each other (E.g. video on the left column and tabs on the right column).
3. After this, if you want the tabs to be "scrollable", just set a fixed height in CSS and a "scrolled" overflow. E.g.

```
.views-field-body pre {
    height: 300px;
    overflow-y: scroll;
}

```

That should do the trick, the colorbox will open one node, instead of 2 as currently.
> 0 votes

---
Tags: javascript
---


# Question
Title: Backup and Migrate module - no option to back up files?
In Drupal's Backup and Migrate module (/admin/config/system/backup\_migrate), the only option for "Backup from" is "Default Database". In tutorials, that drop-down seemingly should also have "Public Files Directory".

I'm a new Drupal user - is there something simple I'm missing here?

# Answer
> 1 votes
There was a module which did this earlier, Backup Migrate Files, but it got obsolete and the code is not merged with Backup Migrate module, and is available with version 7.x-3.0 Make sure you use the latest version of the module.

---
Tags: backups
---