title: Block does not show up in block list

text:
# Question
Title: Block does not show up in block list
recentpost.file

```
name = recentpost
description = A list of node with thumbnail
package = Liu's custom
core = 7.x
version = 1.0
files[] = recentpost.module

```

recentpost.module

```
/**
 * @file
 * Add thumbnail to each node
 */

function recentpost_block_info(){
  $blocks['recentpost'] = array(
    'info' => t('Recentpost'),
    'status' => true,
    'weight' => 0,
  );
  return $blocks;
}

function recentpost_block_view($delta = '') {
  $block = array();
  $block['subject'] = t('Node with thumbnail');
  $block['content'] = 'ssssssssssssssss';
  return $block;
}

```

I've created a sample module from scratch and can activate it in `admin->module`, but when I go to `structure->block`, the block I've just created doesn't show in the list no matter how many times I've cleared the cache both from drupal and the IE. Can anyone help me sort it out.

# Answer
> 2 votes
**Always set region** (Until bug is fixed)

I believe this may be a bug in the code, it seems that is Status/region are toggled it causes problems, to guarantee that it shows for now make sure you set region

```
    function recentpost_block_info(){
      $blocks['recentpost'] = array(
        'info' => t('Recentpost'),
        'region' => BLOCK_REGION_NONE,
        'status' => true,
        'weight' => 0,
      );
      return $blocks;
    }

```

The bug seems to be in the function "`_block_rehash()`" where it checks for `empty($block['status'])`

# Answer
> 1 votes
Try this in your database: DELETE FROM block WHERE module="modulename";

This will delete the rows in your database related to your block.

# Answer
> 0 votes
Your implementation of `hook_block_view` is incorrect.

You're declaring your *recentpost* block correctly in `hook_block_info`, but you're not telling `hook_block_view` which block to manipulate.

Try the following:

```
function recentpost_block_view($delta=''){
  $block = array();

  switch ($delta) {
    case 'recentpost':
      $block['subject'] = t('Node with thumbnail');
      $block['content'] = 'ssssssssssssssss';
    break;
  }

  return $block;
}

```

`hook_block_info`

`hook_block_view`

**EDIT**

I'm also assuming that the first part is from your `.info` file, and that the snippet above isn't taken in whole from your `.module` file.

# Answer
> 0 votes
I had the same problem caused by the delta. Example:

```
function approval_block_info() {
  $blocks['unpublished_nodes'] = array(

```

As you can see, my delta was unpublished\_nodes. That was the problem! Block was not displayed. When I change this to my\_unpublished\_nodes, everything worked just fine.

Solution: Carefully choose your block names!

# Answer
> 0 votes
I had the same issue. I am guessing it's a drupal issue, more exactly a caching issue. This happened on a fresh installed drupal installation. Here is my hook\_block\_info():

```
/**
 * Implements hook_block_info().
 */

function essential_block_info() {
    $blocks = array();
    $blocks['cursul_zilei'] = array(
        'info' => t('Cursul zilei block'),
    );
    $blocks['imaginea_zilei'] = array(
        'info' => t('Imaginea zilei block'),
    );
    $blocks['animatie_interesanta'] = array(
        'info' => t('Animatie interesanta block'),
    );
    $blocks['news_feed'] = array(
        'info' => t('News feed block'),
    );
    return $blocks;
}

```

For some reason my blocks weren't appearing in the list so drupal rule no.1 popped in my head: "If something is wrong clear the cache". Did that but the issue didn't resolve, therefore I cleared the cache manually from the db and it worked.

Just empty all the tables that start with 'cache' in your db and you'll be fine.

---
Tags: blocks
---


# Question
Title: Repository-based site deployment -- what to do about sites/default/files?
I'm trying to get more rigorous about my process for deploying Drupal sites across development and production servers. In particular, I'm experimenting with pulling the site from my SVN repository into a directory on the server and flipping a symlink to point the server to the updated site. This makes sense to me, but I'm not sure how to handle the sites/default/files folder -- it's not in the repository created by the development process since those files are produced by the production users, and the directories inside this folder have different permissions than the default 0755 that I'm getting from doing the export.

So, what to do here? My current guess is that sites/default/files should be physically moved out of the site directory and then symlinked back in, but wanted to check with others with more experience in this. A related question is whether there are other files or directories in a Drupal installation that would need to have their permissions updated after an svn-based installation like this. sites/default/settings.php comes to mind, for instance. Anyway, is there any advice out there? Thanks!

# Answer
> 2 votes
Ahh the age old question of how to properly deploy Drupal from dev-\>test-\>live. If you search around you will find many opinions and answers. There is no one answer and no singular method. The symlink solution is good one and is safe and simple. Another solution would be to use SVN to sync directly back to the same site/directory(s). You could mark certain files so that they are not pushed. If a mistake is made, you just revert. One other file I can think of that you may not want to overwrite is `.htaccess`. Other than that, `settings.php` and your files directory are about all that would need to be excluded.

---
Tags: 7, deployment
---


# Question
Title: Why am I getting call to undefined function after splitting module functions to two files?
Now my module has two main files:

* menu\_perm.module
* menu\_perm.admin.inc

I added second file to .info:

> files\[\] = menu\_perm.admin.inc

I cleared the cache.

In my test class (PHPUnit) file I am bootrapping Drupal by:

```
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

and I call form submit function manually inside test function, ends with below error:

> Call to undefined function menu\_perm\_user\_form\_submit()

Function is in menu\_perm.admin.inc.

Before this everything was ok.

What am I doing wrong here?

# Answer
> 3 votes
`files[]` only works for class/interface autoloading, it won't include arbitrary PHP files. The docs say

> Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file

You can get around it by adding a line like this to the top of your .module file:

```
require_once DRUPAL_ROOT . '/sites/all/modules/my_module/my_module.admin.inc';

```

# Answer
> -1 votes
Use module\_load\_include inside your test function, e.g.
module\_load\_include('inc', 'my\_module', 'my\_module.admin');

---
Tags: 7, testing
---


# Question
Title: Trying to integrate Rate-Widget (Rate-Module) into Status-Block (Statuses/Facebook Style Status)
With Drupal 7, I am trying to combine the Rate-module and the statuses-module (formerly Facebook Style Status), for my voting widget to show up in status boxes.

At https://drupal.org/node/811742 it explains to implement the hook hook\_facebook\_status\_render\_components.

```
<?php
/**
 * Implementation of hook_facebook_status_render_components().
 */
function MYMODULE_facebook_status_render_components($status) {
  //Only show on individual status pages.
  if (arg(0) == 'statuses' && is_numeric(arg(1))) {
    //Here, the theme function MYMODULE_voting_widget is assumed to take a "type" and "id" parameter, but it may vary.
    return array(
      'MYMODULE' => array(
        'value' => theme('MYMODULE_voting_widget', 'facebook_status', $status->sid),
      ),
    );
  }
}
?>

```

The README from the rate-module however describes to use the following code:

```
<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
  print rate_embed($node, 'NAME');
}
?>

```

So I used this latter code and implemented the hook in the rate-module:

```
<?php
function rate_facebook_status_render_components($status) {
  //Only show on individual status pages.
  if (arg(0) == 'statuses' && is_numeric(arg(1)) && ($node = node_load(arg(1))) ) {
    //Here, the theme function MYMODULE_voting_widget is assumed to take a "type" and "id" parameter, but it may vary.
    print rate_embed($node, 'ratingwidget');
  }
}
?>

```

I deactivated the module and re-activated it, but nothing shows up. What did I do wrong? Do I need to include any files from the Statuses-module in my rate.info-file, in order to implement hooks from one module in the other? Did I do something totally wrong and just don't understand the concepts?

Thanks very much in advance.

# Answer
A couple problems here.

I assume you are using Drupal 7, and therefor this module: https://drupal.org/project/statuses

Which is the successor of facebook\_status module for D6.

Your hook is for the D6 module, and does nothing for the D7 module.

I couldn't find the replacement hook in the new D7 version: http://drupalcode.org/project/statuses.git/blob/bc7e520:/api.php

The other problem, is that 'statuses' are their own 'entity' - for lack of a better word. They are not actually even 'entities' in the Drupal terminology. Just some entries in it's own DB table.

The reason this is a problem, is your code is looking to load a node from path when on a path like (/statuses/5), but a 'status' is not a node.

As far as a solution, you'll have to decide a new road to go down, but at least this helps you understand the situation.
> 1 votes

---
Tags: rating
---


title: Dynamic hook menu to redirect user

text:
# Question
Title: Dynamic hook menu to redirect user
I'm trying to essentially create an alias to an entity edit form, but really all I need to do is redirect, but get a `Page Not Found error`.

```
function kidb_profile_menu() {

    $items['profile/%uid/edit'] = array(
        'page callback' => 'kidb_profile_redirect_user',
        'page arguments' => array(1),
        'access callback' => array('edit own main_profile profile'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function kidb_profile_redirect_user($uid) {
    drupal_goto('profile-main_profile/'.$uid.'/edit');
}

```

# Answer
Since you are using the *%uid* wildcard in the menu definition, your `kidb_profile_redirect_user()` is not getting a user ID, but what `uid_load()` would be returning. That function is not defined from any module and that is the reason why you get the "page not found" error.

The list of wildcards defined from Drupal 6 is reported in Wildcard usage and core's wildcards. A description of what auto-loader wildcards are is given in `hook_menu()`:

> ## Wildcards in Paths
>
> ### Simple Wildcards
>
> Wildcards within paths also work with integer substitution. For example, your module could register path 'my-module/%/edit':
>
> ```
>   $items['my-module/%/edit'] = array(
>     'page callback' => 'mymodule_abc_edit',
>     'page arguments' => array(1),
>   );
>
> ```
>
> When path 'my-module/foo/edit' is requested, integer 1 will be replaced with 'foo' and passed to the callback function. Note that wildcards may not be used as the first component.
>
> ### Auto-Loader Wildcards
>
> Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named `mymodule_abc_load()`. When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments (see "load arguments" in the return value section below). For example, your module could register path 'my-module/%mymodule\_abc/edit':
>
> ```
>   $items['my-module/%mymodule_abc/edit'] = array(
>     'page callback' => 'mymodule_abc_edit',
>     'page arguments' => array(1),
>   );
>
> ```
>
> When path 'my-module/123/edit' is requested, your load function `mymodule_abc_load()` will be invoked with the argument '123', and should load and return an "abc" object with internal id 123:
>
> ```
>   function mymodule_abc_load($abc_id) {
>     return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
>   }
>
> ```

You probably meant to use *%user*, which would return to your page callback the object returned from `user_load()`. Using that wildcard avoids you check in your code that the user ID is valid (e.g. there is a user account with that ID), but also means that you should change your code to match the following.

```
function kidb_profile_redirect_user($account) {
  drupal_goto('profile-main_profile/' . $account->uid . '/edit');
}

```
> 3 votes

# Answer
When defining your menu path like you did `'profile/%uid/edit'`, you are using `Auto-Loader Wildcards` which basically under the hood calls `uid_load` function.

You should use simple wildcard in your path definition:

```
$items['profile/%/edit'] = array(

```
> 2 votes

---
Tags: routes, redirection
---


# Question
Title: Why does Panels output <section> for some panes and <div> for others?
I'm just wondering what causes Panels Pages (or cTools pages? Never figured out which is which) to output some panel panes in a `<section>` html tag wrapper, and output the other panel panes in a `<div>` html tag wrapper?

I would prefer it if they were one or the other, but not both. So I wanted to understand and find out the reason so I could potentially make it consistent.

**Theme I use:** AdaptiveTheme (Custom Sub-theme with minimal configurations and changes)

**Panels "Variant" Layout:** AT One Column (Responsive single column panel layout, AdaptiveTheme core)

# Answer
> 2 votes
To the best of my knowledge, Panels contains no instances of `<section>`. This comes entirely from your theme.

Specifically, I believe it's from `at_core/templates/panels-pane.tpl.php` which contains the following:

```
 * Adaptivetheme variables:
 * - $is_mobile: Bool, requires the Browscap module to return TRUE for mobile
 *   devices. Use to test for a mobile context.
 * - $tag: top level wrapper element, section or div.

```

followed by

```
 <<?php print $tag . $attributes . $id; ?>>

```

The relevant logic appears to be

```
/**
 * Preprocess variables for panels_pane.tpl.php
 */
function adaptivetheme_preprocess_panels_pane(&$vars) {
  // Top level wrapper
  $vars['tag'] = $vars['title'] ? 'section' : 'div';

```

---
Tags: 7, panels, chaos-tool-suite, theming
---


title: Modules/Methods for Faster Data Entry

text:
# Question
Title: Modules/Methods for Faster Data Entry
I have an unlimited-cardinality text field on a node that users need to enter 50-100 values on. Right now, the user has to type in one value, click "add another item", and then click inside the text field to start the process again.

Is there a module or a way to enable them to simply hit "Enter" after entering the first item, that will automatically open the next text entry area and move the cursor inside it?

# Answer
This particular solution was a custom form, where I had fine control over the CSS classes applied to the different elements, but it might also work for node-edit et al.

You would use hook\_form\_alter() to target whichever form you want. Then, you would add a custom CSS class and an '#attached' property to that form element, containing a 'js' element which would point to a custom javascript file within your module. The code in this file would watch elements of that CSS class for when a user hit 'tab', and then automatically click the 'Add More' button for you. JS added below for reference:

```
(function ($) {
  Drupal.behaviors.formAutoTab = {
    attach: function (context, settings) {
      $('.othercustomclass').focus();
      $('.customclass').keydown(function (event) {
        if (event.keyCode == '9') {
          $('input[type=submit][id^=addbuttonidgoeshere]').mousedown();
          event.preventDefault();
        }
      });
    }
  }

})(jQuery);

```

The trick is .othercustomclass which you will need to refocus on the new element after it's added. I think core Drupal does apply some sort of 'ajax-processed' class or something else to the fields added by the 'Add More' button, which you might be able to use as the jquery selector.
> 0 votes

# Answer
There probably isn't such a module already, but you could add this functionality yourself with a small javascript snippet.

The easiest way to do this is to download and enable JS Injector and then click \[+ Add\] for a new injection rule.

Name it whatever you'd like, paste in the code below, and make sure to limit the scope to:

```
node/add/*
node/edit/*

```

Custom javascript that handles this behavior:

```
(function ($) {
  Drupal.behaviors.multiTextEnter = {
    attach: function (context, settings) {
      // Begin attach method

      // Only run in document context
      if (context !== document) {
        return;
      }

      // Look for multiple field container
      var $multiTable = $('.field-multiple-table');
      var $nodeForm = $('.node-form');

      if ($multiTable.length) {

        // Listen for ajaxComplete
        $nodeForm.ajaxComplete(function(e, xhr, settings) {
          $nodeForm.find('.field-multiple-table .form-text:visible:last').focus();
        });

        $nodeForm.delegate('.field-multiple-table .form-text', 'keydown', function(e) {
          // if enter key is pressed
          if (e.which == 13) {
            // trigger "Add another item"
            $('.field-add-more-submit').trigger('mousedown');
            // prevent default form submit when enter is pressed
            e.preventDefault();
          }
        });
      }
      // End attach method
    }
  };
})(jQuery);

```
> 0 votes

---
Tags: javascript, entities
---


# Question
Title: Body content appears to anonymous viewer but not to site admin
In Drupal 7, on my front page, when logged in as admin, the node's content is not rendered.

However, when I log out, I can see content

This only occurs on one content type (called Front Page). No other content type mimics this behavior.

We're using Responsive Premium as our base theme, of which it is based on omega.

Is there a permission that I have forgotten about?

# Answer
Check the field permissions in your content type. If you added custom permissions to a field and did not grant admin role access, the node will not be displayed.

By "admin" do you mean uid1 superuser or user in a role named "admin"
> 0 votes

---
Tags: 7
---


# Question
Title: How to display the input box next to the label in a form?
My objective is to improve the look and feel of a form developed in Drupal 7.

By default, I have (as an example):

* Name (label)
* BLANK INPUT box (below the label)

How to display the **label** and **input box** as inline ?

# Answer
> 0 votes
you can do this with css float

A more difficult ways that render the items via php preprocessing before css adjusts the layout) would be to create a php template file and use theme functions for the form in your theme

Here is tutorial that uses both methods http://www.jaypan.com/tutorial/themeing-drupal-7-forms-including-css-and-js

also, it depends on what kind of form you are theming. Here is another example for webforms https://drupal.org/node/1157306

---
Tags: forms
---


title: Autocomplete on "Unlimited" text field?

text:
# Question
Title: Autocomplete on "Unlimited" text field?
I'm adding Drupal's built in Autocomplete functionality using hook\_form\_alter to set the #autocomplete\_path like so:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  ...
  $form['field_company']['und'][0]['value']['#autocomplete_path'] = 'autocomplete/company';
  ...
}

```

This works perfectly for a text field where the number of values is 1, but doesn't work when the number of values is unlimited. I'm assuming this has something to do with the field be added via Javascript. Is there another hook I can tap in to in order to add the #autocomplete\_path?

EDIT : Drupal 6.

# Answer
> 4 votes
You have to iterate your field's delta ; here, you only affect `$form['field_company']['und']__[0]__, not $form['field_company']['und']__[n]__`

Stay in your `hook_form_alter` but iterate it each time your `$form` is rebuild :

```
    foreach($form['field_company']['und'] as $delta => $field) {
        if(is_array($field) && is_numeric($delta)) {
            $form['field_company']['und'][$delta]['value']['#autocomplete_path'] = 'autocomplete/company';
        }
    }

```

# Answer
> 1 votes
When altering a field with cardinality, I like to use #process. Basically you are defining a function that will get called everytime the field is processed on the form including when added via javascript.

In your case, the code might look like this:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  ...
  $form['field_company'][$form['field_company']['#language']]['#process'][] = 'field_company_process';
  ...
}

function field_company_process($element, &$form_state, $complete_form) {
  $element[$element['#max_delta']]['value']['#autocomplete_path'] = 'autocomplete/company';
  return $element;
}

```

---
Tags: 6, entities, ajax
---


# Question
Title: Why is hook_menu_local_tasks_alter called twice?
For some reason, Drupal is calling `hook_menu_local_tasks_alter` twice. This results in either a) doubled tabs or b) really annoying code trying to determine if my custom tabs have already been added.

Can someone help me figure out what's going on here? Why would it be called twice? I'm using PathAuto, is this maybe a redirect issue?

# Answer
OK, so I solved my problem but not my question. For the time being I think this is the best solution, so I'll post it here for others. Please correct me if I'm wrong because I'm not a Drupal guru or anything.

Still don't know why `hook_menu_local_tasks_alter` is being called twice -- I swear I remember reading it was a two-step process; first for tabs, then for actions, but I don't remember.

Anyway, my solution is pretty simple. It appears that if I change the `data` array in `hook_menu_local_tasks_alter` and include my own key `mymodule_processed` as `TRUE`, it successfully sees that on the second time around and ignores the additional tabs.

Edit, For C&P junkies:

```
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {
$map = $router_item['map']; //Map corresponds to the router
if (count($map) >= 2) { //Node views have 2 parameters: [0]=>node,[1]=>node object
    if ($map[0] == 'node') {
        if ( //Ensure we haven't already added the tabs & we have an object of correct type
            !empty($map[1]) &&
            is_object($map[1]) &&
            $map[1]->type == 'post' &&
            !empty($data['mymodule_processed']) && !$data['mymodule_processed']
        ) {
            $data['mymodule_processed'] = TRUE;
            //Add your tabs here

```
> 0 votes

# Answer
If you are familiar with the command line, you can use the following command to return file names and line numbers where this hook is being called.

For example, change directories into your /sites/all/modules directory or other module directory and run,

(assuming your are using mac or linux)

```
$grep "menu_local_tasks" * -rn

```

or as Clive has it below.

```
$grep "drupal_alter(\'menu_local_tasks\'" * -rn

```

\*Note, the backslashes escape the single quotes.

Jason.
> 0 votes

# Answer
I thought I might suggest a way that I have dealt with this in the past:

```
function mymodule_menu_local_tasks_alter(&$data, $router_item, $root_path) {

    // Declare job assignment link path
    $new_tab_path = 'tab-path';

    // Check to see if the the anticipated key for the new tab has already been created. If not, add the tab. If so, skip the tab addition
    if (!isset($data['tabs'][1]['output'][4])) {
        $data['tabs'][1]['output'][] = array(
            '#theme' => 'menu_local_task',
            '#link' => array(
                'title' => t('New Tab'),
                'href' => $new_tab_path,
                'localized_options' => array(
                    'attributes' => array(
                        'title' => t('New Tab'),
                    ),
                ),
            ),
        );
      }
    }

```

It basically just tests to see whether or not the index that the new tab will take, in this case key number 4, is set or not.

I'm not too familiar with Drupal yet and I don't know that this is the best way, but it seemed to work to solve the problem of the duplication of tabs.
> 0 votes

---
Tags: routes, hooks
---


# Question
Title: array value within Rule's PHP action always gives 0 instead of related uid
I want to fetch the latest Ubercart order's associated uid and if it is NOT the same as the newest user's ID then my Rule should validate and send an email to a selected address.

In the Rule I created, I've written the following PHP action in order to first check what $uids\[0\] is giving me. When this works as require, I'll put the same code as a PHP condition, replacing the watchdogs with return FALSE & TRUE.

The problem I'm facing is that $uids\[0\] always gives 0 instead of the last order's user ID.

```
$query = db_query("SELECT uid, created FROM {uc_orders} order by created desc");
$uids = array();
while ($records = db_fetch_array($query)) {
    $uids[] = $records['uid'];
}
$latestaccountuid = $account->uid;
$latestorderuid = $uids[0];

$message = "Latest account id:".$latestaccountuid." .Latest order uid:".$latestorderuid;

if ($latestaccountuid == $latestorderuid) {
watchdog('FALSE', $message);
//return FALSE;
}
else {
watchdog('TRUE', $message);
//return TRUE;
}

```

# Answer
I think the problem is with your `$account` variable. I don't see where it's instanciated in your code. It's probably related to the current logged in user, so you've to find a way to access this information from Rules. Try to use `dsm($account);` if you're using the devel module and check if the variable is empty.
> 0 votes

# Answer
$account is the account of the logged in user. when you are testing it, are there any orders assigned to the account you are logged in with?

I the Rules UI:

> $account User logged in user

also

> dsm() is legacy function. It's a call to dpm() as it is, so you should use dpm()
> 0 votes

---
Tags: rules, ubercart
---


title: Event related to node - how to display?

text:
# Question
Title: Event related to node - how to display?
Thinking how to achieve what I need, looking into possibilities. I have a content type that is used for all kind of locals: restaurants, clubs and so on. Now, what I want is to have a list of nearest 3 events that will take place in that specific place.

So far I was thinking about creating new type of nodes for events. Let's say: Event content. Seems logical, right? Now, using Entity Reference I should be able somehow to add relation between an event and club (not sure about this one yet). Next step would be displaying this added event on the node of that club. How could I achieve that? Creating a View and putting it into the node display somehow? Block?

Really could use some ideas for that.

# Answer
> 0 votes
You should create a view and add relationship using node reference(entity reference) and after adding relationship you should add fields corresponding to node for which relationship has been added.
Check the link on how to add relationship in views

---
Tags: views, nodes, entities
---


# Question
Title: mymodule.install file not creating the table in drupal 7
I have a very simple table in my .install file and for some reason is not creating the table. What can it be? something i have to add in the .info file? please help.

Its a drupal 7.

this is what i have in my my\_module.install file.

```
function my_module_schema() {
  $schema['my_module_config'] = array(
    'description' => 'Configuration settings for the my_module web service.',
    'fields' => array(
      'name' => array(
        'description' => 'Name ',
        'type' => 'varchar',
        'length' => 50,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
  );

  return $schema;
}

```

# Answer
> 1 votes
1. you should uninstall the module
2. write the hook\_schema function
3. enable the module.

You should also specify the primary key in the hook\_schema

```
 'primary key' => array('field_name'),

```

You can check the drupal link for the hook\_schema

# Answer
> 0 votes
You should install the schema by invoking the **hook\_install** in the **.install** file as follows

```
function modulename_install() {
  drupal_install_schema('my_module_config');
}

```

---
Tags: database
---


# Question
Title: How to get map widget for location selection with Location / GMap
I have GMap and Location modules set up and working. I have a working API key. The node with the location field can store long/lat or address data which I am using to populate a view. All of this works. The only problem I am facing is that I want the node creation form to use the GMap widget, so that users can click the map to populate the location field. I cannot, for the life of me, figure out how to enable this feature. I've checked everywhere that I can think of- any help is appreciated.

# Answer
Have you checked out the Geolocation Field Module? It works with the Google Maps Api v3 and does exactly what you are trying to do. You add the map as a field/widget within your content-type. The Field stores lat/lon values.
> 2 votes

# Answer
For the benefit of others who stumble on this question in future - If you are using a Drupal 7 site, then you can use Location and Gmap modules for this.

To allow picking of coordinates from a map you would have to edit the location module settings at `admin/config/content/location` and CHECK the option for using a google map as shown below
> 2 votes

# Answer
If you creating a service with maps and GeoTagFields, that you want to develop and improve in future - you should to install Drupal 7.

1. Sooner or later you have to go to D7 - Do it right now!
2. There a lot of new location modules for d7 which is unique and haven't versions for d6.
3. In August we expect в8 core and programmers instead of improving d6 versions of modules, will write new for d8.
> 0 votes

---
Tags: 6, location, google-maps
---


# Question
Title: Showing Error while insertion of data in database, Drupal 7
I am new to drupal, and i am trying to insert data in database from form using Database API. But its showing an error. That error is given below:

```
PDOException: SQLSTATE[HY000]: General error: 1364 Field 'x1' doesn't have a default value: INSERT INTO {members} (first_name, last_name, email, username, password, country) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => Ravneet [:db_insert_placeholder_1] => Singh [:db_insert_placeholder_2] => rvtsingh@gmail.com [:db_insert_placeholder_3] => rvtsingh [:db_insert_placeholder_4] => 123456 [:db_insert_placeholder_5] => India ) in form_test_form_submit() (line 63 of C:\wamp\www\Biding\sites\all\modules\own\form_test\form_test.module).

```

The code I used in module file to create code and insert in database is :

```
<?php
function form_test_menu() {
  $items['formtest'] = array(
    'title' => 'Sign up',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function form_test_form($form, &$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['email'] = array(
    '#title' => t('Email'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['username'] = array(
    '#title' => t('Username'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['password'] = array(
    '#title' => t('Password'),
    '#type' => 'password',
    '#required' => TRUE,
  );
  $form['country'] = array(
    '#title' => t('Country'),
    '#type' => 'select',
    '#options' => array('India' => 'India', 'Pakistan' => 'Pakistan', 'USA' => 'USA', 'UK' => 'UK', 'China' => 'China'),
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

function form_test_form_submit($form, $form_submit) {

  global $user;
    $user = db_insert('members')
    ->fields(array(
        'first_name' => $form_submit['values']['firstname'],
        'last_name' => $form_submit['values']['lastname'],
        'email' => $form_submit['values']['email'],
        'username' => $form_submit['values']['username'],
        'password' => $form_submit['values']['password'],
        'country' => $form_submit['values']['country'],
    ))
    ->execute();

    drupal_set_message("You have registered successfully.");

}

```

Please help me to resolve this error. Thanks in advance.

# Answer
> 0 votes
Looks like the issue is related to your mysql table `member` structure. The member table field `x1` doesn't have a default value that means you need to serve a value on every insert, you can solve this in three ways,

1. Pass the value in the field array Ex: `'x1' => "<value here>",`
2. Add a default value / NULL (based on your requirement) through altering your table

> (ALTER TABLE `member` CHANGE `x1` `x1` NOT NULL DEFAULT '') OR (ALTER TABLE `member` CHANGE `x1` `x1` NULL)

3.Check your table mode, if the table mode is STRICT change it to `SET GLOBAL sql_mode='';` REFERENCE : SQL Mode

---
Tags: 7, forms
---


title: Sticky header block module?

text:
# Question
Title: Sticky header block module?
I am searching for a way to make a block behave as a drupal-highlighted area, similar to the header here. In other words, stick to the header and move along as the user roles down.

I was wondering if there is either a module that can do that, to sort of wrap the block's content or a custom workaround in my module.

I know that there exist some themes which can do that, but I would like to implement a theme-free solution.

Thanks!

# Answer
> 7 votes
This is just a CSS thing! ~~There a tutorial here on how to achieve it,~~ but you're pretty much just looking at some CSS like the following.

*Edit:* The tutorial has now gone, but the CSS contained is very similar to that shown below, and a quick search in your favourite search engine will return similar results.

```
#BLOCKID {
    position: fixed;
    top: 0;
    left: 0;
    height: 160px;
}

```

Just apply the CSS to your chosen block and you're off.

# Answer
> 2 votes
Try this: https://drupal.org/project/floating\_block. It works fine and it's easy to use.

> The Floating block module allows you to keep html blocks, selected using jquery selectors in a fixed position on the page as you scroll. It works in a similar way the table header fixer in Drupal Core. This means that when the user scrolls their browser selected parts of the page can stay in the users view.

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


# Question
Title: Custom commerce payment methods based on item
In my Drupal commerce website, I have 2 payment methods, Payment Method #1, Payment Method #2

This is working just fine but the thing is I need to make it custom for a specific product type, for example if I'm selling Asus products, I want to get 40% pay with Payment Method #1 and the rest via Payment Method #2.

I'm not a module developer so I thought I can make it happen with some customization and/or rules.

I'd like to know if it's possible without module development,what's the best approach and how to do it properly.

thanks in advance.

# Answer
> 1 votes
An administrator can add two payment transactions to an order using different payment methods from the admin \> order \> payment area.

However an end-user normally selects a single payment method from the radio button form during checkout.

To support multiple payment methods you may need to send the customer through the payment step of the checkout twice, each time with a different amount and a different payment method selected.

Payment method selection is controlled by Rules logic and can be configured there. The order status controls whether it can be sent through checkout again so may need to be set to the relevant checkout status. The order amount to be paid may need to be set in custom code during the payment step process.

---
Tags: 7, commerce
---


# Question
Title: How do I completely uninstall a custom entity implemented by my module?
I need to write an uninstall use-case for my custom entity. I just want to know what operations I should take care of, in order to completely uninstall my entity/module and all attached fields (including custom fields created by Field API).

Should I use `hook_uninstall` and how should I implement this hook?

# Answer
> 2 votes
The tables declared by the hook\_schema() will be automatically remove when you uninstall your module.

If you need to remove other tables or variables use the hook\_uninstall()

# Answer
> 0 votes
I think the use of function field\_attach\_delete\_bundle would be a better approache here.

---
Tags: 7, entities, installation
---


# Question
Title: How to stop the book module defaulting to IE7 standards mode?
I currently have a problem whereby when visiting a page created with the book module it forces IE into IE7 standards document mode.

I am running Drupal 7 with the Omega 3 base theme. I have disabled the RDF module and added:

```
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

```

Which forces all other areas of the site to render correctly, just not in the book module pages.

Has anyone else come across this problem?

# Answer
> 0 votes
I suspect you may have visited the book page in IE, and selected compatibility mode once, and it is now being remembered. Another possibility is that you have an internet zone rule (probably an intranet rule) that is forcing compatibility mode on. Your IT department may be forcing this via a policy, too.

I have had some problems with just using the meta in the header of a page, and have been using this:

```
/**
 * Implements hook_html_head_alter().
 */
function MYTHEME_head_alter(&$head_elements) {
  // disable IE compatability mode
  // see http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx

  $head_elements['x_ua_compatible'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'X-UA-Compatible',
      'content' => 'IE=Edge,chrome=1',
    ),
  );

  $head_elements['x_ua_compatible']['#attached']['drupal_add_http_header'][] =
    array('X-UA-Compatible', $head_elements['x_ua_compatible']['#attributes']['content']);
}

```

This adds the meta, so you can see it when you do a view source, and it also adds a proper HTTP header to disable it.

Just note that if this is being enforced via policy or IE settings, you may not be able to override it.

# Answer
> 0 votes
I finally figured out that because I have access to the server the site runs on I could add the custom header X-UA-Compatible - IE=edge. This has solved the issue server side. I haven't found a solution if you don't have access to the server.

---
Tags: nodes
---


title: Parse managed file

text:
# Question
Title: Parse managed file
I am very new to Drupal 7 module development and I have been working to develop a module where it parses a file after the user uploads it. I am using hook\_forms, but for some reason I can't get a submit handler to be called after I click upload, or attach a submit handler.

```
$form['r_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('R file'),
    '#upload_validators' => array('file_validate_extensions' => array('xlsx')),
    '#upload_location' => 'public://babies',
    '#default_value' => variable_get('r_file'),
    '#description' => t('For all the babies in the world'),
    '#progress_message' => t('Uploading file...'),
    '#progress_indicator' => 'bar',
    '#required' => TRUE,
);

```

Where can I attach a handler so that when the user clicks upload/remove, I can conduct some post processing?

What I meant is according to this section, https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#managed\_file it says "The form's validate and submit handlers receive a file object ID in $form\_state\['values'\] that represents the ID of the new file in the {file\_managed} table."

Then it goes on describing what should go inside the submit handler. My question is, how should the submit handler look like?

Hope that clarifies the question.

# Answer
Seems to me that you are looking for this hook\_file\_insert (https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_file\_insert/7) It is being called once managed file is inserted to database which is exactly what it occurs when you hit the upload button of file upload widget.
> 0 votes

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


title: How to Ajaxify a Drupal 7 Views block

text:
# Question
Title: How to Ajaxify a Drupal 7 Views block
I have a custom content type, with an associated block, which all displays correctly. The block is initially hidden, upon clicking a button the block is moved into view, and the user is able to scroll horizontally through each content item.

Each content item contains an image, so I am interested in preventing them from being loaded initially, and only when the button is clicked (in order to reduce initial loading time).

I don't suppose there is a Drupal way of doing this? The only way I can think of is making direct calls to the database, which I don't want to do for obvious reasons.

I noticed a "Use Ajax" option in the Views interface, however I wouldn't have thought this would work with my custom jQuery code?

# Answer
You might try the Lazy Image Loader. I'm not sure if it will work for your case, but it's worth a shot. You can also implement the lazy behavior yourself. Use javascript to test the "complete" property of each image, and change the src attribute on any image that currently hidden from view. When it becomes visible, swap in the original src. I've seen good results with this script: http://www.appelsiini.net/projects/lazyload.
> 1 votes

# Answer
You can also use Ajax Blocks module which permits to load some blocks by additional AJAX request after loading the whole cached page when the page is viewed by anonymous user.

This module works well when you want to ajaxify some Drupal blocks.
> 0 votes

---
Tags: views, blocks, ajax
---


title: Programmatically assign user role

text:
# Question
Title: Programmatically assign user role
I have multiple roles on my website, and I want to assign a certain role to some users when they register to my site.

How can I assign a specific role to new users programmatically when they submit their registration forms?
I have tried modules like logintoboggan, autoassignrole, but they provide a default user role on registration, when I want to assign role to specific users, not to all users signing up on my site.

# Answer
> 10 votes
While you may not consider this to be "programmatic," you can use the Rules module to do this.

Install the module and create a new rule on the event "After saving a new user account." For the action, you will want to set the user role to ABC (where ABC are the role(s) you want to assign).

You can limit the role to specific users by adding conditions. For example, you can use the "Data comparison" condition to only apply the rule if the user has chosen a specific value on the registration form (detailed example: limit the rule to only those users who select "female" as their gender on registration).

You will have to create a rule for each condition/role combination you wish to award. However, Rules is a widely used module and can be exported manually or with the Features module, giving you a lot of flexibility.

# Answer
> 14 votes
We also solved this task with the user\_multiple\_role\_edit() function. In our usecase we didn't react on the register-form but on a special menu-callback to create users on the fly.

First: Create a user

```
$user = new stdClass();
$user->name = $name;
$user->status = 1;
user_save($user);

```

Second: Assign the user to the role

```
$role = user_role_load_by_name("my custom role");
user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);

```

# Answer
> 5 votes
This will make the default roles 4,5 and 6:

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id){
    $form['account']['roles']['#default_value'][] = '4';
    $form['account']['roles']['#default_value'][] = '5';
    $form['account']['roles']['#default_value'][] = '6';
}

```

# Answer
> 2 votes
In my case there were only four profile2 profiles, but if the person was having a certain value in their registration form, I had to add them to a new role. Here is what I did:

```
<?php
function MYMODULE_user_insert(&$edit, $account, $category){
  if (array_key_exists('profile_club', $account)) {
    $is_uni = FALSE;
    if ($account->profile_club['field_uni_club']['und'][0]['value'] == 1 ) {
      $is_uni = TRUE;
    }
    if ($is_uni) {
      $uid = $account->uid;
      $role_name = 'uni_club';
      if ($role = user_role_load_by_name($role_name)) {
        user_multiple_role_edit(array($uid), 'add_role', $role->rid);
      }
    }
  }
}
?>

```

---
Tags: 7, users
---


title: After upgrade admin menu not coming

text:
# Question
Title: After upgrade admin menu not coming
After upgrading from Drupal 6 to Drupal 7 successfully, the admin menu links are disappeared.

I have carefully followed the steps to upgrade it successfully. But after upgrade, I changed the administration theme to Seven and everything was working but the administration menu. What could be the problem?

Update: Management Menu snapshot

I tried to see if the problem is with Menu, so I installed Admin menu but after that admin menu appearing. Only problem is with Drupal7 default toolbar. What am I missing?

# Answer
Can't tell you why, but can tell you how I fixed it last time when it happened to me:

1. Disable Admin Menu
2. Uninstall it if possible
3. Delete it's files and directory
4. Download and unpack fresh copy
5. Clear all caches (Drupal and browser)
6. Enable Admin menu

Worked for me, when menu disappeared during 6.x -\> 6.x upgrade, when everything else failed to bring it back.

If the problem is only with core toolbar module, and not Admin Menu module, you have 2 options, really:

1. Try steps above, just for Toolbar. You can download core archive and then just extract toolbar's directory. Admin menu and toolbar are build in similar fashion, and purging all module's data is a pretty solid method anyway, so it still can work.
2. Give up on toolbar, and use 3rd party module instead.
> 1 votes

---
Tags: 7, upgrading
---


# Question
Title: Custom reference field settings in different content types
I have a **field** called booked user and two types of **content types**, event-type-A and event-type-B.

I am referring to the same field from both content types. However, along the process I figured out that I want to have multiple values for this field in event type-A and single value for event-type-B. Initially both had multiple values.

Whenever I change the field settings in one content type, it also changes in the other.

How can I overcome this? Considering that I have content created in type-B and I can not really add a new field to replace that one, cause I will lose all the previous field content for that user.

# Answer
The solution a colleague proposed is to add the following code in the hook\_form\_alter():

```
$language = $form['field_user']['#language'];
$form['field_user'][$language]['#multiple'] = 0;

```

If you want to be a bit more aggressive on data consistency you can also hook into the form validator and check that the correct number of values is inserted.
> 1 votes

---
Tags: entities, nodes
---


# Question
Title: How to create a tabbed view in a panel without a menu entry?
**What is my goal?**

I'd like to create a view for my users' profile page, similar to the 'Questions' block one finds on the user pages on this website. Instead of the user's questions, I'd like to display the articles he/she created. The users should be able to reorder/filter the articles in the view by clicking on *"filter links"/tabs* similar to the ones I marked in the underneath picture.

I don't know the exact term for this, but I suppose one calls this a *tabbed view*.

**What is my problem?**

I can't find any suitable solutions for this functionality on the internet, but I've read a lot of similar requests. The main problem is that the view doesn't have its own page. That means: it should just be part of the user profile page, which has been overridden with "user\_view" (see: How to create a profile page?) into a panels page. (This is exactly why the tabs in @Jhilke Dai's solution don't show up.)

It's also important that the path still contains the user's ID when one clicks on the tabs, because - of course - the *Articles* view needs this information, namely via the *Contextual filter: (author) User uid* \> *Provide default value: User ID from URL*.

**What did I try so far?**

I've already created a view called *Articles* that displays all the articles that were added by the user. As any view would, it's displayed perfectly in the panel on my user profile pages. My next step was to add the tabs to the view. I followed @Jhilke Dai's answer to the letter, but as I mentioned before, the tabs don't show up when I don't give the Master display a normal menu entry (that's not what I want).

# Answer
> 3 votes
Take a look at the QuickTabs module. You create a tabbed block via QuickTabs, with each tab itself being an already defined block, page, view, etc. Then you add the QT block to pages the same as any other. You will probably need to create your own style for the tabs (it does come with a handful of predefined styles) to achieve exactly what you want.

# Answer
> 4 votes
You don't need 3 views, just create one view with 3 pages Votes, Activity and Newest. define your fields and filters. In **Page Settings -\> *Menu Option***, Use the **Menu tab**.

**Edit:** Exmaple

If **Page Path** for main view is ***mylist***

* Add Pages in View with Paths *mylist/votes*, *mylist/activity*, *mylist/newest* for all the 3 pages respectively
* Select **Menu Tab** and Provide the Menu for Votes, Activity and Newest respectively

---

Above was the previous reply, here is answer with some graphics.

For the demo of your use case:

* I created a taxonomy vocabulary called **DSE** with 3 terms ***Vote***, ***Activity*** and ***Newest***
* I created a new content type called **Drupal Stack Exchange**, with ***Title***, ***Questions*** and ***Tags*** field, where ***Tags*** field is *Term Reference* to **DSE**

In Views, I created a Master Display with Just Title field for demonstration, and I gave the Page path as ***questions*** like in this picture

For the Menu for Master display I selected ***Normal menu entry*** and selected **Main Menu** as its menu type:

Then I added the new Page for Activity, and in Path I gave ***questions/activity***

In Menu for Activity, I selected **Menu Tab** and gave a title called **Activity**

In Filter for Activity I selected **DSE Tag** and chosed it to be one of ***Activity Tag*** like in the picture below. (**Note**: While adding filter select only this display)

I repeated the same process for Votes and Newest, as you can see Path settings for Newest is also the Menu Tab like:

Save the view and you'll see the New Menu called ***Questions*** in **Main Menu**, and clicking the Menu will give you 3 tabbed menu inside like:

**Note**: To make tabbed menu it is required the path to be on the same Path like in above case *`questions/vote`* for Vote tab, *`questions/activity`* for Activity tab.

Finally the Sneak peak of the View page

---
Tags: 7, views, panels, routes
---


# Question
Title: Changing the Open Atrium 2 login hyperlink
How do I change the open atrium 2 login hyperlink for anonymous users so that they can register instead of being directed to the user login page?

# Answer
Try this:

* Goto admin/config/people/accounts
* Select **Registration and cancellation**
* Under **Who can register accounts?**, chose **Visitors** instead of **Administrators only**

Then users can create an account from the user/login page.
> 1 votes

---
Tags: distributions
---


# Question
Title: Views Criteria Filter - Changes Affect Master Display
I have a problem with the module `Views` with the `FILTER CRITERIA`, When I clone a block inside my view and change the `FILTER CRITERIA` the change also occurs on the `Master Display` is it a normal behavior ?

Thanks !

# Answer
> 3 votes
Yes, that's the default behaviour. But you can change it easily.

When you're editing the filters in your cloned display, look to the top of the dialog. You'll see a select list like this:

That select list determines whether the changes you're about to make are applied to the whole view, or just the display you're working on. If you choose "This xxx" (where xxx could be any number of things like page, etc), the changes you save will not apply to the other displays.

---
Tags: views
---


# Question
Title: PDO datetime exception when saving a Computed Field (but no datetime in my query)
This one has me stumped. I get the following error when trying to create/edit a node with a computed field, which is an INT:

> PDOException: SQLSTATE\[22007\]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'field\_film\_civicrm\_event\_code\_value' at row 1: INSERT INTO {field\_data\_field\_film\_civicrm\_event\_code} (entity\_type, entity\_id, revision\_id, bundle, delta, language, field\_film\_civicrm\_event\_code\_value) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 363 \[:db\_insert\_placeholder\_2\] =\> 364 \[:db\_insert\_placeholder\_3\] =\> film \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> ) in field\_sql\_storage\_field\_storage\_write() (line 451 of /data/disk/o1/static/drupal-7.23/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module).

Here is my code for the computed field:

```
list($id, $vid, ) = entity_extract_ids($entity_type, $entity);

$result = db_query("SELECT
                    ce.id AS CiviEventID
                    FROM node n
                    INNER JOIN civicrm_event ce ON n.title = ce.title COLLATE utf8_unicode_ci
                    WHERE n.nid = :nid
                    AND n.vid = :vid
                                        LIMIT 1",
                  array(':vid' => $vid, ':nid' => $id));

if ($result->fetchField() === NULL)
{
$entity_field[0]['value'] = 0;
}
else
{
/*$entity_field[0]['value'] = 0; */
$entity_field[0]['value'] = $result->fetchField();
}

```

I'm using a computed field to get a CiviCRM event code where its event name matches my node title. It previously matched the Civi event date to a node date field as well, but I removed that when troubleshooting. This worked normally two weeks ago. Since then I've applied updates to Ubuntu and PHP, and the Entity and Date modules, but haven't changed my computed field code (until troubleshooting for this post). If I hard-code the value to 0, the node saves without error.

The error shows the correct nid and vid, but also shows empty for my computed field (I'm assuming due to this datetime error). When I run the query directly against the DB I get the correct result, so my query syntax isn't broken.

I'm running this all on Linode using the BOA stack from Omega8cc. Drupal is 7.23 currently. Any advice for troubleshooting or a solution?

UPDATE: I've modified the db\_query to its simplest form ("SELECT 1 FROM NODE LIMIT 1") and the fetchField() still doesn't return a value. But if I set the value without using a query at all, it saves.

# Answer
In the end, something in the BOA or Entity update affected fetchField(). I resolved it by explicitly setting the index like so: `fetchField(0)`.

I added a comment to api.drupal.org to hopefully help the next person who has the problem.

https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/DatabaseStatementBase%3A%3AfetchField/7
> 1 votes

# Answer
it's saying that field\_film\_civicrm\_event\_code\_value expects an integer in the format datetime and there is no value: \[:db\_insert\_placeholder\_6\] =\> )

If that is not the correct format, you can change the field settings in the db, and/or make sure the field allows NULL values and the default is NULL

http://www.php.net/manual/en/class.datetime.php
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to scrape specific elements of the Drupal theme to a file?
I want to save two divs - one with the site header and the other has the main nav menu - to a PHP file that can be used in other (even non-PHP) sites to replace their header and menu using Javascript DOM insertion and CORS with a header on the saved file that allows cross-origin resource sharing.

The idea is to update the distibution code automatically on cron or on demand, when changes in the menu are made, so they will be reflected in the satellite sites.

I have been able to create a working proof-of concept using simplehtmldom on the current version of our site. However, when I tried to adapt it to the new version in dev, using a different theme as a subtheme of Adaptive Theme, then simplehtmldom cannot read the URL properly - it seems that the blocks are missing see https://drupal.org/node/2139613

The divs are not $page regions, although the header-wrapper div contains the $page\['header'\] region (and the region is invisible to simplehtmldom).

I looked at the Web Widgets module, but that is for content and views - I want to get the theme elements in the header-wrapper and the nav-wrapper, two arbitrary divs at the top of the page.

It's also frustrating that I cannot access the $page array or even the $variables in my module. I had to set the module weight to 1 to be "heavier" than the simplehtmldom module, since there are other modules that require simplehtmldom module (like devel themer) and I don't want to load its library twice. But I tried the latest simplehtmldom library separately, with the same results.

I know there are scraping tools based on node.js but I'm looking for a more lightweight solution. simplehtmldom worked, but in the new site it doesn't

# Answer
I solved the issue, and it may have been related to

```
// the zero here is necessary because simplehtmldom returns a collection
$topbar = $html->find('#header-wrapper', 0)

```

Here is my sample code - I am thinking about contributing a module for this function, with some admin settings

```
// get the header code and write it to a file
function module_name_global_header_write() {//dpm('raw_html');

    // there may be an issue if we are processing this function while viewing the same url as $sourceDomain
    // perhaps we will need to create a page or URL that is not viewed but can supply the HTML for the header
    $sourceDomain = 'http://site_name.com';
    $sourceMenuId = 'superfish-1';

    // initialize simplehtmldom objects
    $html = new simple_html_dom();
    $responsive_desktop_css = new simple_html_dom();
    $global_styles_css = new simple_html_dom();

    // load files into simplehtmldom
    $html->load_file($sourceDomain); // the generated HTML
    $global_styles_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/global.styles.css');
    $responsive_desktop_css->load_file($sourceDomain . '/sites/all/themes/adaptivetheme/site_namedaptive/css/responsive.desktop.css');

    // #header-wrapper and #nav-wrapper are the ids of the header and menu
    $topbar = $html->find('#header-wrapper', 0); // the zero here is necessary because simplehtmldom returns a collection
    $navbar = $html->find('#nav-wrapper', 0);

    // prepare Cross Origin Resource Sharing header
    $header = "<!-- This header necessary using CORS http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ -->
    <?php
    header('Access-Control-Allow-Origin: *');
    ?>";

    // some more CSS rules that are not in the css files
    $morestyles = '#google-appliance-block-form{width:100%;height:30px;text-align:right}#block-google-appliance-ga-block-search-form .container-inline div{display: inline;}.element-invisible, #block-google-appliance-ga-block-search-form label, .url-textfield{display:none!important;}#nav-wrapper ul li a, #menu-bar ul li a {padding: 5px 8px;}#nav-wrapper ul li.last, #menu-bar ul li.last {
    border-right: none;}';

    // prepare the CSS style tag; in case we do not want css, we only have to unset the $global_styles_css var
    $cssStyles = $global_styles_css ? '<style>' . $global_styles_css . $responsive_desktop_css . $morestyles . '</style>' : '';
    // replace relative image urls with absolute
    $cssStyles = str_ireplace("../",$sourceDomain . "/sites/all/themes/adaptivetheme/site_namedaptive/",$cssStyles);

    // assemble output from components
    $output = $header . $topbar . $navbar . $cssStyles;

        // create directory if not exists
        if (!file_exists('public://global_header')) {
                mkdir('public://global_header', 0777, true);
        }

    //write the file that will be fetched by the script tag embedded in the target site
    $filename = "public://global_header/raw_header.php";
    file_put_contents($filename,$output);
}

```

here is the code in the js file:

```
//cross-browser see http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){ //IE
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}
var sourceURL = 'http://site.com/';
var request = createCORSRequest("get", sourceURL + "/sites/default/files/global_header/raw_header.php");

if (request){
    request.onload = function(){
    // do stuff if request is successful; if it fails, there is no replacement of existing HTML in target site
  // look first if a container with id #header-id exists, if not use the existing #topbar container
    document.getElementById('header-id') ? document.getElementById('header-id').innerHTML = request.responseText : document.getElementById('topbar').innerHTML = request.responseText;
    // change a relative image URL into absolute
    document.getElementById('branding').getElementsByTagName('img')[0].src = sourceURL + '/sites/default/files/image.png';
    // change relative Google Appliance Search action into absolute
    document.getElementById('google-appliance-block-form').action = sourceURL + '/';
    };
    request.send();
}

```

example script tag:

```
<script src="http://site.com/sites/all/modules/custom/module_name/module_name.js"></script>

```
> 0 votes

---
Tags: blocks, routes
---


# Question
Title: What would be the best way of creating a drop down menu - selected go to page
I would like to create a drop down menu that does two things and I am still new to Drupal and i am trying to figure it out. The two functions are:

1. automatically grabs the title of the pages i am trying to list.
2. When an item is selected it will navigate to the corresponding page.

I feel like this has to be doable, but i am just not sure how i would go about it. Would anyone have any ideas on how i would go about doing something like this? any help would be much appreciated! Thanks!

# Answer
You can create a View (with the Views module) with the Format "Jump Menu"

In the fields include the title, and link it to its node in the field settings.

If that does not serve your purpose, there are several Jump Menu contributed modules http://drupalmodules.com/search/node/jump+menu
> 1 votes

---
Tags: 7, views
---


# Question
Title: Why didn't I get MySQL as possible database type to use for the site?
When I installed Drupal 7 on localhost, it didn't show MySQL as database type.

>

Why?

It also shows this error.

> Fatal error: Undefined class constant 'MYSQL\_ATTR\_USE\_BUFFERED\_QUERY' in D:\AppServ\www\drupal\includes\database\mysql\database.inc on line 46

# Answer
Appserv includes MySql, but your post shows that only SQLite is installed

Try to reinstall Appserv with MySQL

There is more discussion on this error on drupal.org

You may need to enable PDO example:

> use the phpinfo() function to know the path of php.ini: "Loaded Configuration File C:\Windows\php.ini", then modify the php.ini file to enable: "extension=php\_pdo\_mysql.dll" and it works!
> 0 votes

# Answer
You need the php's PDO and mysql extensions installed on your system in order for Drupal to use MySql data storage. One or both of them are apparently missing, and Drupal defaults to Sqlite, which is a simple database system and only needs a writable file to work. Please refer to Drupal's system requirements page for further info.
> 2 votes

---
Tags: 7, installation
---


# Question
Title: How to create a $navigation main menu with target="_blank" on specific page.tpl.php pages
I have a Drupal 7 site using the main menu for all pages. However, I've just added some unique landing pages for some advertising campaigns which all come from 'page--landing.tpl.php'

Oddly, my client wants just the 'page--landing.tpl.php' pages to have the main menu for these pages only work in such a way that the links all open in new windows (like target="\_blank").

Does anyone know how to achieve this?

In the 'page--landing.tpl.php' file, the menu is created with:

```
<div id="menu">
<?php print $navigation; ?>
</div>

```

Thanks for any and all help given.

# Answer
> 1 votes
There are many ways to do this

A quick way would be to use jQuery to rewrite the anchor tags in the menu with the target attribute

```
$( '.page--landing [menu link selector] ).attr( 'target','_blank' );

```

Using the Drupal API

```
function MODULE/THEMENAME_menu_link_alter(&$item)
{
   if (some logic that sets it only for the desired paths/context)
   {
     $item['options']['attributes']['target'] = '_blank';
   }
}

```

an example from the documentation for function hook\_menu\_link\_alter

```
function MODULE/THEMENAME_menu_link_alter(&$item)
{
  if($item['link_path']=="admin/tutorial14333")
  {
  $item['options']['attributes']['target'] = '_blank';
  }
}

```

---
Tags: routes, navigation
---


# Question
Title: How to run custom command running drush cron via sudo?
The documentation for drush cron says:

> You should set up crontab to run your cron tasks as the same user that runs the web server; for example, if you run your webserver as the user www-data:

I wrote a wrapper drush command to do this. In my drush\_hook\_COMMAND, I call

```
system('sudo -i -u www-data /usr/bin/drush --uri=http://BLAH --root=BLAH cron');

```

This works in almost all ways. However it does not correctly check for updates. On my drupal status page I get

> There was a problem checking available updates for Drupal...

I've tried using drush\_shell\_exec instead of system, just the same. However if I do it via drush eval, it does work:

```
drush eval "system('sudo -i -u www-data /usr/bin/drush --uri=http://BLAH --root=BLAH cron');"

```

So I'm completely baffled. Any idea what could be different between eval and the command hook?

# Answer
OK, I've finally solved my own problem.

In summary, it wasn't actually a Drush thing in the end.

In detail, my custom drush command was also fixing file permissions and ownership, as per https://drupal.org/node/244924 (because cron can sometimes create a file, and then the file may have the wrong owner/perms). This sets the ctime on all files, and it turns out that Drupal update checking relies on the ctime.

With hindsight of course I should have done a test with the permissions line removed from my custom command, but it hadn't occurred to me it could be relevant.
> 0 votes

---
Tags: drush, updating, cron
---


# Question
Title: Function preprocess_views_view if not logged in
I have added two javascripts for one page only using preprosess in template.php. The two scripts seem to work well.

The jquery version I include on this page/view is interfering with admin overlay and other stuff for the editor. I'd like to apply this preprosess only if the user is not logged in.

```
/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
     // add needed javascript
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
     drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
  }
}

```

Is it possible to correct this function to make sure the scripts are not served to logged in users? Or does it require a different approach like preprocess\_html?

(For now there is not going to be registered users other than editors)

(Using Drupal 7.25 and custom subtheme of Responsive Bartik)

# Answer
> 2 votes
Sure, add either:

```
global $user;

```

to your function and check its `uid` status or wrap the `drupal_add_js` in an `IF` block using the Core API function user\_is\_logged\_in()

For exmaple:

```
$user_is_not_logged_in = (user_is_logged_in() === FALSE);
if ($user_is_not_logged_in) {
  if ($view->name == 'foo') {
    /* drupal_add_js(...); */
  }
}

```

**EDIT:**

So the full thing (doing your homework for you) would look like this:

```
/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
    if (!user_is_logged_in()) {
      // add needed javascript
       drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
       drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
    }
  }
}

```

---
Tags: views, theming
---


# Question
Title: How to control a taxonomy view's output?
On the page referenced below, the two blocks to the left are separate views that represent two different taxonomy terms: "fence type" and "application."

J.C. Greene Rail Fencing photos page

I want to be able to add a new page of photos each job and be able to label type with something like "2 Rail" and application with "Horse fence" for example. But the views need to be dynamic, so that if a new type/application is used, it is added to the list to the left and the styles applied as desired.

For example, if a new fence is installed, and its application is to keep cattle in a field, then I might put "Cattle fence" in the application field, so a new item would be added to the Application block, and upon clicking "Cattle fence," the visitor would see a grid showing one job with one picture (later to see more jobs as more cattle fences are done). Upon clicking the one picture, it would go to that job's page with the slideshow, as shown by the link below (which is what I want to see when clicking on the 2 Rail link in fence type).

2 Rail test view

To get an idea of the view configuration for each block, check out this image: (Right click & click 'view image' to see the full size.)

# Answer
> 0 votes
It sounds like you're trying to do a couple complex things: 1) use contextual filters to choose which term to show and 2) then you're trying to theme certain taxonomy term pages. Once you've got stuff set up in a way that uses these concepts, you should be able to accomplish your end goal (*But the views need to be dynamic, so that if a new type/application is used, it is added to the list to the left and the styles applied as desired.*) relatively easily.

This is a good basic introduction into Views Contextual Filters: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

As for theming taxonomy term pages, I think everyone has different ideas on how to best to do that, but if you've already got these three views set up, it might be easiest to use Panels (https://drupal.org/project/panels) and drop those existing views into a panel that is context-based. Of course, Panels comes with its own learning curve, so it might not actually be that easy (though here is a basic introduction for something like what you're trying to do: https://drupal.org/node/1582906). And maybe I'm over-complicating this by assuming you want to theme your pages; maybe contextual filters were all you needed?

Just in case, here are some other ways of theming taxonomy pages:

I'm sure there are a bunch of other ways too, but that's all I've got off the top of my head for now. And I'm sure someone else will chime in with more options soon.

Also, here are some other links that you might find useful:

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


# Question
Title: Which folders/files in drupal 6 need not executive permission?
In order to tighten security of D6 against malicious XSS file uploads, I am wondering what files and folders can have go-x permission where the group is webserver.

# Answer
All folders need `+x` perhaps you're referring to `+w` ? In which case, only the files folder e.g in `/sites/default/files` needs to be `+w` by the webserver. All other folders can be owned and writeable by root only.

Here's some find commands to recursively chmod the file/folder permissions correctly

```
;Change all directories to 755 (-rwxr-xr-x):
find /var/www/mysite -type d -exec chmod 755 {} \;

;Change all files to 644 (-rw-r--r--):
find /var/www/mysite -type f -exec chmod 644 {} \;

;Change ownership of files directory and files to webserver user, e.g www-data
chown -R www-data:www-data sites/default/files

```

Update: example nginx conf to disallow .php file access in the files directory:

```
# Do not attempt to serve php files within sites/default/files
location ~* ^/sites/default/files/.*\.php$ {
    return 404;
}

```
> 3 votes

---
Tags: security, files
---


# Question
Title: Which SELinux setting prevents module upload via Admin interface?
Just wondering if anyone knows which SELinux boolean(s) is/are blocking the installation of new modules via the admin (FTP) upload interface. I have VSFTPD installed, and can upload via FTP client. I just wanted to know for future reference. If I use "setenforce 0", it works fine.

# Answer
I believe I have pegged the variable in question!

```
setsebool httpd_can_network_connect on

```

This allows the web server to connect to the FTP server. So, if you have set up an FTP server and account, but still can't upload modules to Drupal via the front end, try the above command!
> 0 votes

---
Tags: 7, files
---


# Question
Title: EntityDrupalWrapper->value() causes infinite recursion on user login?
I have a few instances on my site where I perform actions on User Login.

I create an EntityMetadataWrapper like so:

```
global $user;
$uw = entity_metadata_wrapper('user', $user);

```

And then I go to retrieve values like this:

```
$special_value = $uw->field_special_value->value()

```

For some reason, this particular line will cause an infinite recursion and crash my site.

Does anyone know what I'm doing wrong here? I am calling one of these from a Rules event and another one from `hook_user_login`, but it seems like no matter what, I get this recursive error.

This ONLY seems to happen in `hook_user_login`, all of my other `value()` calls to Entity Metadata Wrappers seem to work fine.

Note; these are both Entity References -- one references a Taxonomy Term and the other references a custom Entity.

# Answer
are you sure the user is logged in and you have a full `$user` object available in your rule?

Maybe you have to call `$user = user_load($uid, TRUE);` explicity for this 1 case?
> 0 votes

---
Tags: 7, entities
---


title: How can I truncate uploaded file name

text:
# Question
Title: How can I truncate uploaded file name
Can anyone suggest a way, or a module to truncate very long filenames which are uploaded to a Drupal 7 website? I have a client who keeps uploading files that are actually sentences and I want to limit the filename to a reasonable and certain amount of characters (say 20).

Thanks for any help on this.

# Answer
You could use a presave hook and rename the file before it gets saved: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_file\_presave/7
> 0 votes

---
Tags: files
---


# Question
Title: Connecting 3 content types together entity reference/field collection - adding references in reverse?
I have 3 content types:

**1. Client** Fields: business name, description, contact name (all standard text fields)

**Field collection (called 'client campaign'): Fields: Entity reference field to campaign content type - so I can select campaign to tie this client to.**

**2. Campaign** Fields: Campaign brief, campaign duration, campaign budget, campaign monthly hours (all standard text fields)

**Field collection (called 'collection publishers'): fields, publisher status (paid, live, dead, pending) \[select list\], publisher live date \[pop up date\], publisher payment amount \[integer\], Entity reference field to publisher field - so I can select publisher from drop down**

**3. Publishers**

Fields: website url, name, contact email, payment method (all standard text fields)

If I now:

1) add a client (create one client node) 2) add a campaign (create one campaign node)

I now can add publishers to my campaigns via the field collection added to this content type (collection publishers) This is set to unlimited to I can add as many as I want, in each one I can add in details for each publisher such as 'payment amount' 'live date' and all the other fields that are within this collection.

This all works fine but I need to be able to see all my publishers in one view with details of them and 'reverse' add them to a campaign all at once, perhaps via checkboxes. This will save loads of time. I tried an editable view but cannot seem to get this to work. I am not sure why. It is almost like I need to somehow write to the database without opening up the publisher node..

Was wondering it anyone out there can give me some pointers here or just tell me I am doing it all wrong! I don't mind which.

(the end goal here is to track publishers working across multiple campaigns and then I can see what's gong on at all times through views I'll create)

*ADDED A SCREEN SHOT OF THE 'LOGIC' BEHIND THIS!*

Thanks for any help in advance.

Screengrab 2 shows how the current campaign node edit form looks - the field collection is showing the publisher nodes.

Screengrab 3 shows how I would probably like this to look, an editable view of publishers that I can assign a campaign to then save. However, this may not work as publishers can work over many campaigns...

# Answer
It looks like you need Corresponding Entity References:

> It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.
> 1 votes

# Answer
I do all that you want with the following modules:

* entityconnect - edit entityreference in content
* entityreference - call node is an nother content into creatting content
* field\_collection - call entityreference in ones
* field\_collection\_table - option view display table in another necessary views (when u want display untimited entityreference field in views)
* field\_collection\_views - diplay all content of field collection to views into node
> -1 votes

---
Tags: entities
---


title: D7 Location module proximity search

text:
# Question
Title: D7 Location module proximity search
I want be able to have users search for other users based on distance. I thought I did it correctly but everytime I search I get no results.

Heres what I did:

* Install location https://drupal.org/project/location
* Enabled location /w location entity, location search, location taxonomy, user locations
* Added location field to profile2 profile
* Ran the US zipcode file that comes with the location module
* Created a view to show profiles
* Added a relationship to location
* Added a filter of location proximity search based on zipcode and country /w a relation field\_location

# Answer
Every I did above was correct. I needed to have my users re-enter there location so geo-coding would be added to their profile.
> 0 votes

---
Tags: search, users, location
---


# Question
Title: How to query for null in nested db_or conditional
I am trying to perform a query as listed below (notice the check for NULL)

```
$query = db_select('node', 'n');
/* add fields and joins... */
$query->condition(db_or()
      ->condition(db_and()
                  ->condition('join_alias1.field_date_unassigned_value', NULL, 'IS')
                  ->condition('join_alias2.field_date_assigned_value', $end_date, '<='))
      ->condition(db_and()
                  ->condition('join_alias1.field_date_unassigned_value', $start_date, '>=')
                  ->condition('join_alias2.field_date_assigned_or_submitted_value', $end_date, '<=')));

```

I am aware that Drupal expects Null values to be checked like

```
$query->isNull('myfield');

```

But I don't understand how to perform a query like I listed above while using `$query->isNull()`.

Any ideas? Thanks

# Answer
You can use `isNull()` in the `db_and()` condition, it'll work just fine:

```
$query->condition(db_or()
  ->condition(db_and()
    ->isNull('join_alias1.field_date_unassigned_value')
    ->condition('join_alias2.field_date_assigned_value', $end_date, '<=')
  )
  ->condition(db_and()
    ->condition('join_alias1.field_date_unassigned_value', $start_date, '>=')
    ->condition('join_alias2.field_date_assigned_or_submitted_value', $end_date, '<=')
  )
);

```
> 5 votes

---
Tags: database
---


# Question
Title: How to theme Logintoboggan Access Denied Login Page
I am looking to override Logintoboggan's default access denied login page. I can't seem to find what I name the template file and what the defaults are that are required. Any help is appreciated.

# Answer
> 3 votes
Assuming Drupal 7, if you are trying to override LT's `toboggan/denied` page, eg, what overall structure you see when you land on `www.example.com/toboggan/denied`, you could copy your theme's `page.tpl.php` to `page--toboggan--denied.tpl.php` and modify whatever you wanted in there. (If Drupal 6, the new name would be `page-toboggan-denied.tpl.php`.)

If you are instead (or also) trying to override the output of LT's theme function that produces the `You are not authorized to access this page` message on that page, you could create a function in your theme's `template.php` file:

```
function YOUR_THEME_lt_access_denied($variables) {
  return t("Whoa, Dude!  You aren't allowed in here!");
}

```

that would override LT's `theme_lt_access_denied()` function, which is just a quick:

```
function theme_lt_access_denied($variables) {
  return t('You are not authorized to access this page.');
}

```

Or, you could instead create a template file called `lt-access-denied.tpl.php` in your theme that would accomplish the same thing with some potentially more fanciness:

```
<?php
  // contents of lt-access-denied.tpl.php
?>
<div class="tsk-tsk">
  Whoa, Dude!  You aren't allowed in here!
</div>

```

In any case, if you are trying to override any of the other theme functions in LT, or any other module for that matter, you would first look in the module and search for the hook\_theme() to see what's available, and in LT, that would be the `logintoboggan_theme()` function found in the `logintoboggan.module` file. Another great resource is Drupal 7 Template (Theme Hook) Suggestions which details the template names and variants used in Drupal core modules.

# Answer
> 0 votes
You can make a function in your theme's `template.php` file. This function below is the theme hook you're looking for... (from looking at the logintoboggan module ver. 7.x-1.3)

```
/**
 * Theme the Access Denied message.
 */
function theme_lt_access_denied($variables) {
  return t('You are not authorized to access this page.');
}

```

That means, in your custom theme you can make your own theme function. Like this:

```
/**
 * Theme the Access Denied message.
 */
function CUSTOMTHEMENAME_lt_access_denied($variables) {
  return 'WHATEVER HTML/TEXT YOU WANT';
}

```

You can even make a preprocess function that can add to the `$variables` element in the function above like so:

```
/**
 * Implements hook_preprocess_hook.
 */
function CUSTOMTHEMENAME_preprocess_lt_access_denied(&$variables) {
  $variables['MYNEWVAR'] = 'NEWVAR';
}

```

Then you can pull `$variables['MYNEWVAR']` out of the `$variables` var in the `CUSTOMTHEMENAME_lt_access_denied` function and somehow use it, like this...

```
/**
 * Theme the Access Denied message.
 */
function CUSTOMTHEMENAME_lt_access_denied($variables) {
  return $variables['MYNEWVAR']; // which would be 'NEWVAR';
}

```

---
Tags: theming, authentication-authorization
---


# Question
Title: Are entity IDs assigned per entity or across the board?
I'm building an electronic parts database in D7 and want to create a custom "part" entity with bundles for resistors, capacitors, etc.

I also need to autocreate an atomic serial part number common to all bundles, i.e no separate part numbering system per bundle. I was going to use the Serial module but it only works with nodes. In D6 I did everything in nodes for a similar application and just used the NID, but this parts DB really wants a cleaner solution using entities. I'd like to use the entity ID as the serial part number but only if it's unique per custom entity type.

Question is: Does each custom entity type I create have its own set of entity IDs or is it like in D6 with nodes where NIDs apply across all content types?

# Answer
Each entity type has it's own ID sequence. For example a user may have the uid of 1 while a node may also have an nid of 1. Similarly a taxonomy term may have a tid of 1. In all those cases the "entity\_id" is 1.

Regarding the serial module, as it provides a field via the Field API, presumably that field could be attached to any entity bundle.

In regards to linking your entities, you could probably use the entityreference module to create reference links between your entities.
> 1 votes

# Answer
Each entity type maintains its own IDs, they're not related to the IDs of any other entity type.

So you can easily have node/1, taxonomy\_term/1, entityform/1, custom\_entity/1, etc. You can't use the ID as a unique field across different types of entity.

As Mołot mentioned in the comments, the UUID module goes some way to solving your problem.
> 1 votes

# Answer
Ok, I'll just use the entity ID as my "part number" as it's unique to that entity type. I'll also use Computed Field to start the sequence at 1000000001 or something like that.

UUID generates a hash, not a sequential number like 0004538615 which is what I want. A long alphanumeric hash would be too confusing. Part numbers get referenced by vendors on purchase orders, for example.

I will have a custom entity type called "Parts" and bundles for categories like resistors, capacitors, etc. That way a sequential part number will be created for every new record no matter which bundle triggered it.

The Serial Field module doesn't work with entities, only nodes. Some work has been done about that but the thread went dead 9 months ago.

Thanks for the answers!
> 0 votes

---
Tags: entities
---


# Question
Title: How do I turn off full html in comments only in drupal 7
Okay, I have set all content editing for admins on full html in drupal 7. I have also enabled wysiwyg and ckeditor. All is good, except I just want plain text and no ckeditor for the comments sections but want to allow automatic converting of links on it. How do I fix this? thanks guys.

# Answer
> 2 votes
Two settings control which text format is used for posting content: permissions and the order of the text formats. The first format a user has permissions for is used. Since administrators have permission to use the Full HTML format, if it is listed first under `admin/config/content/formats` it will be used by default - and if it's configured with a WYSIWYG profile, that too wil be used.

Better Formats (already partly in D7 core) will give the possibility to configure which text format is used per content type / comments (so you can assign a text format without WYSIWYG profile). Unfortunately, it is not yet ready for Drupal 7. So at the moment you cannot (AFAIK) configure whether or not to use the WYSIWYG without (manually) chosing different input formats (or custom coding). Some workarounds:

* You could list Filtered HTML first and not assign it a WYSIWYG profile. You'll have to select Full HTML for each post where you do want to use it.
* Or you could configure comments to use plain text. This leaves you without link parsing however (for Article: Structure \> Content types \> Article \> Comment fields: text processing (plain text or filtered text).
* Or you can set the WYSIWYG editor to disabled by default, and toggle it active when you do want to use it. Then start using Better Formats when it's ready.

On a side note, it's better not to use Full HTML by default - even with trusted users, just to avoid mistakes. It would be better to create an extra text format and configure the HTML Filter with an extended set of HTML tags.

**Edit**: I wanted to use something like this myself. You can (temporarily) use a custom module like this to automatically set the text format for node or comment bodies. So, adapt this example code for comment\_body and set to filtered\_html (or another format not configured for WYSIWYG) and you'll also have link parsing.

# Answer
> 2 votes
I've always got on well with the Better Formats module, which allows complete control of input formats per type (comment/block/node), role and content type.

Others have answered this too, have a look at these:

# Answer
> 1 votes
In Drupal 7

1. Go to your content type and click on the "`Comment fields`" button.
2. Edit the `comment_body` field
3. Select the `"Plain text"`

The url to get to comments for your content type will be (if you have comments enabled for that type)

```
admin/structure/types/manage/[YOUR CONTENT TYPE]/comment/fields

```

---
Tags: wysiwyg
---


# Question
Title: workbench access warning message when I click preview
Has anybody come across a warning message which appears when you preview content? This message only displays when the workbench access module has been installed and the following setting has been checked 'Require a Workbench Access form element'

The messages: "\*Warning: array\_keys() expects parameter 1 to be array, string given in workbench\_access\_node\_form\_element() (line 1465 of C:\wamp\www\dev\sites\all\modules\contrib\workbench\_access-7.x-1.2\workbench\_access\workbench\_access.module).\*

\*Warning: Invalid argument supplied for foreach() in workbench\_access\_node\_form\_element() (line 1466 of C:\wamp\www\dev\sites\all\modules\contrib\workbench\_access-7.x-1.2\workbench\_access\workbench\_access.module).\* "

Cheers!

# Answer
> 0 votes
You can find the related bug here and the patch here.

You can then download the patch into the `workbench_access` directory and execute

```
patch -p1 < 1935190-wa-array-keys_0_1.patch

```

---
Tags: workbench, entities
---


# Question
Title: how to Create some nodes of a content type when created a node of another content type?
I would like to create an editable task table with slickgrid view, where each row is a node (of content type 2) that will be created automatically by a different content type (the 1st content type) or a webform.

Content type 1 - The 1st content type have 4 fields (this node will create automatically some nodes of the second content type)

1st - "Days" - is a Date field type - with unlimited (1 to 10) values

2nd - "City's" - is a Reference to a Term - with unlimited (1 to 10) values

3th - "Type of operation" is a Reference to a Term - with an unique value

4th - "Number of person by city" is a Integer field type - with an unique value

Content type 2 - the 2nd content type have those fields

1st - "Day" - is a Date field type - with an unique value

2nd - "City" - is a Reference to a Term - with an unique value

3th - "Type of operation" is a Reference to a Term - with an unique value

4th - "Name of a person" is a text field - with an unique value

Now for example if i create a node of Content type 1 with 5 values for the date field and 5 for the City's and the number "2" for the integer field, it will create automatically **5\*5\*2= 50** nodes of Content type 2, the "name of a person" field will be created empty of course.

I think i must create a module or perhaps with rules it's possible ? is it possible to replace the content type 1 by a webform? I'm newbie in drupal module developement. Thanks.

# Answer
> 0 votes
Custom module is the best way to go. With rules it's really complex. You need to use below hook in your custom module to solve above problem.

* hook\_node\_insert to hook into above node creation. Hook Responds to creation of a new node.
* In above hook implementation you need to create new nodes using code. Please find article which explains same.

---
Tags: nodes
---


title: How to redirect on User based?

text:
# Question
Title: How to redirect on User based?
I am new to drupal So I want to redirect the user based on login Say, if there is an Anonymous user, he will be redirected to specific page, and if is an Authorized user along with login id and password, then he will be redirected to other specific page using script

# Answer
> 0 votes
Use Rules module and create redirect rules.

Project page says

> The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

Example use cases

* Build flexible content publishing workflows changes
* Send customized mails to notify your users about important
* **Create custom redirections**, system messages, breadcrumbs, ...
* Build an eCommerce store using Drupal Commerce And many more...

# Answer
> 0 votes
Simply implement `hook_preprocess_page()` in `template.php` file and add your business logic: example

```
function MY_THEME_preprocess_page(&$variables) {
  if(CONDITION /* additional condition, e.g. $variables['is_front'] */) {
    if(user_is_anonymous()) {
      drupal_goto('node/13'); //change the url, with yours
    }
    else {
      drupal_goto('node/7'); //change the url, with yours
    }
  }
}

```

if you are implementing this hook for the first time then you need to flussh the cache.

---
Tags: redirection
---