# Question
Title: CSS fix for stacked gear icons in Drupal Panels?
When using the Panels module within Drupal, I often end up with **multiple gear icons stacked on top of each other**, inaccessible to the Drupal admin.

For example, take a Panels page with this structure:

1. MyCustomContentPaneTop
2. A Drupal View
3. MyCustomContentPaneBottom

When logged in as a Drupal admin, I can access the gear icon for MyCustomContentPaneBottom easily.

However, when I try to edit **MyCustomContentPaneTop**, I can only see an "Edit Panel" gear icon. I can see that this originates with this code, toward the bottom of the page.

```
<div class="contextual-links-wrapper contextual-links-processed">
  <a class="contextual-links-trigger" href="#">Configure</a>
  <ul class="contextual-links" style="display: none;">
    <li class="0 first last">
      <a class="colorboxNodeContextual-processed" href="/admin/structure/pages/nojs/operation/page-MyPanelPageName/handlers/page_MyPanelPageName_panel_context_2/content">Edit Panel</a>
    </li>
  </ul>
</div>

```

I can see in the HTML source that the gear icon does exist for **MyCustomContentPaneTop**, but it must be sitting in a z-index below the Panels gear icon.

```
<div class="pane-content">
  <div class="contextual-links-region"><div class="panel-display panel-1col clearfix" >
  <div class="panel-panel panel-col">
  <div><div class="contextual-links-region panel-pane pane-custom pane-1" >
  <div class="contextual-links-wrapper"><ul class="contextual-links"><li class="0 first last"><a href="/admin/structure/ctools-content/list/MyCustomContentPaneTop/edit">Configure content pane</a></li></ul></div>
  ...
</div>

```

I know I can hack around with very specific CSS rules that apply only to pages where I discover this issue. However, is there an easy Drupal (or CSS) method to say, "If two gear icons are stacked on top of one another, stagger them by 5 pixels?"

# Answer
> 2 votes
Here's the minified version of that same Javascript, from said coworker. :)

```
jQuery(function($){l=[];t=[];$('.contextual-links-wrapper').each(function(){h=$(this);o=h.offset();k=o.left;v=o.top;if($.inArray(k,l)>-1&&$.inArray(v,t)>-1){h.offset({top:v+=50})}l.push(k);t.push(v)})});

```

# Answer
> 1 votes
A co-worker suggested the following. Use JavaScript to find the X and Y coordinates of each gear icon, and then move the icons by 50 pixels if they overlap.

I like it!

```
jQuery(function($) {
  // Declare Arrays
  left_array = new Array();
  top_array = new Array();

  // Get all the contexual link containers and iterate through them
  $('.contextual-links-wrapper').each(function(index){
    var this_left = $(this).offset().left;  // Set a convenience variable for the x-coord of the gear
    var this_top = $(this).offset().top;    // Set a convenience variable for the y-coord of the gear

    // If a previous link container had identical x&y coords, add 50 pixels to the current container y-coord
    if($.inArray(this_left,left_array) > -1 && $.inArray(this_top,top_array) > -1) {
      this_top += 50;
      $(this).offset({top: this_top});
    }

    left_array.push(this_left);  // Add the current container x-coord to the list of containers
    top_array.push(this_top);    // Add the current container y-coord to the list of containers
  });
});

```

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


title: CDN not working on multilingual site

text:
# Question
Title: CDN not working on multilingual site
I have a site that is multilingual using path prefix, for example I can have:

* example.com/en
* example.com/es
* example.com/fr

If the user goes to `example.com`, a language selection page appears (using the language selection module).

But I'm trying to enable the CDN module and it's not working because all resources are pointing to `example.com/sites/.../somecss.css` instead of `example.com/en/sites/...`

If I disable the CDN module the resources are pointed to the correct path. How can I fix this? I think it's bug in the CDN module.

Using Drupal 7 & Amazon CloudFront. I don't want to change the site to subdomain for the languages (eg, `en.example.com`).

# Answer
> 0 votes
Found the issue the Language Selection Page module is causing the issue https://drupal.org/node/2283985. You can see the styles exemption in the code. For you I would add in the advagg and cdn paths to the language\_selection\_page\_blacklisted\_paths variable. You should find it under "Paths blacklist" on the `admin/config/regional/language/configure/selection_page` page.

Gotta run will add in the exact paths tomorrow, but it will be something like

> farfuture/\*
> sites/default/files/advagg\_css/\*
> sites/default/files/advagg\_js/\*
> httprl\_async\_function\_callback

---
Tags: i18n-l10n, cdn
---


# Question
Title: Workflow module missing content type mapping
I don't see a tab or area to add a content type to a work flow. The documentation does not match what I am seeing. The tabs I see at the top are:

```
Primary tabs
  Edit
  States
  Transitions(active tab)
  Labels
  Permission summary

```

Where should I look to find the mapping area?

# Answer
> 0 votes
The recent versions of workflow module comes with `workflow_field` and `workflow_node` modules. If you want to use `workflow_field`, a new feature, then you have to create a workflow field in your content type and it can also be used in any entity. But if you to use it the old way then enable `workflow_node` module and you can assign the content type to the workflow, but it can only be used for nodes.

---
Tags: workflows
---


title: Event volunteers registration module

text:
# Question
Title: Event volunteers registration module
I'm looking for a module for an event website which calls for volunteers to register by sending name/email.

Ideally, it would allow some users to access the registered volunteers database in some downloadable format (CSV for instance).

Is there something like this for D7? I've been googling but found nothing.

# Answer
I've used the Webform module for this situation in the past. Just create a name and email component!

> Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.
> 1 votes

---
Tags: 7
---


# Question
Title: In image_link setting, How can I change "content" to the specific node
The example in API show that 'image\_link' =\> 'content', How can I change "content" to the specific node. This is my code in basic page:

```
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_pg_image');
$output = field_view_value('node', $node, 'field_pg_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
  'image_style' => 'thumbnail',
  'image_link' => 'xxxxxxxxx',
),
));
print render($output);

```

I would like to change 'image\_link' =\> 'xxxxxxxxx' to "node/30?ptype=20"; How to do this

# Answer
keep

```
'image_link' => 'content',

```

and after your code, before print:

```
$output['#path']['path'] = "node/30?ptype=20";

```
> 1 votes

---
Tags: entities
---


# Question
Title: Register the user from the login form itself
I want to create new accounts only if user name and password have matched with that of with Active Directory.

So if a completely new user tries to login and enters correct Active Directory login & password then I'm adding him/her using user\_save in the form validator.

But at the same time I'm returning with error that "please re-login".

However I want a seamless login. That is if a new user tries to login -- I'll create a new user and at the same time he/she should also be logged in.

How can I do this?

# Answer
> 3 votes
I had a similar use case in the past and i am giving some snippet, hope will help you. The key was *user\_login\_finalize* and *then redirecting internally to the same page*.

Load the user if already present or create and then load him

```
$user = user_load_by_name_and_password($username, $password);
if ($user == FALSE) {
  $newuser = array(
    'name' => $username,
    'pass' => $password, // some password
    'mail' => $email, // some email
    'status' => 1,
    'init' => $email, // some email id
    'roles' => $roles, // some roles
  );
  // New user is saved and loaded
  $user = user_save(drupal_anonymous_user(), $newuser);
}
user_login_finalize();
drupal_goto(get_current_url_with_query_params());

```

http://api.drupal.org/api/drupal/modules!user!user.module/function/user\_login\_finalize/7 Finalize the login process. Must be called when logging in a user

drupal\_goto must be called as user\_login\_finalize() bootstraps the currently logged in user too late and hence will throw 'access denied' even for the page for which the user has permission. drupal\_goto() makes sure that the user is properly bootstrapped and then is made to access the page again.

It is equivalent to reloading the page after the user has logged in but this is the only way i got my external login work. Refer User login using a token or ID (no password)

# Answer
> 1 votes
I wrote a simple module to do this: first I alter a user\_login form and add my function to it's validation functions. on my validate function I check if username/password combination is correct,if not I check if username is not existed and then I create new user with that combination and regenerate a session to login this user,then redirect to '/user'.now user is logged in.but there is a error saying "Sorry, unrecognized username or password. Have you forgotten your password?" to clear errors I called drupal\_get\_messages() function and set my custom message to welcome user.

```
//implement hook_form_FORM_ID_alter
function MODULENAME_form_user_login_alter(&$form, $form_state, $form_id) {
    if ($form['#form_id'] == 'user_login') {
        $form['#validate'][] = 'MODULENAME_login_validate';
    }
}

function MODULENAME_login_validate($form, &$form_state) {
    $username = $form_state['values']['name'];
    $password = $form_state['values']['pass'];
    $user = user_authenticate($username, $password);
    $roles = array(2); // authenticated user role id,you can set other roles here
    if ($user == FALSE && !user_load_by_name($username)) { /* and other validation you want for username-passwors structures */
    $acc = array(
        'name' => $username,
        'pass' => $password,
        'mail' => $username . '@dummy.com',
        'status' => 1,
        'roles' => $roles, // some roles
    );
    // New user is saved and loaded
    $account = user_save(drupal_anonymous_user(), $acc);
    global $user;
    $user = $account;
    drupal_session_regenerate(); // regenerate a session to login a user
    drupal_get_messages(); // to clear error message generated by user login form
    drupal_set_message('Welcome'); // or other message you want
    drupal_goto('user');
    }
}

```

# Answer
> 0 votes
I've implemented it using JQuery. So if anybody presses Submit button after entering login & passwd then I send an Ajax request and in the back-end module I receive the login & passwd, check it in the Active Directory, if verified then create a new user and send success to the front end, which then submits the form and user is able to login(without even registering).

---
Tags: 7
---


# Question
Title: Error while trying to install drupal commerce kickstart
I am new to drupal and am trying to install drupal commerce kickstart on a digital ocean server. But it fails at install profile step with the following error,

An AJAX HTTP error occurred. HTTP Result Code: 404 Debugging information follows. Path: http:///install.php?profile=commerce\_kickstart&welcome=done&locale=en&use\_dfp=1&id=1&op=do StatusText: Not Found ResponseText: 404 Not Found 404 Not Found nginx/1.0.15

I dont know what to do. Please help. I can install drupal easily with no issues but installing all modules for commerce is a headache so I decided against it.

NOTE: is my website

# Answer
* Go to your php.ini file. Search and change values for the following:

```
post_max_size = 500M
upload_max_filesize = 500M
max_execution_time = 2000
max_input_time = 2000
memory_limit = 512M

```

and save file

* In apps config

C:\wamp\apps\phpmyadmin3.3.9/config.inc.php (whatever your server is)

add the below code

```
     //maximum execution time in seconds (0 for no limit)
     $cfg['ExecTimeLimit'] = 300;

```

and save the file.

* Restart your WAMP Server.

For more details go there.
> 2 votes

---
Tags: commerce
---


# Question
Title: How to create a bean bundle programatically
I don't want to use features. ;)

This is my code:

> beanform.info

```
name = Bean form
description = Configure beans blocks to print forms into it.
core = 7.x
files[] = "plugins/BeanForm.class.php"
package = "Bean"
dependencies[] = "bean"

```

> beanform.module

```
<?php
/**
 * @file
 * beanform module file to store the hooks.
 */

/**
 * Implements hook_bean_types_api_info()
 */
function beanform_bean_types_api_info() {
 return array('api' => 4);
}

/**
 * Implements hook_bean_types()
 */
function beanform_bean_types() {
  $plugins = array();
  $plugin_path = drupal_get_path('module', 'beanform') . '/plugins/bean';
  $plugins['bean_form'] = array(
    'name' => 'bean_form',
    'label' => t('Bean form'),
    'description' => t('Choose a form to print into a bean'),
    'handler' => array(
      'class' => 'BeanForm',
      'parent' => 'bean',
      // 'path' => $plugin_path,
      // 'file' => 'BeanForm.inc',
    ),
    'path' => $plugin_path,
    'file' => 'BeanForm.inc',
  );

  kpr ($plugins);

  return $plugins;
}

/**
 * Implements hook_theme()
 */
function beanform_theme(){
  $items = array();
  $items ['theme_bean_form'] = array(
    'arguments' => array(
      'form' => NULL,
    ),
    'template' => 'templates/bean-form',
    'file' => 'beanform.theme.inc',
  );

  return $items;
}

?>

```

But When I go to `/admin/structure/block-types` I don't see my bean.

I don't find the problem, and I'm checking bean\_examples and bean\_twitter\_pull to see how it should be done.

Thanks

Oskar

# Answer
> 0 votes
With bean modules it's required that if you use "name" attribute is the same name that the $plugins key.

In my case

```
'name' => 'beanform'

```

The beast options is not use it, it's no a required attribute.

Oskar

my actual code:

```
  $plugins['beanform'] = array(
'name' => 'beanform',
'label' => t('Bean form'),
'description' => t('Choose a form to print into a bean'),
'handler' => array(
  'class' => 'BeanForm',
  'parent' => 'bean',
  'path' => $plugin_path,
  'file' => 'Beanorm.inc',
),
//   'path' => $plugin_path,
//   'file' => 'BeanForm.inc',
   'editable' => TRUE,
  );

```

---
Tags: 7, blocks
---


title: Clear a single url from cache

text:
# Question
Title: Clear a single url from cache
Using Drupal's standard cache system, is there a way to clear the cache for a node or url without clearing the entire cache (which slows down the whole site)?

# Answer
> 6 votes
The module Cache actions provide very fine grained control over your cache clearing.

Unfortunately, whether it will solve your exact problem depends on how this particular url is built up. In case it doesn't do exactly what you want, it's codebase would still be an excellent start for building more exactly what you need.

# Answer
> 6 votes
Yes you can do it programmatically also.

In this example we clear the front page cache :

```
$url = url('<front>',  array('absolute' => TRUE));

cache_clear_all($url, 'cache_page');

```

Drupal stores the paths as CID in table and in above example we are providing front page URL as CID as a first argument in the function and if you define the CID, it is mandatory to define the second argument $bin in the function, which is like from which table you want to delete cache. As we have to delete a single page, so its present in cache\_page which holds cache for pages.

# Answer
> 3 votes
There is a module for that: Flush page cache. Here is a quote about it (from the module's project page):

> Easing the pain when you need to flush ... Drupal's cache.
>
> Flushing Drupal's cache on a large site can feel like you're waiting to takeoff on the tarmac at JFK. The delay comes from the fact that when you clear Drupal's cache, it clears everything. Most of time you just want to flush the cache for specific object on a page.
>
> The 'Flush page cache' module solves this problem by flushing only the cached objects for a single page. Additionally, you can define custom objects and cache tables to be cleared on specific pages.

# Answer
> 0 votes
Another option would be to create a form and use the function cache\_clear\_all on the url whose cache you want to clear. I found an example of it use here

# Answer
> 0 votes
A little late to the party here, but, the Cache Expire module is probably what you're looking for. It gives you really fine-grained control over how caching is utilized for multiple entity types (if you use the 2.x version of the module).

Either version of the module however gives you access to a Rule action ***"Clear URLs from page cache"***. So, you can specify whatever events and conditions are necessary for the rule to fire, and then the URLs you specify will get wiped out. Hope this helps.

# Answer
> -1 votes
cache clearing stuff can be done simply by downloading drush module from http://drupal.org/project/drush

```
terminal->your drupal directory

```

write the command drush cc

It would return you with

\[0\] : Cancel
\[1\] : all
\[2\] : drush
\[3\] : theme-registry \[4\] : menu
\[5\] : css-js
\[6\] : block
\[7\] : module-list
\[8\] : theme-list
\[9\] : registry
\[10\] : views

So you can select which ever thing you want to clear..

If you want to do clear cache from the drupal website then you could install and enable the module http://drupal.org/project/admin\_menu It provides a home icon on your drupal sile and would give you a menu list where you could go for cache clear stuff....

---
Tags: caching
---


title: Do one time action after logging in

text:
# Question
Title: Do one time action after logging in
I need to add a Javascript file only once immediately after logging in - which will open another URL in a new window.

Without using \_SESSION what'll be the right place to add drupal\_add\_js function only once after logging in?

Is there a hook which is called in the very first logged-in page?

# Answer
Add the JS file inside the implementation of `hook_user_login()`.
Function docs:

> The user just logged in. Parameters
>
> `$edit`: The array of form values submitted by the user.
>
> `$account`: The user object on which the operation was just performed.
> 0 votes

---
Tags: 7
---


# Question
Title: Disabled date field on node form stops it from saving
I have a date field on a drupal node edit form using the pop-up calendar widget. When certain things happen on my site I have to disable some fields on that node edit form, including the date.

However, when this happens, I can no longer save the form because I get this message:

> The value input for field \[my field\] is invalid.

I tried changing the widget to plain text, and it works fine, so it is an issue with the pop-up calendar widget.

Any ideas?

# Answer
> 0 votes
If using `hook_form_alter` you can use **`#limit_validation_errors`** to exclude that field from validation.

> The #limit\_validation\_errors property is a list of "sections" within $form\_state\['values'\] that must contain valid values. Each "section" is an array with the ordered set of keys needed to reach that part of $form\_state\['values'\] (i.e., the #parents property of the element).

**Example 1:** Allow the "Previous" button to function, regardless of whether any user input is valid.

```
  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(),       // No validation.
    '#submit' => array('some_submit_function'),  // #submit required.
  );

```

**Example 2:** Require some, but not all, user input to be valid to process the submission of a "Previous" button.

```
  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(
      array('step1'),       // Validate $form_state['values']['step1'].
      array('foo', 'bar'),  // Validate $form_state['values']['foo']['bar'].
    ),
    '#submit' => array('some_submit_function'), // #submit required.
  );

```

**More info:** `form_set_error`

---
Tags: entities
---


# Question
Title: How to disable cron from running while another time consuming process takes place?
We bulk upload nodes on our Drupal site. Those nodes need to be Solr indexed all at once, without having to wait for cron to index them. The cron job indexes apachesolr\_cron\_limit nodes per run. As a result, if I have 40.000 records, I have to wait too long.

A solution I implemented is, creating a button which indexes all remaining. The button runs the code below.

```
function mymodule_index_all_remaining() {
  variable_set('cron_safe_threshold', 0); // Doen not work.
  module_load_include('inc', 'apachesolr', 'apachesolr.admin');
  $env_id = apachesolr_default_environment();
  apachesolr_index_batch_index_remaining($env_id);
  variable_set('cron_safe_threshold', 10800); // Does not work.
}

```

My problem is that we have cron running every 3 hours and when the cron begins (while the mymodule\_index\_all\_remaining is still running), I get HTTP 502 error. The same error occurs if I try to index the remaining from admin/config/search/apachesolr Index all queued content.

So I need to alter the cron interval, which can been seen under admin/config/system/cron, "Run cron every". This interval is stored in a static variable cron\_safe\_threshold. I tried to set it to 0, but it doesn't work. I cannot change settings.php as I really want cron to run evey 3 hours when the indexing does not run. Is there another way to pause cron jobs from running while another process takes place?

Do you recomment another way to index remaining without having the 502 error?

# Answer
You can use Elysia Cron. This module is a enhanced Cron that has, apart of many other improvements, a global disable option. As they say in a bug report this variable may help you:

> It disables ALL cron tasks. (No cron will be executed).

Also Elysia Cron allows you to set complex schedules so you may fix your problem just with the right schedule.
> 2 votes

---
Tags: search, cron
---


# Question
Title: Is there a template for the comment links field?
I want to use ajax-links-api so that when someone replies to a comment, the url comment/reply/60/51 is loaded with ajax on the current page.

I need to add rel="a class" on the reply link's anchor, to select witch div to load.

Display suite adds a manage display for comments

Is there a template file I can use to change the html for the comments field "links"?

> Update
>
> By Installing Devel and adding the block I see the comment wrapper Devel
>
> The template in modules/comment/comment.tpl does not look to have the html for links in it.Comment Template

# Answer
Why don't you use the default selectors to get the url? some thing like this:

```
(function($) {
    $(document).ready(function() {
        $("YOUR-COMMENTS-WRAPPER").find('a').click(function(){
             var url = $(this).attr('href');
        });
    )
    });
})(jQuery);

```

then use the `url` to load the `DIV`
> 0 votes

---
Tags: entities, ajax, display-suite
---


title: Show a PHP page in drupal 7

text:
# Question
Title: Show a PHP page in drupal 7
I have a php script that does some querying and book keeping of drupal tables. How can I run this php script directly from the url? The script uses drupal functions so I guess it should be aware of the API.

When I go to `mysite.com/script.php` I would like this file to run...

Is there any includes that I can add and then run the script so that it is drupal aware and at the same time, does not need to go through all the view/node/block etc? Basically I do not want to add this page as a PHP block data into one of the nodes, I would like to run in directly from the URL.

# Answer
you should boot drupal on your file so that your file be aware of drupal functions,you can do this by : YOUR\_DRUPAL\_ROOT= root of your drupal,here my drupal root was crawler.alexa.com. and require bootstrap.inc of your drupal. and then boot drupal compeletly. here is my example :

```
define('DRUPAL_ROOT', '../crawler.alexa.com');
require_once '../crawler.alexa.com/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```
> 2 votes

# Answer
I would put create a module, and use hook\_menu.

```
function mymodule_menu() {
    $items['custom/script'] = array(
      'page callback' => 'mymodule_custom_script_function',
    );
    return $items;
}

function mymodule_custom_script_function() {
    // put the code from your PHP script here
}

```
> 1 votes

# Answer
You have to change the configuration setting.

Just follow the link and you will have the solution.

https://github.com/perusio/drupal-with-nginx/issues/63
> 0 votes

---
Tags: external-scripts
---


# Question
Title: How do I load multiple nodes by a user reference?
I have a content type "property", with an owner field (field\_user\_ref) which is a user reference.

I want to loop through all of the properties, given a specific user\_id.

```
$user_id = 18273;

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'property')
  ->propertyCondition('field_user_ref', $user_id)
  ->propertyCondition('status', 1);

$result = $query->execute();  // ERROR

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    echo "<br>".$node-title;
  }
}

```

But this gives an error..

```
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node.field_user_ref' in 'where clause': SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type AS entity_type FROM {node} node WHERE (node.field_user_ref = :db_condition_placeholder_0) AND (node.status = :db_condition_placeholder_1) AND (node.type = :db_condition_placeholder_2)

```

"field\_user\_ref" is the name of the field.. property.field\_user\_ref, so not sure what should be the format here..

# Answer
And like magic, I've found the answer as a result of this answer..

EntityFieldQuery causing column not found PDO exception

```
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'property')
  ->fieldCondition('field_user_ref', "uid", $user_id)
  ->propertyCondition('status', 1);

```
> 0 votes

---
Tags: entities, database
---


# Question
Title: Drupal 7.27: 408 Request time out in Chrome browser
We are getting 408 request time out errors in Chrome browser only since the beginning of May. We have not been able to replicate the problem with any other browser. With one website we had a SSL protocol and the error only occured in Chrom on http:// After implmenting a redirect from http:// to https:// via .htaccess the error seemed to have gone. On a second site there is no SSL certificate and the error only occurs occasionally but it does. We have set the request\_time\_out to 10080 in the php.ini to no avail. Another thing we tried: We redirected that site to be accessed only with "www".

Has anyone experienced something similiar? Any suggestions would be very welcome.

# Answer
This is a Chrome bug.

https://meta.stackexchange.com/questions/208790/408-request-time-outs-still-continues/232275#232275

One solution: http://blog.haproxy.com/2014/05/26/haproxy-and-http-errors-408-in-chrome/

Seems to be limited to Chrome, page requests through http:// and servers running HAProxy.
> 0 votes

---
Tags: .htaccess, http-request
---


title: Shipping quote depending on order total

text:
# Question
Title: Shipping quote depending on order total
I am a long time drupal user and a first time ubercart user. I apologize if this question has been asked in the past. I could not find the answer through google, ubercart.org or the forums here.

We are planning on shipping our product USPS flat rate. I would like the shipping cost to depend on the order total. Is this possible?

Something like this:

0-$99.99 - $5.99

$100 - $350 - $9.99

$350 - $500 - $11.99

$500+ - Free

I am running drupal 7 with ubercart 7.x-3.4

Thanks

# Answer
Activate the following Übercart modules:

1. Shipping
2. Shipping Quotes
3. Flat rate

Go to http://yoursite.com/?q=admin/store/settings/quotes and click on "Add flat rate quote". Fill out the from and submit it. The next form should be the conditions form. Create the necessary condition(s), for example, 0 \< order:order-total AND order:order-total \< 100 as a data comparison. To enter the total values (i.e. float numbers) click on the "Switch to data selection" button near the bottom. Repeat this for all of your total ranges.
> 2 votes

---
Tags: ubercart
---


# Question
Title: Drupal.behavior unexpectedly triggered by Ajax callback
I work on a sandbox project which provides a Responsive Tabs to Accordion Panel style. Everything works fine except that once the page loaded, any Ajax callback (i.e *add to cart* or *colorbox*) **seems to trigger the js function** of my module.

## The way js function is set in plugins/styles/reponsive\_tabs.inc

```
function theme_responsive_tabstoaccordion_panels_style_render_region($vars) {
  //...
  $element = array(
    //...
    '#attached' => array(
      'js' => array(
        drupal_get_path('module', 'responsive_tabstoaccordion_panels') . '/plugins/styles/responsive_tabstoaccordion_panels.js' => array('type' => 'file'),
      ),
      //...
    ),
  );
  //set the wrapper id to give to responsive_tabstoaccordion_panels.js
  drupal_add_js(array('responsive_tabstoaccordion_panels' => array('tabstoaccordion_panel' => '#'.$tab_id)), array('type' => 'setting'));

```

## Drupal behavior in responsive\_tabstoaccordion\_panels.js

```
(function ($) {
  $.fn.extend({
    easyResponsiveTabs: function (options) {
      //the main js function which is triggered
      //...
    });

    Drupal.behaviors.responsive_tabstoaccordion_panels = {
      attach: function (context, settings) {
        $(settings.responsive_tabstoaccordion_panels.tabstoaccordion_panel).easyResponsiveTabs({
          //Set options
          type: 'default',
          //...
        });
      }
    };
})(jQuery);

```

I guess it has to see with the way I attach my function to Drupal.behaviors ?

# Answer
> 1 votes
All Drupal behaviors are called when an AJAX call is performed. This allows modules to attach its 'behaviors' to new loaded content.

There are much cases where the behavior should be attached just one time. For this cases the once function is recommended:

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

    $(settings.responsive_tabstoaccordion_panels.tabstoaccordion_panel).once('rttap', function () {
      $(this).easyResponsiveTabs({
        //Set options
        type: 'default',
        //...
      });
    }
  );

```

This way the anonymous function that calls easyResponsiveTabs is called only one time for each element. If new elements are loaded the behavior is applied.

---
Tags: ajax, javascript
---


# Question
Title: What are the steps to make a ie8-friendly bootstrap theme?
I made it by the book (I think):

* download and enable respondjs module;
* download respond.js library and install it like this: libraries/respondjs/respond.min.js & libraries/respondjs/respond.src.js;
* Download and enable Bootstrap Library module;
* Download bootstrap and installed it as a library: libraries/bootstrap/js/...
* Aggregate the CSS files;
* Emptied the caches a few times and used the "InPrivate" navigation in my IE8 browser;

My code is like that:

```
<link type="text/css" rel="stylesheet" href="http://url.com/sites/default/files/css/css_ogjvJnfni1_P_WxvXAHlUOgCs860b3ip9DNMapcIGeM.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://url.com/sites/default/files/css/css_E5INd53MC9D9hGN7fTbvA2YKmpTCORTNG-LyRZO0jWA.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://url.com/sites/default/files/css/css_pQJBTHotR_cijx-fDqH3tXIWdiIZQhUIjxOWwL8rTxU.css" media="all" />
<link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.0.2/simplex/bootstrap.min.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://url.com/sites/default/files/css/css_nFez2jKpXwmW9wMfuF-TAsfoop0107dn7vq0qbY1vio.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,600|Ubuntu:300,500&subset=latin" media="all" />
  <!-- HTML5 element support for IE6-8 -->
  <!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <script src="http://url.com/sites/all/libraries/respondjs/respond.min.js?n5tq5n"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>window.jQuery || document.write("<script src='/sites/all/modules/jquery_update/replace/jquery/1.7/jquery.min.js'>\x3C/script>")</script>
<script src="http://url.com/misc/jquery.once.js?v=1.2"></script>
<script src="http://url.com/misc/drupal.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/jquery_update/replace/ui/external/jquery.cookie.js?v=67fb34f6a866c40d0570"></script>
<script src="http://url.com/sites/all/modules/jquery_update/replace/misc/jquery.form.min.js?v=2.69"></script>
<script src="http://url.com/misc/form.js?v=7.27"></script>
<script src="http://url.com/misc/ajax.js?v=7.27"></script>
<script src="http://url.com/sites/all/modules/jquery_update/js/jquery_update.js?v=0.0.1"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<script src="http://url.com/sites/all/libraries/bootstrap/js/bootstrap.js?n5trqm"></script>
<script src="http://url.com/sites/all/libraries/colorbox/jquery.colorbox.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/colorbox/js/colorbox.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/colorbox/js/colorbox_load.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/views/js/base.js?n5trqm"></script>
<script src="http://url.com/sites/all/themes/bootstrap/js/misc/_progress.js?v=7.27"></script>
<script src="http://url.com/sites/all/modules/views/js/ajax_view.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/captcha/captcha.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/webform/js/webform.js?n5trqm"></script>
<script src="http://url.com/sites/all/modules/colorbox_node/colorbox_node.js?n5trqm"></script>
<script src="http://url.com/sites/all/themes/bootstrap/portfolio/js/scripts.js?n5trqm"></script>
<script src="http://url.com/sites/all/themes/bootstrap/js/misc/ajax.js?n5trqm"></script>
<script src="http://url.com/sites/all/themes/bootstrap/js/modules/views/js/ajax_view.js?n5trqm"></script>

```

But still, IE8 outputs something unappropriate that looks like the mobile version, give or take a few surprises, like the menu which doesn't work at all, instead of working like mobile version without the bootstrap library locally installed. What am I missing?

# Answer
OK so I finally DID IT.

I have overriden the html.tpl.php file, replacing:

```
<!-- HTML5 element support for IE6-8 -->
  <!--[if lt IE 9]>
    <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->

```

By

```
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

```

And since, IE8 is actually responding to the media queries.
> 2 votes

---
Tags: theming
---


# Question
Title: What limits the options in a Bulk Operations Menu (beyond their initial settings) regarding rule components?
I created a View Bulk Operation (VBO) that should allow an admin user to change the author of several nodes at once. Everything works fine when I am logged in as the root user. However, when I am logged in as a different kind of admin user, the VBO drop down menu is empty. I am assuming that there is a setting somewhere that is preventing the menu item(s) from appearing in the drop down list. What could be causing this to happen? I checked my permissions, but there did not seem to be a VBO related permission for the specific drop down option that I have enabled for this.

My setup uses a flag to target a user and a rules link to target an entity. the rules link triggers a 'rule component rule' which changes the author of the target node. I have a view table that renders this rule link as a column and also has a VBO column that can trigger the rule link for multiple columns.

Edit: I added a new test VBO action which calls a rule component rule (that only sets a Drupal message.) This option does not appear for the admin users either.

Edit: the admin user role has full read and write permissions for the content type.

Edit: After enabling all VBO permissions for everyone, the option is still not available.

Edit: I noticed that the Rules Link is not shown in the view for the other admin role.

Edit: After enabling the permissions for all Rule Links, the link is displayed, but still not the VBO option.

Edit: I was able to add generic VBO operations (which could be seen by the admin roles.) This problem only seems to effect VBO operations that are created by rules.

# Answer
> 1 votes
If you are adding operations using **Rules Component** then you have to set the permission.

Edit your rule component and under the settings there will be **Configure access for using this component with a permission.**, set your permission here.

---
Tags: 7, users, views
---


# Question
Title: When using Views Bulk Operations, the options for Rule Components are not shown in the VBO drop down for all users
When I am logged in as the root admin, I am able to create Rule Components (rule and rule sets) and have them appear in the View Bulk Operations (VBO) settings menu as an option for a VBO view table column. As the root admin, I can also navigate to the view's page and successfully perform the Rule Component on table entries using the VBO interface.

However, when I log in as another user (seemingly regardless of role or permission) The Rule Component options which were enabled for the VBO column are no longer available. It appears that some sort of permission is blocking them. It is not obvious which permission (or if it is a permission) is blocking the Rule Component Options so they don't appear in the VBO list.

Does anyone have experience with this problem and knows a way to get Rule Components to appear in the VBO drop down in a view for all users?

# Answer
> 2 votes
If you are adding operations using **Rules Component** then you have to set the permission.

Edit your rule component and under the settings there will be **Configure access for using this component with a permission**, set your permission here.

---
Tags: rules, users, views
---


# Question
Title: Best way to create a property of an association in Drupal 7?
I have a node Theater, and a node Movie, and a Theater can have X movies and for each movie at that specific theater there are Y showtimes. How can I set up the property "showtimes" of the association of Theater to Movie within Drupal?

# Answer
> 1 votes
Look into Field Collection:

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

You can then create:

* a content type Movie. You could have fields like a Poster image field, Title, Cast, synopsis, and then a **Showtimes** *field collection*.
* Then have a content type Theater. Which is a theater. It can have fields like geolocation, a picture of the building, a description, hours of operation, etc.
* Then your Showtimes field collection is itself a multi-value field which contains 2 fields: an entityreference to a Theater, and then a multi-value collection of times (maybe look at event module).

Using Views you should be able to list movies, Theaters and their movies, Movies at a certain time -- etc.

How to integrate this all into the Commerce module or something ... I leave this as an exercise for you.

I don't guarentee this is the best way to build the relationships between data you want. Another alternative to field collection and even the entities could be the Relation module.

**EDIT:**

If you want to easily create like a Theater that doesn't exist yet for a Movie (when making a movie entry) look at the Inline Entity Form module.

# Answer
> 0 votes
You can create a third entity type, let's call it Showtime, that would have the following fields:

* Reference to a Theater
* Reference to a Movie
* Time

That way, Movies won't be linked to Theaters directly, but via Showtime nodes.

---
Tags: entities
---


# Question
Title: Rule to send mail to the users about the percentage of their profile completed(single & multiple profiles)
I am trying to write a rule to send an email to the user if his/her one of the profiles is not completed. But I am not getting how to get the empty field's list to sent to the user. What actually i wanted to do is. List all the fields which are empty from profile (Single & multiple) and sent the list to the user, requesting to fill all the details or just percentage of profile completion . Please help me to sort out this problem.

Thanks for your time,

# Answer
How about using Content Complete or Profile Complete Percent to track profile completion. Content Complete integrates with Rules.
> 0 votes

---
Tags: rules, users
---


# Question
Title: Add a block in page content that use viewreference
I have a content type that use viewreference module to display views on page content.

So every field added with the type "`View reference`" in `manage field` section will display the corresponding view.

I want to insert a new created custom block, between those views(witch are fields in reality).

to be more clear:

> * Field 1 =\> displays view 1
> * Field 2 =\> displays view 2
> * **I want my block here**
> * Field 3 =\> displays view 3

Thanks in advance.

# Answer
> 1 votes
The Block reference module may be what you are looking for.

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


# Question
Title: Rules triggering rules - how to enforce or disable it
There are many situations in which a rule could trigger another rule. For example, If I have a rule that reacts to a Node being created, I can trigger that rule with another rule that created a node. The same should hold true for flagging nodes, but I have seen cases in which it does not. I have written 'single flag enforcement' rules that are triggered by a node being flagged, which un-flag all nodes flagged by that user, then re-flag only the triggering node. This rule should trigger itself over and over infinitely, but it does not. How does Drupal's Rules handle these situation? Is there a way to force rules to allow or disallow this form of cascading rule triggering (and potentially cause/prevent an infinite loop?)

# Answer
> 1 votes
It will not trigger recursively, Rules has inbuilt mechanism to prevent this. if you check the function rules\_element\_invoke\_component you can see this.

```
function rules_element_invoke_component($arguments, RulesPlugin $element) {
  ....
  // Handle recursion prevention.
  if ($state->isBlocked($component)) {
     return rules_log('Not evaluating @plugin %label to prevent recursion.',  $replacements, RulesLog::INFO, $component);
  }
  $state->block($component);
  ....
}

```

---
Tags: 7, rules
---


title: Modifying routing

text:
# Question
Title: Modifying routing
As in Drupal 7, I had this in mymodule\_menu() (Implementing hook\_menu()):

```
$items['admin/config/mymodule/page1'] = array(
    'title'             => 'Mymodule Page1',
    'page callback'     => 'mymodule_page1',
    'file'              => 'mymodule.admin.inc',
  );

```

So, basically in Drupal 7, whenever I navigated to `/admin/config/mymodule/page1`, it showed me the output of `mymodule_page1` function stored in `mymodule.admin.inc` file.

Modifying this to Drupal 8, I did:

```
`mymodule_menu()`:
  $items['mymodule.page1'] = array(
    'title'              => 'Mymodule Page1',
    'route_name'         => 'mymodule.page1',
  );

```

My `routing.yml` file:

```
mymodule.page1:
  path: '/admin/config/mymodule/page1'
  defaults:??
  requirements:??

```

What should be the corresponding code in `defaults` and `requirements` such that the function `mymodule_page1` gets outputted on navigating to that route?

# Answer
You can't route to a function, you need to move the content of your function to a controller class and then specify \_content: Drupal\yourmodule\Controller\SomeController::someMethod in \_defaults, and a \_permission: 'some permission' or other access check in requirements.

hook\_menu() no longer exists, instead, move your default menu links to a yourmodule.menu\_links.yml file.

Almost every core module has plenty examples for this, the necessary documentation has also been linked in the comments.
> 3 votes

# Answer
Try this:

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\EventSubscriber\ContribRoutesOverride.
 */

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class MymoduleRoutesOverride
 */
class MymoduleRoutesOverride implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[RoutingEvents::ALTER] = 'alterRoutes';
    return $events;
  }

  /**
   * Alters existing routes.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The route building event.
   */
  public function alterRoutes(RouteBuildEvent $event) {
    // Fetch the collection which can be altered.
    $collection = $event->getRouteCollection();
    // Get routes
    $routes = $collection->getIterator();

    foreach ($routes AS $route_name => $route) {
        if ($route_name == 'this_are_the_droids_youre_looking_for') {
          $route->setDefault('_content', '\Drupal\mymodule\Myresponder::page');
        }
      }
    }
  }

}

```
> 0 votes

---
Tags: 8, routes
---


# Question
Title: How can I edit the contents of the printable invoice for Ubercart order?
I need to add some text and a few extra order fields (and user profile fields, if possible) to the printable invoice that is accessed via a link like this: http://mysite.com/admin/store/orders/12345/invoice/print

I used grepWin to find all instances of the phrase "Purchasing Information:" (which is on the invoice), and that phrase was found in two files: uc-packing-slip.tpl.php and uc-order--customer.tpl.php. Unfortunately, changes to those files have no effect on the printable invoice (I tried placing the modified tpl files in my theme's templates/ folder as well as in their original location.

The only way I could get a "reaction" was to change the contents of the file uc\_order-invoice-page.tpl.php. However, its contents are merely as follows:

```
<?php

/**
 * @file
 * Default theme implementation to display a printable Ubercart invoice.
 *
 * @see template_preprocess_uc_order_invoice_page()
 */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">

<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <style type="text/css">
    .buttons {
      text-align: right;
      margin: 0 1em 1em 0;
    }
  </style>
  <style type="text/css" media="print">
    .buttons {
      display: none;
    }
  </style>
</head>
<body>
  <div class="buttons">
    <input type="button" value="<?php print t('Print invoice'); ?>" onclick="window.print();" />
  </div>

  <?php print $content; ?>
</body>
</html>

```

I tried adding some of the order fields to that file, replacing `<?php print $content; ?>`, but it did not work. I suppose if I can find out the source of the "content" that is being "printed", I would be in good shape. Can anyone help?

Thanks!

# Answer
Try Ubercart Register Invoice, this will allow you to define new email templates for invoice emails ... these same templates should also be visible/useable by your sites Theme.

> Registers invoice templates with Ubercart so they appear on and can be selected for the Ubercart "E-mail an order invoice" Rules action.
>
> Registers invoice templates with Drupal so they can be used to theme the invoice data.
>
> Provides extensive instructions and feedback on how to configure invoice templates.

See the README. You name your template: `uc-order--*.tpl.php` and it will be seen by the system. Also see the built-in help (prior and after creating a template) at http://mysite.com/admin/help#uc\_register\_invoice
> 1 votes

---
Tags: 7, theming, commerce, ubercart
---


# Question
Title: How to create structure "Author -> Book -> Quote"?
I need to create structure \[taxonomy\_term\] Author -\> \[taxonomy\_term\] Book -\> \[node\] Quote.
I already have the following structure: \[taxonomy\_term\] "Author name and Book name" -\> \[node\] "Quote". Now I want to split vocabulary "Author name and Book name" into 2 different vocabularies: "Author" and "Book" and link them to each other and to node type "Quote" to get the following hierarchy:

* Author \[taxonomy\_term\]
+ Book \[taxonomy\_term\]
        - Quote \[node\]
        - Quote \[node\]
    + Book \[taxonomy\_term\]
        - Quote \[node\]
        - Quote \[node\]

I can create this hierarchy using Entity reference, but I don't know how to achieve the following.

On node (Quote) creation user should be able to:

* choose existing "Author" term and existing "Book" term that belongs to this Author (conditional select);
* choose existing "Author" term and create new "Book" term (and link this book to "Author" term);
* create new "Author" and "Book" terms (using taxonomy autocomplete widget) and link them to each other.

Is there any way to achieve this using existing Drupal modules?

Please note: I need to use 2 different vocabularies for authors and books. I know that it would be much easier to use 1 vocabulary and parent-child hierarchy of terms, but that is not suitable in my case.

# Answer
> 1 votes
Complex business like this is hard "out of the box" with Drupal. Everyones custom logic like you've listed is different -- so community modules regularly dont let you define just deep nesting of logic.

I suspect you'll have to create some custom code to enforce relationships you want (form validation logic).

Additionally, look at Conditional Fields, Entity Inline Form and perhaps the Prepopulate module.

You can use these modules to build the dependant drop down select lists, and a button to create the Book or Author for a quote as needed -- the prepopulate module could let you pass info from a book or author on creation, to the reference entity.

You may want to look at Display Suite or Renderable Elements to tweak how the node form(s) are layed out.

As I said this isn't a solution but tools to help you build your own business-logic solution.

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


# Question
Title: storage_api The file could not be uploaded
I'm attempting to upload a a file using a custom context type that uses the storage class i defined thru the storage\_api module. For some reason the upload of an image to it is failing with "The file could not be uploaded." I have the local file system as the initial container and should propagate to an s3 bucket after the upload.

I've tried the built in Content\>Media\> add file and that works fine. i think the file lands in public:// However I want to use the storage class from the storage\_api.

I see the following in the dblog when i attempt the file upload that fails:

> Message: The upload directory storage-field-corp-image: for the file field field\_corp\_image could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.

Not sure where to go from here.

# Answer
> 1 votes
Found the issue. Turns out the Directory Path in the local container, which is the initial container, for the storage class the content type is using NEEDS to have a trailing slash. As in:

sites/default/files/storage/

instead of:

sites/default/files/storage

it's that picky. and the log does not say its the issue. it just says it had trouble accessing the field. I found it by trial and error.

I hope this helps someone.

---
Tags: 7, files
---


title: Starting with View Modes

text:
# Question
Title: Starting with View Modes
I have done a drupal theme and as of right now am only working with teaser and full view modes. Both of which I have themed in the node--product.tpl.php file I am interested in learning view modes to create different, fully customizable layouts for different pages and products.

How and where to create a new view mode for a paticular node type ie. Node--product.tpl.php before themeing. Is there a preferred module for this which doesn't limit themeing. How and where to tell a given page ie. Page--front.tpl.php which view mode of a paticular node type to use. Is there a module for this. As of now the product nodes appear under the content region.

How and where to theme the html of a view mode. Even if it's a template override. Right now I have the two view modes themed in a photo if else statement. The "if" being the teaser and the "else" being the full node. Any tutorials or videos that stand out for this?

# Answer
You should take a look at Display Suite. It makes easy work of most template modifications without having to create `.tpl.php` files. It has an easy to understand method of managing View Modes.

From the above link:

**Use custom view mode**

1. Enable DS UI module.
2. Go to Administration \> Structure \> Display Suite \> View modes (admin/structure/ds/view\_modes)
3. Click "Add a view mode"
4. Enter a label & define to which entities the mode will be made available
5. Click "Save"
6. Go to Administration \> Structure \> Display Suite (admin/structure/ds)
7. Click "Manage display" for the entity (e.g., "User") whose display you like to change
8. Choose the vertical tab "Custom display settings"
9. Enable the new view modes
10. Click "Save"
11. Flush all caches
12. Choose the custom view mode from the secondary tabs in the top of the page.
> 1 votes

# Answer
It sounds to me like you need theme suggestions for your view modes, which you can create as above, or programmatically, in a custom module:

```
  function my_view_modes_entity_info_alter(&$info) {
  $info['node']['view modes'] += array(
    'my_view_mode' => array(
      'label' => t('My View Mode'),
      'custom settings' => TRUE,
    ),
  );

```

Theme suggestions for your View Modes is explained here - D7 Template Suggestions for View Modes
> 0 votes

# Answer
I actually found the best way to create and edit new view modes is to just use entity view modes. This was I can create the view mode and create .tpl.php files for them.

The only issue that remains is how I tell a given url / page ie. page--front.tpl.php or page--taxonomy--term.tpl.php which view mode of a content type to use as well as what to limit the number of nodes per page to display
> 0 votes

---
Tags: theming
---


# Question
Title: How can i access MySQL of a local Acquia Dev website using the command line?
Can we post about Acquia DevDesktop here? i cannot figure out how to log in locally to MySQL using the command line. i posted on their forum and got no response.

Local Acquia DevDesktop sites do not put the DB config info in settings.php. instead it refers to files in an a folder name .acquia which is hidden. on my set up, a typical included looks like this.

Users/myname/.acquia/DevDesktop/DrupalSettings/loc\_mywebsite\_local.inc

i have managed to open the DB array looks like this.

```
$databases['default']['default'] = array(
 'driver' => 'mysql',
 'database' => 'mydbname',
 'username' => 'drupaluser',  //this is real default setting for username
 'password' => '',
 'host' => '127.0.0.1',
 'port' => 33067 );

```

am kind of mystified why there is no DB password?

can any tell me how to access MySQL via the command line. very aggro right now, thanks!

# Answer
> 1 votes
The easiest way to access a CLI database on any site is with drush:

```
~$ drush help sql-cli
Open a SQL command-line interface using Drupal's credentials.

Examples:
 drush sql-cli                             Open a SQL command-line interface
                                           using Drupal's credentials.
 drush sql-cli --extra=-A                  Open a SQL CLI and skip reading
                                           table information.

Options:
 --database=<key>                          The DB connection key if using
                                           multiple connections in
                                           settings.php.
 --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
 >
 --extra=<--skip-column-names>             Add custom options to the mysql
                                           command.

```

If you don't give it any options, then it will use the normal drush magic to find the settings for the current site you are in or from the site alias that you are using.

```
$ cd /path/to/your/drupal/docroot
$ drush sql-cli

```

TL;DR, if you can drush to your site, you can instantly connect to it with `drush sql-cli`

---
Tags: configuration
---


# Question
Title: Drupal site not loading any CSS/JS/Images
I've been trying to migrate my site from my local to GoDaddy server. I've done it so many times before and it's worked fine but this time I can't quite figure out what's wrong.

My steps on migrating the site:

1. Clear cache
2. Export DB
3. Create DB on server and import local DB
4. Upload Files (tar zip)
5. Change settings file

As I say, that's worked for me this whole time but now the site and content loads up fine but no styles, no images, no js. If I inspect the page it seems all of those files have a **403 forbidden error.**

I noticed that even the Drupal menu and other Drupal CMS styles aren't loading up either so maybe that could be important in finding a solution?

# Answer
Ok found the problem, it was all to do with file/folder permissions. So I did some reading and I learnt that it's recommended that folders are 755 and files are 644 (with the exception of htacces)

So I went and made those changes to files/folders and it all seems to work fine.
> 1 votes

---
Tags: migrations
---


# Question
Title: Make Exposed form view content only appears to logged in user
I have created a view and exposed that form.
I want when user click on exposed form search button it should show register or login form if user is anonymous otherwise it should show result.
After user logged in it should get back to result
drupal 7

# Answer
The easiest way - use hook\_form\_alter.

1. Add custom validate function on your exposed form
2. Use function user\_is\_logged\_in in your validate function
3. If it return false, use drupal\_goto, for redirect user to the login or register page.
> 0 votes

---
Tags: 7, views, users
---


title: Customizing recent blog posts block

text:
# Question
Title: Customizing recent blog posts block
I'm including the recent blog posts block in the sidebar of my Drupal site which pulls out the 10 most recent posts in a list with the title of the post linking to the post itself. I'd like to pull out more information, specifically the "Authored by" and "Authored on" fields.

What I have at the moment:

```
<ul class="item-list">
  <li>
    <a href="#postURL#">#post title#</a>
  </li>
</ul>

```

What I'd like to achieve:

```
<ul class="blog-list">
  <li>
    <a href="#postURL#">#post title#</a>
    <div class="author">#author#</div>
    <div class="date">#date</div>
  </li>
</ul>

```

The `blog_page_last` function in `blog.pages.inc` appears to be where the fields are being pulled out but I can't work out the additional field names (author, date) to enter.

There doesn't appear to be a `.tpl.php` file in the blog module folder and I can't find anything in `blog.module` or `blog.pages.inc` that indicates how/where the markup is set.

Thanks

# Answer
> 2 votes
The block "Recent blog posts" is in blog.module.

```
/**
 * Implements hook_block_view().
 *
 * Displays the most recent 10 blog titles.
 */
function blog_block_view($delta = '') {
  global $user;

  if (user_access('access content')) {
    $result = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('type', 'blog')
      ->condition('status', 1)
      ->orderBy('created', 'DESC')
      ->range(0, variable_get('blog_block_count', 10))
      ->addTag('node_access')
      ->execute();

    if ($node_title_list = node_title_list($result)) {
      $block['subject'] = t('Recent blog posts');
      $block['content']['blog_list'] = $node_title_list;
      $block['content']['blog_more'] = array(
        '#theme' => 'more_link',
        '#url' => 'blog',
        '#title' => t('Read the latest blog entries.'),
      );

      return $block;
    }
  }
}

```

So there is no .tpl.php to customize. Using Views module to create a block which lists out recent blog posts would be a solution for you.

Hope this help,

# Answer
> 2 votes
You just need to edit the view and add the fields that you need.

On this video it shows how to add a field, skip to 5:20 Tutorial 2 of 10: Creating and Customizing Views

# Answer
> 0 votes
You should clone the fields template:

* In your views, find Themes, you'll see something like the image:
* It's the Row style output template that you should clone.
* Once the Row style output template is cloned to your theme folder, try to print out the variables $fields (with dpm() or print\_r()) and you'll see your variables needed and you can customize the template here.

\** You can read the comments in file views-view-field.tpl.php in the views module to see all variables available in this template.

---
Tags: theming, database, nodes
---


# Question
Title: Show Block only if it's a front page and GET variable is set
I am setting up a block in Drupal 7 to "show block on specific pages" through PHP.

What I want is that if it's a Front page and there is a GET (`listed`) variable, only then it shows the block otherwise not.

Hence, the block would only be shown, if the url is `www.site.com/?listed=true`

I tried this, but it doesn't work:-

```
<?php
if ( (drupal_is_front_page()) && ( !empty($_GET['listed'])  ) {
  return true;
}
?>

```

any idea?

# Answer
You missed a closing bracket. Try this:

```
<?php
if (drupal_is_front_page() && !empty($_GET['listed'])) {
  return TRUE;
}
?>

```

or

```
<?php
if (drupal_is_front_page() && isset($_GET['listed'])) {
  return TRUE;
}
?>

```
> 1 votes

# Answer
I would suggest to look at Context module. It gives you lot of options to configure.

In your case you can add a new context and put two conditions

1. Path = `<front>`
2. Query String : `listed=true`

then add a reaction to display the block you want. Its simple.
> 1 votes

---
Tags: blocks
---


# Question
Title: Undefined variable error in node.tpl.php
I'm having an issue with an undefined variable

> Notice: Undefined variable: comment\_count in include() (line 33 of ...\themes\simplecorp\node.tpl.php).

This is what my line 33 looks like:

```
<?php print $comment_count; ?>

```

I don't understand this error, Can someone tell me how to do it?

# Answer
If you want to get rid of this notice, replace your line 33 with:

```
<?php if (isset($comment_count)) print $comment_count; ?>

```
> 0 votes

---
Tags: nodes
---


# Question
Title: Add non mandatory fields to user registration form
I can add custom fields to the user registration form, if I add the fields to the user profile: admin/config/people/accounts/fields

There is a checkbox "Show on user registraion" which is inactive:

The checkbox only gets active if I check "Mandatory field", but some of the fields must not be mandatory. Is that a bug? Is there a workaround (without using module 'Profil2') ?

I'm using Drupal Core 7.28

# Answer
I have never encountered such problem before. But since you have such problem then I think the best way is to write a hook\_form\_alter. And set the required field that you don't want as mandatory to false.

```
function mymodule_form_alter(&$form, $form_state, $form_id){
switch ($form_id)  {
    case 'registration_form_id':
                $form['field_name']['und'][0]['value']['#required'] = FALSE;
            break;
                   }
               }

```

Hope this helps.
> 1 votes

# Answer
It sounds like something is missing. Both of those options can be found on the field edit page. Both are usually available for checking. However, when you check the 'Required field' option, the 'Display on user registration form' option gets an automatic check and locked (making it virtually impossible to un-check it.) Otherwise when the 'required' option is not checked, the 'Display on user registration form' option should be completely accessible (not automatically checked and available for checking.) If this option is not available (when the 'required' option is not checked,) there may be something wrong with your Drupal Installation.
> 0 votes

---
Tags: entities, users
---


title: Drupal Solr Remaining is wrong. Why?

text:
# Question
Title: Drupal Solr Remaining is wrong. Why?
Using the Drupal Solr admin UI I indexed all queued content. However, even if everything is indexed and searchable, it indicates, as seen below, that only 2% has been indexed!

Indexed 31084 Items (934.03 MB on disk) Remaining 30597 items (2% has been sent to the server) Schema drupal-4.1-solr-3.x

The problem is that when I want to index the remaining, it starts from zero. Why is that? Is it a bug?

# Answer
Indexing is done during cron runs. When you've set up indexing, don't ask for it to be indexed again, unless you want it to start from scratch.

If you want to increase the percentage, and don't want to wait for the next scheduled cron run, run cron manually by navigating to *Home » Administration » Configuration » System » Cron* and press *Run cron*.

If you want to automate this, set up an external cron and trigger it every 10 minutes until indexing is done.

There is no setting to index everything instantly. If that is what you want to do, the answer is that this is not possible. You have to be patient. The reason there is no such setting is because that would put a too heavy load on your system. The system is designed to work the way it works for a reason.
> 0 votes

---
Tags: search
---


title: Page view mode and node settings

text:
# Question
Title: Page view mode and node settings
I have been creating new view modes with the entity view mode module as well as created template files for the new view modes.

At this point I would like to know how I tell a given page or url (ie. front page) which view mode of a particular content type to use

# Answer
You can create a view and go to **Format** section and display it as **content** then select the **view mode** you want. After that go to `admin/config/system/site-information` and change the **Default front page** to the view that you have created.
> 0 votes

---
Tags: nodes
---


# Question
Title: Drush archive-restore not restoring database nor giving error
I have a Drupal 7 site and database in an archive created via Drush. I'm trying to restore it with Drush on a Mac running MAMP.

When I tell it to restore the site it says "\[ok\]" afterwards and the site files are in their correct destination, but it doesn't create and populate the database nor does it give an error that it couldn't.

I've made sure that their is a database user with the same name and password that is in the settings.php file.

My command is: drush archive-restore /Users/abailey/Downloads/dev-sbirt-reg.20140321\_200259.tar.gz dev-sbirt-reg --destination=./dev-sbirt-reg

I added the -v tag hoping it might show me what the problem is and it outputs:

```
Mime type for                                                           [notice]
/Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz is
application/x-gzip
Executing: tar  -C /tmp/drush_tmp_1395439263_532cb69f676ea -xzf dev-sbirt-reg.20140321_200259.tar.gz
Archive restored to ./dev-sbirt-reg                                  [ok]
./dev-sbirt-reg
Command dispatch complete                                               [notice]

```

Any idea what I could be doing wrong or at least how I can figure out what I'm doing wrong? I would think at the very least I would get an error saying it can't connect to the database or something.

I'm running this from the directory I've set MAMP to use for holding site documents.

-Thanks

# Answer
> 5 votes
run the same command with `--debug` and a MYSQL error will likely be outputted to the screen.

So try:

```
drush archive-restore /Users/abailey/Downloads/dev-sbirt-reg.20140321_200259.tar.gz dev-sbirt-reg --destination=./dev-sbirt-reg --debug

```

# Answer
> 2 votes
It's definitely a long-time behaviour/bug(?) with ard/arr. I watch this behaviour since version 5.x that even if you give credentials --db-su / --db-su-pw to have rights to create new database on local lamp, the database gets created but not filled. But if you create the parallel named database before and run it with the same command it works. Since this happens under many circumstances in the last years there are no real details to provide for this to reproduce. Many cases, many servers, many years. It seems like the db creation process is interrupting the db build or the permissions are not correct when it tries to create AND to build from dump file in one step. It always needs a little kick to get finished correctly. Creating the db before, even if it suggests that this would not be needed, made it here mostly. I was thinking that I miss something or do something wrong in earlier days, but I came to the conclusion later, that this functionality is too case-sensitive to maintain it for all users and scenarios correctly, so I don't care to give the script some kicks to work.

---
Tags: drush, database, 7, backups
---


# Question
Title: How to install a specific version of drush?
How can I install the a specific version of Drush, for example 5.9.0?

# Answer
> 8 votes
The recommended way to install Drush is via composer.

`composer global require drush/drush:5.9.0`

See the Drush README for instructions on installing composer.

# Answer
> 1 votes
A specific version of Drush can be installed using PEAR:

```
 sudo apt-get install php-pear

 pear channel-discover pear.drush.org

```

And then:

```
sudo pear install drush/drush-5.9.0

```

---
Tags: drush
---


# Question
Title: Entity Reference Autocomplete module: hook_entity_info definition?
I have tested the Entity Reference Autocomplete module by defining a form field of type `entityreference` (via `hook_form`) on the `user` entity - and it works as advertised.

When I try it on my own entity an AJAX error is thrown.

My form element definition:

```
$form['name'] = array(
  '#title' => t('Ground'),
  '#type' => 'entityreference',
  '#era_entity_type' => 'ground',
  '#size' => 32,
);

```

I can't imagine the problem is my entity's base table. So, the only thing I can think of, which may be the source of the error, is my `hook_entity_info` definition:

```
/**
 * Implements hook_entity_info().
 */
function scorebook_entity_info() {
  $return = array(
    'ground' => array(
      'label' => t('Ground'),
      'controller class' => 'EntityAPIController',
      'base table' => 'scorebook_ground',
      'entity keys' => array('id' => 'grid'),
    ),
  );
  return $return;
}

```

It contains the minimum keys. Do I need to add some other keys to my definition? If anyone knows of a working example of this module working with a custom entity that may help too. Thanks.

**UPDATE:**

Here is the correct `hook_entity_info` definition for anyone who doesn't want to read everything below. You need to define an access callback function, also, to return either TRUE/FALSE accordingly.

```
'ground' => array(
  'label' => t('Ground'),
  'controller class' => 'EntityAPIController',
  'base table' => 'scorebook_ground',
  'entity keys' => array(
    'id' => 'grid',
    'label' => 'name',
  ),
  'access callback' => 'scorebook_access',
),

```

# Answer
Right. Checked your module, and your issue here is permissions.

Before returning results, the module checks whether the user has actually permission to see those results, and cuts the ones that the user is not supposed to see.

In this case, none of your entities define an 'access callback' in `hook_entity_info()`, which ultimately translates in the Entity API returning NULL when permissions are checked, which my module treats as "nothing defined, better be safe and don't return results".

So you were probably using my module in the right way, but your entities are missing the access checks.

I suggest you add at least a global check for them, like

```
      'access callback' => 'scorebook_entity_access',

```

And then implement that function.

```
function scorebook_entity_access($op, $entity, $account = NULL, $entity_type = '')
{
 // Edit to fit your requirements.
  return TRUE;
}

```

I've tested it with grounds, which are the ones defining a label, and it works all right.

Hope it helps!
> 0 votes

# Answer
I'm the module maintainer. Thanks for using the module, hope you're finding it useful. You need to add a 'label' key to your entity definition, like:

```
'entity keys' => array(
  'id' => 'grid',
  'label' => 'table-column-that-contains-the-human-name-of-entity',
),

```

With that, and after flushing caches, etc, your form should work fine. The reason is that entityreference\_autocomplete assumes that (as a best practice), every entity would have, apart of the ID, which will be normally just a number, some friendly way to identify it through a label. Therefore, you need that on your custom entity.

However, I get that not everyone might want / need that 'label' key or a column for the label in their schema, for whatever reason, and I've added support to the module to work without that. That bit is on the dev version on the module, and will be rolled out in the next stable version. So it's up to you, to define a column for the 'label' key in your schema, or download the dev version, or wait a couple days for the stable release that supports entities without the 'label' key.

Cheers!
> 0 votes

---
Tags: entities, ajax
---


# Question
Title: Share one User Table with two Drupal Sites
I have a drupal site which has thousands registered users. (I also added fields like age,dob country etc at /admin/config/people/accounts/fields)

I have another site which is hosted at the same hosting with different database.

Is there a way that i can use first site USERS table in the second site ? (user registration, forget password and login etc will be connected to first site)

Any clue?

thanks

# Answer
> 0 votes
I believe this module does what you need Domain Access

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


# Question
Title: Hook function for admin/structure/taxonomy/your_vocaburary form (Save and Reset to alphabetical)
I'm looking for a hook function to interact with the buttons "Save" and "Reset to alphabetical" on taxonomy term hierarchy. Does anyone know how to override this functionality?

# Answer
> 1 votes
with hook\_form\_FORM\_ID\_alter you can add extra function to trigger on submit.here is a simple example for you :

```
/**
 * Impelement hoo_form_FORM_ID_alter
 * @param array $form
 * @param type $form_state
 * @param type $form_id
 */
function MODULENAME_form_taxonomy_overview_terms_alter(&$form, $form_state, $form_id) {
    $form['#submit'][] = 'my_news_submit';
}

function my_news_submit($form, &$form_state) {
    if ($form_state['triggering_element']['#value'] == t('Reset to alphabetical')) { // check if reset button submited or not
        drupal_set_message('RESET CALLED');
        // ADD YOUR EXTRA WORKS HERE FOR RESET
    } else { // act on "save" button submited
        drupal_set_message('SAVED CALLED');
       // ADD YOUR EXTRA WORKS HERE FOR SUBMIT
    }
}

```

---
Tags: taxonomy-terms, hooks
---


title: Two menus can't hide the other

text:
# Question
Title: Two menus can't hide the other
I have been reconfiguring my drupal site for faster loading so i restarted from strach, the problem is i can not get rid of the Menu tab which is above the Home tab, if you look at http://beta2.computersuppportservicescs.co.uk you will see what i mean, i have went into the theme setting and untick main menu and seocndary menu and flushed the cache but it is still there.

On http://beta.computersupportservicescs.co.uk you can see i did get rid of it but i think i edit one of the php files directly and commented out the section but i cant remember which one.

# Answer
Finally worked it out again
Look for navigations.css
Edit it and look for menu-toggle
change it from display: none; to visibility: hidden; !important;
now it gone
I will update question with screenshots so others can see the problem better and know what this solution does
> 0 votes

---
Tags: 7, routes, theming
---


# Question
Title: Can the profile2 fields in registration be made obligatory?
I have a profile2 profile type in which I want to expose some fields to the user when registering.

Is there a way to make a field obligatory?

# Answer
Yes, as you do with any field make it as **Required field**.
> 0 votes

---
Tags: users
---


# Question
Title: Drupal 7 - Giving correct path to callback function in #autocomplete_path
I have this below code for autocomplete implementation but I just get AJAX error

As you can see there is not anymore details for tracking down the issue. I also checked the logs but seems like this particular error is not logged anywhere which is making me hard to debug. However I suspect (almost confirmed) there is a strong relation between menu path (`tdyards/tdyards_searchbox`), autocomplete\_path (`tdyards/tdyards_searchbox/autocomplete_callback`)and callback function name (`tdyards_searchbox_autocomplete_callback`)

Please help me to understand and correct this

Below is the complete code of my module which is sub-module of tdyards

```
function tdyards_searchbox_menu(){

  $items['tdyards/tdyards_searchbox'] = array(
    'title' => 'Autocomplete (simple)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('autocomplete_form'),
    'access arguments' => array('access user profiles'),
    );

  return $items;

}
function autocomplete_form($form, &$form_state) {

  //dpm(cities_autocomplete_callback("A"));
  $form['info'] = array(
    '#markup' => '<div>' . t("This example does a simplest possible autocomplete by username. You'll need a few users on your system for it to make sense.") . '</div>',
  );

  $form['user'] = array(
    '#type' => 'textfield',
    '#title' => t('Choose a user (or a people, depending on your usage preference)'),
    '#autocomplete_path' => 'tdyards/tdyards_searchbox/autocomplete_callback',
  );

  return $form;
}

function tdyards_searchbox_autocomplete_callback($string = "") {

  return drupal_json_output(drupal_map_assoc(array('Data','Theta','Quota','Meta')));

}

```

# Answer
> 1 votes
You've just forgotten to define the path for the autocomplete itself:

```
function tdyards_searchbox_menu(){

  $items['tdyards/tdyards_searchbox'] = array(
    'title' => 'Autocomplete (simple)',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('autocomplete_form'),
    'access arguments' => array('access user profiles'),
    );

  $items['tdyards/tdyards_searchbox/autocomplete'] = array(
    'title' => 'Autocomplete',
    'page callback' => 'tdyards_searchbox_autocomplete_callback',
    'access arguments' => array('access user profiles'),
    'type' => MENU_CALLBACK,
  );

  return $items;

}

```

Add that, clear the caches, and it should work.

# Answer
> 1 votes
Your #autocomplete\_path needs to point to a menu callback, so you'd have something like this

```
function hook_menu() {
  // autocomplete_path menu item
  $items['tdyards/tdyards_searchbox/autocomplete_callback'] = array(
    'page callback' => 'tdyards_searchbox_autocomplete_callback',
    'type' => MENU_CALLBACK,
  );
}

```

..

```
// automcomplete menu item callback function
function tdyards_searchbox_autocomplete_callback($string = "") {
  return drupal_json_output(drupal_map_assoc(array('Data','Theta','Quota','Meta')));
}

```

If you are passing in arguments you can add % wildcard to the path and set 'page arguments' =\> array(1)

---
Tags: forms, ajax, routes
---


# Question
Title: Implementing LDAP with exsisting user base
We are in the experimental stages of implementing LDAP in our Drupal 6 environment, using the LDAP integration module. LDAP is installed and working in our dev environment and now we are looking at different transition plans. We have a fairly substantial user base (couple hundred user in the DB) although realistically we have only a few dozen active users.

My first thought is to go 'cold turkey' and just drop the Users table and ask all users to just start using LDAP for authentication. I tried this in dev, and while authentication worked, some pages would not load, and I'm wondering is this because there is no longer a user associated with these pages?

So along with the specific question above I'm wondering what is the best path for a transition to LDAP on a server with an existing user base? We cannot reliably key off of a username or email to 'sync' the users. That is why I am inclined to start with a clean user table if I can.

# Answer
> 0 votes
Our goal was to 'clean up' the hundreds of old users in the system so rather than try and do some sort of merge, here is what we decided on.

First we will export the node and user tables so we can restore these if anything goes wrong.

Next we will update the node table and set uid to '0' for all nodes. uid is the author that is associated with a node. Setting the uid to 0 associates the node to the anonymous user. If you don't do this, when you drop the user table then you have an orphaned node associated to a uid that does not exist.

Next we will truncate (drop all rows) in the user table except for users 0 & 1 (anonymous and admin users).

Thats it. The disadvantage is that our users will lose there 'My Content' pages. We hope to mitigate this by sending emails in advance and telling our users to make note of pages they own. Additionally we may try and do a query that will list all pages and their users.

# Answer
> 0 votes
You could try having them create the new LDAP accounts and then merging the users. User Merge

> This module helps users to merge together duplicate accounts. It uses a hook system so other modules can do whatever they need to manage their relationships to users.

---
Tags: 6, users, authentication-authorization
---


# Question
Title: Omega 4 LiveReload auto refresh browser issue
I am on a Windows desktop developing remotely on a linux server. LiveReload does not make any changes without refreshing the browser.

The default **LiveReload settings** are as follows, do I need to change them?

* Script: URL `http://localhost:35729/livereload.js`
* Host: localhost
* Port: 35729

# Answer
> 0 votes
Yes - they need to reflect the location of the server you are looking at. SO, if you access the website with x.y.com in your web browser, that's what you need to say in that setting.

---
Tags: theming
---


title: Module/theme installation error

text:
# Question
Title: Module/theme installation error
I couldn't installed new modules/theme, when i try to install it asks for FTP request for server. Here I spell out what I did,

At first, Update manager module was not enabled. As I couldn't find "install new module" link in the module page, I enabled the update manager module. Now, I got "install new module". The problem starts here: In the module's page, it shows some warnings.

> fileowner()\[function.fileowner\]:stat failed for temporary

When I tried to install a new module (on click "install new module"), it shows warnings as follows.

I found Installing modules without FTP, but I couldn't resolve my issue.

# Answer
I don't have the write permissions for the directory `/admin/config/media/file-system`. So, I got to change the write permissions to `files` directory that appears in `/sites/default path` \- change permissions from `dwrx-rx-x` to `dwrx-wrx-wrx`

If every thing goes well, you will no longer see the warning. Now, you are ready to install the new modules/themes.
> 0 votes

---
Tags: 7, installation, files
---


# Question
Title: Parent-child node relationship without using taxonomy?
I'd like to be able to offer sub-site maintainer's the ability to create their own sections of content. I can use a hierarchical taxonomy tree to force multiple levels of content to be classified at different depths of the site. However, I'd rather not be on the hook for revising custom nested term lists for each maintainer.

Is there an easy way to allow publishers to create parent node \<-\> child node relationships without relying on taxonomy revisions?

I'm using Drupal 7 and Node Hierarchy is unfortunately not yet out of development for D7.

# Answer
> 1 votes
You can use Entity Reference module.

You create two content types: Parent and Child.

in Child content type, add an mandatory "Entity Reference" field that reference to a Parent node.

# Answer
> 0 votes
You can try using book module which comes with drupal core. you can checkout the documentation provided here.

> A book is a set of pages tied together in a hierarchical sequence, perhaps with chapters, sections, subsections, and so on. You can use books for manuals, site resource guides, Frequently Asked Questions (FAQs), or whatever you'd like.

# Answer
> 0 votes
I do something like this of a simple project management system. I have one content type - Project/Task which has a node reference that I call Parent Task that is NOT required.

I have a simple module that adds in a task level if this field is filled out and then indent this. Let me know if you want more details.

---
Tags: nodes, navigation
---


# Question
Title: How to avoid caching of fields in Entity View?
I have a few computed fields on my entity and they have dynamic values. These values cannot be cached because they change often.

I've created the necessary field formatter that uses the same approach that the comment module uses to display the uncached comment form by using the #post\_cache\_render callback.

This I found does not always work(the value is sometimes displayed in one view mode but not in another).

The other issue I have is that if the value is empty, the field label is still visible because it is not part of the formatter and therefore it is cached with the rest of the Entity View data.

So my question is: **how can I use fields with dynamic values so they won't get cached in the Entity View?**

I've also tried all hooks that allow adding or changing data in the Entity View but every single one get's cached and so I found it impossible to avoid the cache.

# Answer
> 0 votes
You can not do it per field, that would defeat the purpose. The whole entity is cached.

You can disable render caching for your entity by setting render\_cache = FALSE in your annotion and you can do it per view mode.

---
Tags: caching, 8, entities, theming
---


title: Instant search and ajax events

text:
# Question
Title: Instant search and ajax events
I want to make a search field for a form that automatically refreshes the form as you type with the answers that match the filter, like google does it.

I looked at https://api.drupal.org/api/drupal/includes!ajax.inc/group/ajax/7 and the examples module for the ajax related stuff but I can't find all the possible ajax events listed. The only ones I know of are blur, keydown and keyup.

I thought keyup would do the trick but every time I type a letter in the textfield the ajax event will disable the textfield, only to let me type another letter after the ajax callback is finished. I can't use this.

I want something like the autocomplete Drupal incorporates, it doesn't block the textfield at every typed letter, but as far as I know the native autocomplete uses a combination of ajax events.

Can someone please give me an idea of how I can accomplish such a task?

Edit: Just to be clear, I'm not looking to autocomplete suggestions, I know how to do that, I want to update a paged table of results with each letter typed.

# Answer
> 0 votes
Take a look at Drupal Instant Search, or Finder. Even if it isn't exactly what you want, it should be a good starting point.

Drupal Instant Search:

> It works as follows: The url for the instant is at /instant The user types his search word, once he finishes typing (javascript keyup) the module automatically submits the search word and returns the search results. The search results are displayed at the same page of the instant search.
>
> Instant search is also integrated with Top searches module. if Top searches module exists, the instant search auto-completes top search words.

Finder:

CHECK MODULE FIRST DUE TO THIS WARNING:

> This module is unsupported due to a security issue the maintainer didn’t fix.

---
Tags: ajax, search
---


title: Google Maps directions link icon

text:
# Question
Title: Google Maps directions link icon
I would like to know how to embed a Google map on a page, so that the the "directions" icon is showing. I had previously used the Simple Gmap module, but it doesn't provide the icon which I need.

# Answer
> 0 votes
You could create a custom region in your theme, then include a block with unaltered text that directly makes a call to the Google Maps API. This allows you the most flexibility since you work directly with the API - however this is only practical with a static location. If you are using something like a geo location module to assign destination parameters or other, you will need to adjust this.

EDIT:

in hindsight, depending on your needs, you probably don't need to create a dedicated region in your theme.

To create an unaltered text area (D7):

1) goto admin/config/content/formats

2) 'add text format'

3) Name: unaltered, Roles: Administrator ONLY! - giving others access to this has MAJOR security issues, so make sure it is admin only.

4) Save, and move it to the bottom of the list, Save Changes (this makes sure it's not the default

Get the google maps API address:

1) go here: https://developers.google.com/maps/web/

2) setup a google developer account (all google api's require this - its free).

3) goto Google Maps Embed API on that page

4) read the page, and setup your api call as you want.

5) copy the code

In admin/structure/blocks:

1) 'Add block'

2) title: \< none \> (with spaces removed) or as desired

3) Body: paste code from google API - adjust the dimensions as desired (width and height as given by the API call)

4) Text format: unaltered

5) save

6) put the block in the appropriate region

---
Tags: google-maps
---


# Question
Title: Is it wise to edit the default Google Analytics path exclusions?
The Google Analytics module has a default configuration under the "Pages" tab: "Add tracking to specific pages". The listed exceptions are:

```
admin
admin/*
batch
node/add*
node/*/*
user/*/*

```

I'm using Webform, which generates confirmation pages like `node/125/done` by default. I could of course create specified paths for each of my webform confirmation pages, but there are many on the site (over 50), so the easier route would just be to remove `node/*/*` from the GA exclusions.

What repercussions might arise from this?

# Answer
It should mean that pages such as EDIT nodes, will appear and be tracked by google analytics, which could cause false numbers. You could change the exceptions by removing the

```
node/*/*

```

but including other specifically excluded content, such as

```
node/*/edit.

```

You would want to keep an eye on google analytics to see if other pages are creaping in and then exclude them as you find them.
> 1 votes

---
Tags: 7, google-analytics
---


# Question
Title: Modify a variable before it saves to database
I have a user profile form. I'm having trouble modifying a variable before it saves to the database. I have these hooks in my template.php but the value going into my database is still the same value that was submitted in the form post.

```
function mytheme_user_profile_form_presave()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

function mytheme_preprocess_user_profile_form()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

function mytheme_user_profile_form_validate()
{
  if($form['#id'] == 'user-profile-form') {
    if($_POST)
    {
            $ec = 'fooo';
            $form['field_last_name']['und'][0]['value']['#default_value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['value']['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['value'] = $ec;
            $form['field_last_name']['und'][0]['#entity']->field_last_name['und'][0]['safe_value'] = $ec;
            form_set_value($form['field_last_name'],array('und' => array(0 => array('value' => $foo))),$form_state);

    }
  }
    return '';
}

```

what am i doing wrong?

UPDATE

Ok, I added this in my template.php

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'user-profile-form') {
    $form['#validate'][] = 'mymodule_foo_data';
  }
}

```

Then I added this to `mymodule.module`

```
function mymodule_foo_data(&$form,&$form_state)
{

        $form['field_last_name']['und'][0]['value'] = 'foo';
}

```

The function mymodule\_foo\_data gets fired on save. But the value foo doesn't get written to my database. Instead, the value that's in the $\_POST array is what gets written to the database. how do I get foo into the databasE?

# Answer
I don't think your approach is the best. You need to do the following:

1. Add a custom module.
2. Implement hook\_form\_alter in your module and and alter the user profile form. Form id: `user-profile-form`.
3. Add a validation function i. e. `$form['#validate'][] =
'my_module_custom_form_validate';`.
4. add an implementation for the function in your module and modify the form values as you wish.

Also, you don't need to use the `$_POST` variable if you are following the drupal form api.
> 0 votes

---
Tags: forms, hooks
---