# Question
Title: Simpletest: database exception during setUp
I'm writing lots and lots of test cases for different modules and have come across a rather strange error about which I'm hoping others may have more insight. In my `setUp` function override, the first thing I'm doing is `parent::setUp('my_module')`. Whenever I run a test case that part fails with a PDOException inserting (duplicate) entries into the {block} table. This is the entire stack trace:

```
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'bartik-system-main' for key 'tmd': INSERT INTO {block} (module, delta, theme, status, weight, region, pages, cache) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7), (:db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13, :db_insert_placeholder_14, :db_insert_placeholder_15), (:db_insert_placeholder_16, :db_insert_placeholder_17, :db_insert_placeholder_18, :db_insert_placeholder_19, :db_insert_placeholder_20, :db_insert_placeholder_21, :db_insert_placeholder_22, :db_insert_placeholder_23), (:db_insert_placeholder_24, :db_insert_placeholder_25, :db_insert_placeholder_26, :db_insert_placeholder_27, :db_insert_placeholder_28, :db_insert_placeholder_29, :db_insert_placeholder_30, :db_insert_placeholder_31), (:db_insert_placeholder_32, :db_insert_placeholder_33, :db_insert_placeholder_34, :db_insert_placeholder_35, :db_insert_placeholder_36, :db_insert_placeholder_37, :db_insert_placeholder_38, :db_insert_placeholder_39), (:db_insert_placeholder_40, :db_insert_placeholder_41, :db_insert_placeholder_42, :db_insert_placeholder_43, :db_insert_placeholder_44, :db_insert_placeholder_45, :db_insert_placeholder_46, :db_insert_placeholder_47), (:db_insert_placeholder_48, :db_insert_placeholder_49, :db_insert_placeholder_50, :db_insert_placeholder_51, :db_insert_placeholder_52, :db_insert_placeholder_53, :db_insert_placeholder_54, :db_insert_placeholder_55), (:db_insert_placeholder_56, :db_insert_placeholder_57, :db_insert_placeholder_58, :db_insert_placeholder_59, :db_insert_placeholder_60, :db_insert_placeholder_61, :db_insert_placeholder_62, :db_insert_placeholder_63), (:db_insert_placeholder_64, :db_insert_placeholder_65, :db_insert_placeholder_66, :db_insert_placeholder_67, :db_insert_placeholder_68, :db_insert_placeholder_69, :db_insert_placeholder_70, :db_insert_placeholder_71), (:db_insert_placeholder_72, :db_insert_placeholder_73, :db_insert_placeholder_74, :db_insert_placeholder_75, :db_insert_placeholder_76, :db_insert_placeholder_77, :db_insert_placeholder_78, :db_insert_placeholder_79), (:db_insert_placeholder_80, :db_insert_placeholder_81, :db_insert_placeholder_82, :db_insert_placeholder_83, :db_insert_placeholder_84, :db_insert_placeholder_85, :db_insert_placeholder_86, :db_insert_placeholder_87), (:db_insert_placeholder_88, :db_insert_placeholder_89, :db_insert_placeholder_90, :db_insert_placeholder_91, :db_insert_placeholder_92, :db_insert_placeholder_93, :db_insert_placeholder_94, :db_insert_placeholder_95); Array
(
[:db_insert_placeholder_0] => system
[:db_insert_placeholder_1] => main
[:db_insert_placeholder_2] => bartik
[:db_insert_placeholder_3] => 1
[:db_insert_placeholder_4] => 0
[:db_insert_placeholder_5] => content
[:db_insert_placeholder_6] =>
[:db_insert_placeholder_7] => -1
[:db_insert_placeholder_8] => search
[:db_insert_placeholder_9] => form
[:db_insert_placeholder_10] => bartik
[:db_insert_placeholder_11] => 1
[:db_insert_placeholder_12] => -1
[:db_insert_placeholder_13] => sidebar_first
[:db_insert_placeholder_14] =>
[:db_insert_placeholder_15] => -1
[:db_insert_placeholder_16] => node
[:db_insert_placeholder_17] => recent
[:db_insert_placeholder_18] => seven
[:db_insert_placeholder_19] => 1
[:db_insert_placeholder_20] => 10
[:db_insert_placeholder_21] => dashboard_main
[:db_insert_placeholder_22] =>
[:db_insert_placeholder_23] => -1
[:db_insert_placeholder_24] => user
[:db_insert_placeholder_25] => login
[:db_insert_placeholder_26] => bartik
[:db_insert_placeholder_27] => 1
[:db_insert_placeholder_28] => 0
[:db_insert_placeholder_29] => sidebar_first
[:db_insert_placeholder_30] =>
[:db_insert_placeholder_31] => -1
[:db_insert_placeholder_32] => system
[:db_insert_placeholder_33] => navigation
[:db_insert_placeholder_34] => bartik
[:db_insert_placeholder_35] => 1
[:db_insert_placeholder_36] => 0
[:db_insert_placeholder_37] => sidebar_first
[:db_insert_placeholder_38] =>
[:db_insert_placeholder_39] => -1
[:db_insert_placeholder_40] => system
[:db_insert_placeholder_41] => powered-by
[:db_insert_placeholder_42] => bartik
[:db_insert_placeholder_43] => 1
[:db_insert_placeholder_44] => 10
[:db_insert_placeholder_45] => footer
[:db_insert_placeholder_46] =>
[:db_insert_placeholder_47] => -1
[:db_insert_placeholder_48] => system
[:db_insert_placeholder_49] => help
[:db_insert_placeholder_50] => bartik
[:db_insert_placeholder_51] => 1
[:db_insert_placeholder_52] => 0
[:db_insert_placeholder_53] => help
[:db_insert_placeholder_54] =>
[:db_insert_placeholder_55] => -1
[:db_insert_placeholder_56] => system
[:db_insert_placeholder_57] => main
[:db_insert_placeholder_58] => seven
[:db_insert_placeholder_59] => 1
[:db_insert_placeholder_60] => 0
[:db_insert_placeholder_61] => content
[:db_insert_placeholder_62] =>
[:db_insert_placeholder_63] => -1
[:db_insert_placeholder_64] => system
[:db_insert_placeholder_65] => help
[:db_insert_placeholder_66] => seven
[:db_insert_placeholder_67] => 1
[:db_insert_placeholder_68] => 0
[:db_insert_placeholder_69] => help
[:db_insert_placeholder_70] =>
[:db_insert_placeholder_71] => -1
[:db_insert_placeholder_72] => user
[:db_insert_placeholder_73] => login
[:db_insert_placeholder_74] => seven
[:db_insert_placeholder_75] => 1
[:db_insert_placeholder_76] => 10
[:db_insert_placeholder_77] => content
[:db_insert_placeholder_78] =>
[:db_insert_placeholder_79] => -1
[:db_insert_placeholder_80] => user
[:db_insert_placeholder_81] => new
[:db_insert_placeholder_82] => seven
[:db_insert_placeholder_83] => 1
[:db_insert_placeholder_84] => 0
[:db_insert_placeholder_85] => dashboard_sidebar
[:db_insert_placeholder_86] =>
[:db_insert_placeholder_87] => -1
[:db_insert_placeholder_88] => search
[:db_insert_placeholder_89] => form
[:db_insert_placeholder_90] => seven
[:db_insert_placeholder_91] => 1
[:db_insert_placeholder_92] => -10
[:db_insert_placeholder_93] => dashboard_sidebar
[:db_insert_placeholder_94] =>
[:db_insert_placeholder_95] => -1
)
in standard_install() (line 201 of /Library/WebServer/Documents/drupal7/profiles/standard/standard.install).

#0 /Library/WebServer/Documents/drupal7/includes/database/database.inc(2171): PDOStatement->execute(Array)
#1 /Library/WebServer/Documents/drupal7/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)
#2 /Library/WebServer/Documents/drupal7/includes/database/mysql/query.inc(36): DatabaseConnection->query('INSERT INTO {bl...', Array, Array)
#3 /Library/WebServer/Documents/drupal7/profiles/standard/standard.install(201): InsertQuery_mysql->execute()
#4 [internal function]: standard_install()
#5 /Library/WebServer/Documents/drupal7/includes/module.inc(866): call_user_func_array('standard_instal...', Array)
#6 /Library/WebServer/Documents/drupal7/includes/module.inc(477): module_invoke('standard', 'install')
#7 /Library/WebServer/Documents/drupal7/modules/simpletest/drupal_web_test_case.php(1498): module_enable(Array, false)
#8 /Library/WebServer/Documents/drupal7/sites/all/modules/my_module/my_module.test(26): DrupalWebTestCase->setUp('my_module')
#9 /Library/WebServer/Documents/drupal7/modules/simpletest/drupal_web_test_case.php(501): MyModuleMenuBlockTestCase->setUp()
#10 /Library/WebServer/Documents/drupal7/modules/simpletest/simpletest.module(178): DrupalTestCase->run()
#11 [internal function]: _simpletest_batch_operation(Array, '118', Array)
#12 /Library/WebServer/Documents/drupal7/includes/batch.inc(284): call_user_func_array('_simpletest_bat...', Array)
#13 /Library/WebServer/Documents/drupal7/includes/batch.inc(161): _batch_process()
#14 /Library/WebServer/Documents/drupal7/includes/batch.inc(80): _batch_do()
#15 /Library/WebServer/Documents/drupal7/modules/system/system.admin.inc(2373): _batch_page()
#16 [internal function]: system_batch_page()
#17 /Library/WebServer/Documents/drupal7/includes/menu.inc(517): call_user_func_array('system_batch_pa...', Array)
#18 /Library/WebServer/Documents/drupal7/index.php(21): menu_execute_active_handler()
#19 {main}

```

The error only happens if my module is enabled, which is particularly strange because the error occurs in `DrupalWebTestCase::setUp` prior to any non-core modules being installed. Could something in my module be causing it to `setUp` more than once or loop back on itself somehow? My module implements the following hooks:

* hook\_install
* hook\_uninstall
* hook\_menu
* hook\_block\_list\_alter
* hook\_drupal\_goto\_alter
* hook\_theme
* hook\_theme\_registry\_alter

My module also uses `features` to install certain block settings with the `fe_block` module in `features_extras` and has the following dependencies:

* fe\_block
* features
* menu
* some other custom modules

The other custom modules are all thoroughly tested now and this issue does not occur if only they are installed. They include an implementation of `hook_watchdog`, `hook_element_info`, various additional API for forms, API for communication with an external web service, and account object manipulation using the latter API (primarily with `hook_user_presave`).

Has anybody got an idea what is causing my error?

# Answer
> 3 votes
To really figure out what's going on I'd have to dig deep into the `features` and `fe_block` modules, which I started to do and decided I *could* spend the next week digging and *still* not find any answers. So I tried enabling the module with the `fe_block` feature *after* setup, like so:

```
class MyModuleTestCase extends DrupalWebTestCase {

  // ...

  function setUp() {
    parent::setUp();
    // Enable my_module.module after setup is finished to avoid problems
    // with fe_block being enabled during initial installation.
    $success = module_enable(array('my_module'), TRUE);
    $this->assertTrue($success, 'Enabled modules: my_module');
    $this->resetAll();

    // ...
  }

```

Doing it this way got rid of the error, although for some reason one of the tests is taking *forever* to execute.

---
Tags: 7, features, testing
---


# Question
Title: Updating taxonomy terms with vbo and workbench
I'm using VBO to bulk update taxonomy terms on my nodes. I'm running into an issue when using workbench that VBO only updates the published revisions, and doesn't touch any of the drafts.

The problem with this is that when there are drafts, the published revision is not the newest revision. So by updating the published revision via VBO, then later publishing a draft, the taxonomy changes done with VBO do not carry forward, since they are part of an older revision.

How do I use VBO to only update the latest revision (whether this is a draft, or published content)?

# Answer
The basic principle behind using Views to display the latest revision, instead of the published revision, is to base the view on the `node_revision` table instead of the `node` table. Unfortunately you cannot change the base table of an existing view, so you'll have to rebuild the entire view showing "Content revisions" instead of "Content".

To display only the current revision, use the filter criteria "Workbench Moderation: Current" on the `node_revision` table (otherwise all revisions will be displayed). To gain access to fields on the node itself, add a Relationship of "Workbench Moderation: Node" (and then be *really* careful you don't use this relationship unless you intend to reference the published node).

To avoid a potential security bypass in your view, you should also include the filter criteria "Content access: Access" on the Node relationship.

With all that plumbing out of the way, you should now be able to edit the taxonomy term field on the most recent revision of your nodes using "Content (historical data): \[taxonomy field name\]".
> 4 votes

---
Tags: taxonomy-terms, views, workbench
---


# Question
Title: More link not displaying in content pane
I've got a Content Pane View which I display multiple times on one page (it shows a grid of Employees and takes a Department as a parameter, so I show the View 4 times on a page, sending each one a different Department parameter).

Each view on this page shows only a subset of the results (it only shows 6 Employees from each Department). I want to add a More link at the bottom of each view that links to a page that shows all results for that Department.

However, in the View configuration (Content Pane variant) I enable the More link to show, but it doesn't show.

Any ideas why the More link wouldn't show? I've definitely got enough content and I've even tried setting the configuration so that it'll show the More link even if there isn't more data.

Are More links disabled when displaying the view in a content pane?

# Answer
You can use this module to define more link for each pane

Views Panes More Link

> Adding the ability to define a custom "More Link" link for View Panes.
>
> Just go to the view pane settings and you will find a new fieldset which will allow you to define the new custom "More Link".
> 1 votes

# Answer
I had the same problem.

I solved it by creating a page view as well as an original block view.

Hope this helps
> 2 votes

---
Tags: 7, views
---


title: Understanding namespaces

text:
# Question
Title: Understanding namespaces
I am new to namespaces and I am practicing with Drupal 8. I have created a custom module and have installed the contrib, devel.

Inside my module, I have defined a block.

```
namespace Drupal\twitter_pull\Plugin\Block;
use Drupal\block\BlockBase;

/**
 * Provides a block for executing PHP code.
 *
 * @Block(
 *   id = "twitter_pull_tweets_block",
 *   admin_label = @Translation("Twitter Tweets")
 * )
 */
class TweetsBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    dpm(array('this','is','a','test'));
    return 'this is a block';
  }
}

```

It works fine. Why do I have access to the devel functions? Where in my code do I include the namespace for devel that I should have access to `dpm()`?

# Answer
Straight from the PHP Global space docs:

> Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Devel's `dpm()` is declared in 'Global space', and since there's no other `dpm()` function declared in your namespace, the 'global' one is used (no need for the preceeding `\`).
> 8 votes

---
Tags: 8
---


title: Drupal Menu Translation Not Functional

text:
# Question
Title: Drupal Menu Translation Not Functional
I am working on internationalization. My site's first language is english, with a spanish translations.

I am using Drupal 7, with Internationalization 7.x-1.10

I have everything but menu translation working. The tutorials I am reading about menu translation say to create a new menu, and before you submit your new menu go to the "Multilingual Options" section, which lets you set the translation for this menu.

Mine is missing this "Multilingual Options" setting.

Despite this I tried to translate the menu's links by viewing the links for the menu and clicking on "translate"

When I add links to the menu, and click translate on those links, I get an "access denied" exception.

Does anyone know why this might be happening?

# Answer
> 1 votes
Go to /admin/structure/menu/manage/main-menu/edit and click "Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized. "

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


title: Add an input[type="file"] label

text:
# Question
Title: Add an input[type="file"] label
i need to style the `input[type="file"]`, the only way to really style them is to add a `<label>` which has the same `for` value as the input's `id`. Drupal does not provide a correct label in single `input[type="file"]` upload and even no label in multiples `input[type="file"]` uploads. Is there any way to solve this issue?

Thanks

# Answer
The markup in Drupal is always overridable. In this case, you may either need to use a hook\_form\_alter() in a custom module to modify the label html, override the theme\_file() theme function (which is responsible for producing the markup for the file input element), or theme the form specifically. Any of these three methods should be able to meet your needs (although I'm partial to the theme\_file() approach).
> 2 votes

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


title: Select menu's hierarchy show

text:
# Question
Title: Select menu's hierarchy show
I would like it to show the hierarchy of menu's links. Testimonials and Company are under About us. How can I achieve this effect? Let me specify with an image:

# Answer
You just need to make the `About us` as `Expanded` and place the menu items `Testimonials`, `Company` under the About us. Please see the attached screenshots

Here, `About us` acts as parent item of `Testimonials` and `Company`. After that just need to add and set the `css` in `style.css` file to the menu to be displayed accordingly.

Hope it works for you!
> 0 votes

---
Tags: 7, routes
---


title: Javascript amateur's problem

text:
# Question
Title: Javascript amateur's problem
I have a function:

```
  jQuery(function($){
    $(document).ready(function(){
      $('.Testimonials').each(function(){
        var theContent = $(this).html();
        theContent = '-' + theContent;
        });
    }); // END doc ready
  }); // END function

```

Basically I wanted to add a text before an option (unable to do it by css). What am I doing wrong?

I tried like this as well:

```
$('.Testimonials').insertBefore($(this).html(), $('text'))

```

but it doesn't work either.

# Answer
It can be done this way, i don't see any reason to to use `each()` function.

```
 $(document).ready(function(){
        $('.Testimonials').text('sample text '+$(this).text());

      }); // END doc ready

```

It will add text before each element having class **Testimonials**.
> 1 votes

# Answer
```
  $(document).ready(function(){
    $('.Testimonials').each(
                    function()
                        {
                            $(this).text('- '+$(this).text());
                        }
    );
  }); // END doc ready

```

It worked!!
> 0 votes

---
Tags: javascript
---


# Question
Title: How do I show all the images in my public:/images/ folder?
So i have successfully uploaded my images into my public:/images folder now i want to output/display all of them in page how do i retrieve all the images?

here's code by the way of handling the form.

```
 function testform($form, &$form_state) {
   $form = array();
   $form['file'] = array(
      '#type' => 'file',
      '#title' => t('Image'),
      '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
     );
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
     );
 return $form;

```

}

here's the code for validating it.

```
      function testform_validate($form, &$form_state) {
         $file = file_save_upload('file', array(
        'file_validate_is_image' => array(),
        'file_validate_extensions' => array('png gif jpg jpeg'),
          ));
       if ($file) {
       if ($file = file_move($file, 'public://')) {
       $form_state['values']['file'] = $file;
    }
else {
        form_set_error('file', t('Failed to write the uploaded file the site\'s file   folder.'));
     }
  }
else {
   form_set_error('file', t('No file was uploaded.'));
}

```

}

here's the code for submitting.

```
    testform_submit($form, &$form_state) {
         $file=$form_state['values']['file'];
         unset($form_state['values']['file']);
         $file->status = FILE_STATUS_PERMANENT;
         file_save($file);
         drupal_set_message(t('The form has been submitted and the image has been saved,   filename: @filename.', array('@filename' => $file->filename)));
          }

```

# Answer
you can simply achieve that by using a module called Filebrowser.

> Allows site administrators to expose a particular file system folder and all of its subfolders with a fancy FTP-like interface to site visitors. File metainformation (via descript.ion and files.bss) is supported. The module also allows these metafiles to store special content, which can be parsed with a callback. If no callback is specified in the file, only the description will be fetched.

Using this module you can display all your exported files.

Here is the sample screenshot from project page.

Hope this post helps you.
> 1 votes

# Answer
To display all the files managed by Drupal, you can use Views.

Create a view based on files. You can add the fields related to files, i.e. Filename, rendered file, path, etc.

An export of a sample view below:

```
$view = new view();
$view->name = 'test_files';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'file_managed';
$view->human_name = 'Test Files';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: File: Rendered File */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_file';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'full';
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 0;
/* Field: File: Name */
$handler->display->display_options['fields']['filename']['id'] = 'filename';
$handler->display->display_options['fields']['filename']['table'] = 'file_managed';
$handler->display->display_options['fields']['filename']['field'] = 'filename';
$handler->display->display_options['fields']['filename']['label'] = '';
$handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
$translatables['test_files'] = array(
  t('Master'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
);

```
> 0 votes

# Answer
Firstly get fid of the images and then put it in the function below Like i did:-

```
$file_load=file_load($fid);
$url=$file_load->uri;

```

$url retrieve you image path where you have uploaded your image. Like:- public:/images/image\_name

Use this fuction to display your image. image\_style

```
$variables= array(
'style_name' => 'style_name',
'path' => $url,
'getsize' => FALSE,
'attributes' => array(
 'width' => '100',
 'height' => '100')
);

echo theme('image_style',$variables);

```

Note :-if you are using drupal theme('image\_style',$variables) function to display image.then put url like public:/images/image\_name in path given above.else you are using to display image then use below code.

Or You can also do this.

```
$file_url=file_create_url($url);
echo '<img src="'.$file_url.'"'>;

```

Hope this will help you.
> 0 votes

# Answer
You can use media module, to import all the media contents you have uploaded into your site.

1. First download and install the module.
2. Now, navigate to

Content » Media

`example.com/admin/content/media`

Here, you can add your new files to media or simply import from your directory location.

Usage:

You will need to add a field to your content type with the widget type "Media file selector", this will bring up the your media selecting window.

Demo video
> 0 votes

---
Tags: 7
---


# Question
Title: Module for animation when link is clicked
If a user clicks ANY of the links on the drupal site I am setting up, I want to show animation before the transition to another node/page.

Is there a module for this? Or would jquery work/how would I insert this into drupal.

Here's a site that I created a long time ago, but in flash template: http://jonesstuckey.com/

Click on ANY Link and you will see the animation.

I'm trying to apply all this flash/actionscript to my drupal site.Any suggestions

# Answer
> 0 votes
You can override the click event on your links, as shown here.

The code from that question is:

```
var goToURL = null;

$('a').click(function() {
   var goToURL = $(this).attr("href");
     $(el).delay(500 * i).animate({'left': '-300px'}, 1000, function() {window.location = gotoURL;});
     return false; // or e.preventDefault();
   }
});

```

# Answer
> 0 votes
I used the JQuery Loadinganimation module for a similar reason:

> JQuery loadinganimation module shows a loading layer on page loading events. These may be triggered by form submission, clicking a hyperlink or executing an AJAX call.
>
> Hyperlinks may be excluded from trigger by adding a ".noLoadingAnimation" class. Further "javascript" and "#" hyperlinks are automatically excluded. Loading and animation may be aborted by pressing "ESC". Hope it helps!

---
Tags: ajax, javascript
---


# Question
Title: Users get a new password detect forced logout
I want to create a rule:
When the user changes the new password, the system should force the user to log out and then use his new password to login.

I know the event to choose after updating an existing user account. The next part is to be added in the ELEMENTS PHP source code to detect it?

I have tried this code. It fails, the user can no longer change the new login password.

```
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id =='user_pass'){
    $form['#submit'][] = 'mytheme_password_redirect';
  }
}
/**
* Redirects user after password reset form is filled
*/
function mytheme_password_redirect(&$form, &$form_state){
  $form_state['redirect'] = 'user/lougout';
}

```

# Answer
All is correct except 'user/lougout' should be 'user/logout'.
> 2 votes

---
Tags: rules, users
---


title: Reverse node reference

text:
# Question
Title: Reverse node reference
I have 2 content types:

1. vehicles
2. engines

Several engine nodes are referenced to the single vehicle. Is there any way I can load all engines referenced to the single vehicle node if I have that vehicle node object (thus the nid as well)?

I use Node reference module.

If you need any more info, please ask. Thanks in advance!

# Answer
> 1 votes
I found a solution to this issue by performing a query on 'field\_data\_field\_vehicle\_reference' table.

For my case, the solution can be something like this:

```
function engines_of_vehicle($vehicle) {
  $nid = $vehicle->nid;

  // get all engine nids referenced to this vehicle
  $engine_nids = db_query('SELECT ref.entity_id FROM {field_data_field_vehicle_reference} ref WHERE ref.field_vehicle_reference_nid  =:nid AND ref.bundle =:bundle', array(':nid' => $nid, ':bundle' => 'engine'))->fetchCol();

  //load all engines referenced to this nid
  $engines = node_load_multiple($engine_nids);

  return $engines;
}

```

---
Tags: nodes
---


# Question
Title: Automatically show one selection of a field based on the selection of another field in a view
Sorry if this is a repeat question but I'm stuck!

Ok, I have a content type named 'Media' that is basically a bunch of videos, pictures, podcasts as well as a small write up that explains what it is. I have a view that lists these media files according to most recently added. My problem is that in this view, I display an icon according to whichever type of media it is (a camera logo for videos, and podcast logo for podcasts, etc.) but I have to choose which one it is every time I create a new 'Media' content type.

I have a field called 'icons' within this 'Media' content type, which is just a term reference with a select list widget. The taxonomy terms are the file types (video, podcast, picture) and they are linked to the correct image/logo/thumbnail whatever you want to call it.

What I want to do is have it so that when I am adding a new 'Media' content type, it will automatically figure out the correct image/logo to display once I select the type of Media it is (the 'type' is a list(float) field and also uses a select widget). I hope this makes sense!

# Answer
Take a look towards conditional fields module. Hope this will helps to solve your issue. (https://www.drupal.org/project/conditional\_fields)
> 0 votes

---
Tags: views, entities, taxonomy-terms
---


# Question
Title: Drupal 7 add ajax listener directly to node form
I'm trying to register an ajax listener to a checkbox on one of my standard node forms. I want to display certain regions of the form only in case, the field is checked. I can get the drupal ajax ecosystem to work, when I use it in a custom form, but I'm unable to make it work on my node forms.

First I hook into form\_alter to check if I'm with the node type I want to add the listener for:

```
function interceptor_form_alter(&$form, &$form_state, $form_id) {
  if($form_id === 'film_node_form') {
    interceptor_dvd_listener($form, $form_state);
  }
}

```

Then I try to attach the ajax stuff to my checkbox, which name is field\_dvd:

```
function interceptor_dvd_listener(&$form, &$form_state) {
  $form['field_dvd'] = array(
    '#title' => t('You want to display DVD informations too?'),
    '#type' => 'checkbox',
    '#ajax' => array(
      'callback' => 'interceptor_dvd_listener_callback',
      'wrapper' => 'checkboxes-div',
      'effect' => 'slide',
      'progress' => array('type' => 'none'),
    ),
  );
  return $form;
}

```

The function interceptor\_dvd\_listener\_callback is never called. I try to print some debug information there, but nothing happens...

```
function interceptor_dvd_listener_callback($form, $form_state) {
  data_service_log_object($form);
}

```

**UPDATE**

After passing $form as reference to interceptor\_dvd\_listener the ajax callback function got called like expected. I edited my code above.

# Answer
This interceptor\_dvd\_listener\_callback() should return value, in documentation:

> After form processing is complete, ajax\_form\_callback() calls the function named by #ajax\['callback'\], which returns the form element that has been updated and needs to be returned to the browser, or alternatively, an array of custom Ajax commands.

Why don't you use this: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#states

It is drupal 7 standard feature to hide or show some fields when some elements has some states.
> 1 votes

---
Tags: nodes, ajax, forms
---


title: Complex condition drupal query

text:
# Question
Title: Complex condition drupal query
I'm trying to add following mysql condition:

```
WHERE       DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'))) YEAR))
AND         DAYOFYEAR(curdate()) +7 >= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(field_birthday_value, '%y-%m-%d'))) YEAR))

```

To my db\_select $query-\>condition:

```
//Build query
$query = db_select('users', 'u');
$query->leftJoin('field_data_field_birthday', 'fb', 'u.uid = fb.entity_id');
$query->condition('THE CONDITION MUST BE ADDED HERE');
$query->fields('u', array('uid', 'name'));
$query->fields('fb', array('field_birthday_value'));
$query->range(0,5);
$users = $query->execute();

```

But i can't figure out how. Simple conditions like =, \<\> are easy. But i got no clue how to add my more complex condition.

Thx

**EDIT:** Should pay more attention to the documentation :). Ty!

```
//Build query
$query = db_select('users', 'u');
$query->leftJoin('field_data_field_birthday', 'fb', 'u.uid = fb.entity_id');
$query->where("DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'))) YEAR))");
$query->where("DAYOFYEAR(curdate()) +7 >= DAYOFYEAR(DATE_ADD(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'), INTERVAL (YEAR(NOW()) - YEAR(FROM_UNIXTIME(fb.field_birthday_value, '%y-%m-%d'))) YEAR))");
$query->fields('u', array('uid', 'name'));
$query->fields('fb', array('field_birthday_value'));
$query->range(0,5);
$users = $query->execute();

```

# Answer
> 0 votes
As The Docs for `condition` says:

> Parameters
>
> $field: The name of the field to check. If you would like to add a more complex condition involving operators or functions, use where().

So let's see `QueryConditionInterface::where`:

> # Parameters
>
> **$snippet**: A portion of a WHERE clause as a prepared statement. It must use named placeholders, not ? placeholders.
>
> **$args**: An associative array of arguments.

Should do the trick for you.

# Answer
> 0 votes
Your need use the

```
$query->where(...)

```

---
Tags: 7, database
---


# Question
Title: Generating Main content nodes based on SQL data (associated with users)
This is the first fully fledged website outside of a blog that I've ever configured, so please forgive any glaring errors I make in my logic.

My website is a ranking website: people create a profile for their website with an image, title and description, and users (who have separate 'voter' profiles) vote based on the website they visit. Voter and Websites are distinguished by a field.

All of the other profile details (image, desc ect.) are also stored in fields, and votes are recorded with an SQL table.

My website then displays the image and description of each website, in order of descending number of votes. (a ranking)

---

This is where I encounter my issue. In order to display these values properly (scrolling through pages) I need to display them as nodes. I have no idea how to generate these nodes.

# Answer
> 0 votes
From what i have understood about the problem you are facing, i believe its advised using the content type for profile as well as the votes. Here is the CCK field to use the vote field. https://www.drupal.org/project/rate It would be very easy for you to create view if all fields are part of content types.

---
Tags: 7, nodes, database
---


# Question
Title: How to display only "after now" dates (of multiple) of a date-field in a node?
I have an 'event' node-type with just a body and a date-field. For that date-field, multiple dates are allowed.

I'm listing event-nodes in a view and already use filters to only display nodes when the latest date is after 'now', so that completely outdated events do not get listed automatically. However, when I have multiple dates and at least one of those is still in the future, the node gets displayed.

In the latter case, **how can hide all dates that are in the past, and only display the ones that are still in the future**? I didn't find an option for that for the date-field in the node-type display settings.

I guess I could override my `node.tpl.php` with a custom `node--event.tpl.php`, but how do I parse out single dates of my date-field then, check if they are in the past and hide those that are? I'm totally lost when it comes to PHP and Drupal content-arrays.. I'd appreciate any help with that!

# Answer
Ok, I dived into the drupal variables with the help of the devel module and came up with a solution (*first version, see better version below the edit*):

I now parsing all dates directly from the content in my specific `node--event.tpl.php`. I then iterate through them and store all dates that are in the past in a new array. In the end, if that array contains any values and my new option is activated (differentiating between teaser and full display), I remove those past-dates from the date-field array in the content:

```
<?php
// remove dates in the past from the date-field if enabled
if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    $past_date_array = array();
    foreach($content['field_eventdate']['#items'] AS $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        array_push($past_date_array, $date_array);
      }
    }

    if (count($past_date_array) > 0) {
      $only_future_date_array = array_filter($content['field_eventdate']['#items'], function ($var) use ($past_date_array) {
        return !in_array($var, $past_date_array);
      });
      $content['field_eventdate']['#items'] = $only_future_date_array;
    }
  }
}
?>

```

Maybe there is a cleaner way of preprocessing the content (let me know), but this was the quickest I could come up with and I now have the option per-node.

**== EDIT ==**

Why make it complicated: I forgot about hiding fields, so no more array-assigning, just on-the-fly hiding of past-dates:

```
if (isset($node->field_hide_past_dates) && !empty($node->field_hide_past_dates)) {
  $option = $node->field_hide_past_dates['und'][0]['value'];
  if (($option == "teaser" && $teaser) || $option == "always") {
    $UTC = new DateTimeZone("UTC");
    $now_utc_datetime = new DateTime( "now", $UTC );
    foreach($content['field_eventdate']['#items'] AS $key =>  $date_array) {
      $to_date_utc_string = $date_array['value2'];
      $to_date_utc_datetime = date_create_from_format("Y-m-d H:i:s", $to_date_utc_string, $UTC);
      if ($to_date_utc_datetime < $now_utc_datetime) {
        hide($content['field_eventdate'][$key]);
      }
    }
  }
}

```
> 0 votes

---
Tags: theming, datetime
---


# Question
Title: Need Separator image for views ticker content?
I am using Views Ticker module for display the news in my site. It's perfectly worked for me. I want separator image for one content to another content.

# Answer
If you wants the separator between two content you have to write css for that.This is a css query.Please check the css.Have a great day.
> 1 votes

---
Tags: views, 7
---


# Question
Title: Have the '@domain.com' part of the email fixed
I'm using the email registration module so that users can log in using their email address. The users are all from the same company, so I want to know if there's a way to have the '@company.com' part of the email as fixed text, like those grayed-out input fields. Someone knows if it's possible?

EDIT: I'm hoping to have something like this.

# Answer
> 0 votes
Look at email\_registration\_user\_login\_validate(), if there is no user with such email, drupal searchs user with such name. This module as I understood creates name from email by email\_registration\_cleanup\_username(). So you can add own validate callback as the module do and pass name value throw this function. Or better to add domain suffix. Something like this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * FORM_ID need to set to 'user_login' or 'user_login_block' or some else you have.
 */
function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['name']['#element_validate'], 'mymodule_user_login_name_validate');
  $form['name']['#suffix'] = '<span class="name-email-domain">@domain.com</span>';
}
function mymodule_user_login_name_validate($form, &$form_state) {
  $values = &$form_state['values'];
  if (!isset($values['name'])) {
    return;
  }
  //$values['name'] = email_registration_cleanup_username($values['name']);
  $values['name'] .= '@domain.com';
}

```

# Answer
> 0 votes
You can achieve this using the hook\_form\_alter API. Alter the email field with something like $form\['field\_email'\]\['#default\_value'\] = '' . '@company.com';

That will always append the @company.com to each email entered.

---
Tags: 7, users, emails
---


# Question
Title: Drupal hide form items completely with states
I try to hide a whole date/image/taxonomy block on my node form dependent on a checkbox. If use the following for my title field it works perfectly. The title field is hidden/visible dependant on the test\_box checked value.

```
function interceptor_box_listener(&$form, &$form_state) {
  $form['test_box'] = array(
    '#title' => t('You want to choose a title?'),
    '#type' => 'checkbox',
  );
  $states_array = array(
    'visible' => array(
      'input[name="test_box"]' => array('checked' => TRUE),
    ),
  );
  $form['title']['#states'] = $states_array;
  return $form;
}

```

The point is that I have more complex fields I need to toggle and I'm not able to address them correctly. If I try to adress the following fielditem, nothing happens at all.

```
<div id="edit-field-plakat" class="field-type-image field-name-field-plakat field-widget-image-image form-wrapper">
<div id="edit-field-plakat-und-0-ajax-wrapper">
<div class="form-item form-type-managed-file form-item-field-plakat-und-0">
<label for="edit-field-plakat-und-0">Plakat</label>
<div class="image-widget form-managed-file clearfix"><input type="hidden" value="109" name="field_plakat[und][0][fid]">
</div></div></div></div></div>

```

It tried the following:

```
$form['field_plakat[und][0][fid]']['#states'] = $states_array;

```

Is there any possibility to just pass an id to drupal but stay with the states system? Of course I'd be able to use plain javascript here, but I really like to stay strictly on the module side.

# Answer
Find this field in `$form` array and set states currently to it. I'm not sure, but maybe it is in `$form['field_plakat'][LANGUAGE_NONE][0][$fid]`? It must be somewhere in this renderable `$form` array.
> 1 votes

---
Tags: javascript
---


# Question
Title: Fatal Error when trying to log in DRUPAL
My `Drupal 7` website is throwing `500 internal server error`, when I try to log in as Admin.

I checked the apache error log it throws below error

```
 PHP Fatal error:  require_once(): Failed opening required '/*****/******/sites/all/modules/context/context_ui/export_ui/context.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /******/******/sites/all/modules/ctools/includes/plugins.inc on line 480, referer: http://*******/user

```

What could be the problem ?

Thanks

# Answer
> 0 votes
Can you confirm which version of php you are using? I just realized that the magic php constant "**DIR**" (which I first used here in beta4) may only work in php versions 5.3 or greater, so I'm guessing you have a version that's below v5.3.

According to the Drupal requirements, the PHP requirement for Drupal 7 is "PHP 5.2.5 or higher (5.3 recommended)", So I may have made a mistake by introducing a construct that's not compatible with some php versions that Drupal 7 still supports. I'll need to fix this, but either way if you can confirm your php version that would be very helpfu

---
Tags: 7, installation
---


title: Removing parts of a content type

text:
# Question
Title: Removing parts of a content type
so, I was trying to get rid of the comment title and there is a lot to read about that on the net, but I still had my issues getting it right, so I came up with this, but I believe there should be a better way. What is the best way of doing this:

```
function theme_preprocess_comment(&$vars) {
// Remove the comment title
  $vars['title'] = NULL;
}

```

# Answer
You can set your content type to not use comment title by unchecking "Allow comment title" under the settings for your content type.

Then I would copy comment.tpl.php to your theme and customize the output there instead of just unsetting the title value in theme\_preprocess\_comment().
> 2 votes

# Answer
If you really want to do this by custom coding. Then create a custom Module. The following code will do this.

function your\_modulename\_form\_comment\_form\_alter(&$form, &$form\_state, &$form\_id) { //This disables title field.

$form\['subject'\]\['#access'\] = FALSE; return $form;

}

Hope this helps you.
> 0 votes

---
Tags: theming
---


# Question
Title: Autocomplete on multiple fields Entity Reference
This is my case:

I have a content type `advertisement` with some fields and an **entity reference** of content type `product`. The **widget type** of the entity reference is **autocomplete**.

These are my settings of the autocomplete field:

When I create an `advertisement` I can type in the name of the `product`. But the product has also other fields like **cnk**. How can I make sure the autocomplete will search on the name **AND** the cnk?

# Answer
You can use the functionality *Views: Filter by an entity reference view* that comes with the Entity Reference module to search on more fields.

To use this functionality you need to change Entity selection mode to *Views: Filter by an entity reference view* instead of *Simple (with optional filter by bundle)* on the settings for your entity reference field.

First off you need to setup a View that lists your product nodes. Then add a display of the type Entity Reference.

You can exclude the field cnk from display but **add it as a search field to the settings** for the Format "Entity Reference List". If you don't exclude the field cnk from display it will show content from the field in the autocomplete widget.

No go back to the entity reference field and choose the view you just created under the settings for *Views: Filter by an entity reference view*.
> 6 votes

# Answer
Autocomplete will search against the referenced entity label (e.g. title). If you're set on using auto-complete then you may have to write your own custom module to provide alternative auto-complete behavior.

If you simply want to make it easier to search/select a referenced entity then I'd recommend giving the Entity Reference View Widget module a try.
> 2 votes

---
Tags: entities, nodes, ajax
---


# Question
Title: Drupal 7 Remove field suffix from search index
On my Drupal 7 installation I have many different custom fields with different suffixes. Drupal inserts the suffixes into the search\_index table which I need to avoid. I could change the output, so that the suffixes are hardcoded on the template side and only shown if the specific fields are printed, but I don't like this solution.

Is there any other way to tell Drupal which fields to add to search\_index and which fields to skip? Any hook I could use?

I'm not sure if I really want to use the Search API Module...

# Answer
> 1 votes
You can exclude fields from being added to the search index under the settings for you content type.

Go to the settings for you content type and Manage display. Click on the view mode Search index and drag the fields you don't want to index to Hidden.

---
Tags: search
---


# Question
Title: How to open product detail when user click on product image?
I am new in Drupal and I am working on one commerce website using drupal commerce module.

The problem is arise in my website is--\>

I am used views for display products with product image,title, price etc fields.

But I want to know that when user click on product image the new page will open and in that page display 3 related images of that product with detail information.

I want to give link for product image to open that clicked image product with detail.

Please help me to solved this problem...!

# Answer
In view add "nid" fields before image field and make exclude from display.

Click on image field. Go to "Rewrite Results" section.Check "output this field as link" .In the "link path" put the 'nid'. It will take you the details page of product. ...

You can also create tpl file for product content type details page. Enjoy
> 0 votes

---
Tags: commerce
---


# Question
Title: Attach a node to a menu link OR attach custom fields to menu links?
My client would like to add content to the top-level links in the main menu, in order to have "Featured" content that is displayed in the drop-down menu. They must be able to choose which piece of content will be shown, and which menu link it will be associated with. I figure I have two options:

1) Creating a "Featured in Menu" Content Type and adding a drop-down menu of top-level menu links as a field. The problem with this is I am not sure how to output a custom field that will list top-level main menu links. There does not seem to be a module currently that will achieve this, so I guess I would have to do it from scratch.

2) Adding custom fields to the main menu links themselves (image, title, node reference). I tried using the Power Menu module to achieve this, however every version of the module I tried gave SQL errors and broke the Edit Menu page. I'm hesitant to debug and pursue a fix for that module if it could end up being unstable.

I'm not sure which solution would be preferable but either way I'm stuck! I would very much appreciate some help on how to achieve either one of these solutions. (Or if I'm totally over-thinking this and there's a much easier way to achieve this, by all means please let me know.) For the record, I'm using Drupal 7.

Thanks!

# Answer
Look into like Menu Views or GigaMenu or MegaMenu ... there are a few solutions that let you place a view in a menu.

Then you can either add a field to a content type such as, "include in featured menu" of type boolean, that you use as a Filter in your View. Or, re-use the "promote to frontpage" re-labeled to fit your needs on a specific content type.
> 1 votes

# Answer
I have personally used and like Menu Attach Block

> Menu Attach Block allows you to attach blocks to standard core Drupal menu items. This is especially useful for creating complex dropdown menus and mega menus.
>
> Any block can be used, including blocks generated by other modules. Blocks generated by Views are particularly good candidates for embedding.
>
> You can choose to replace menu items with Blocks, or keep the menu items and have the block available by clicking a link which is inserted beside the menu item.
>
> You can see this module in use at Syfy.de (click the drop-down arrows in the main menu).
> 1 votes

---
Tags: 7, entities, routes, nodes, navigation
---


# Question
Title: Bootstrap subtheme does not recognize stylesheets
I'm trying to use a custom (LESS) build of Bootstrap in my Drupal project. I have a subtheme in the proper folder and have compiled a style.css file. However, Drupal does not recognize this file. So far I have

* Edited the .info file to switch of the CDN and switch on the local .js files
* Cleared the cache
* Switched off the aggregation of CSS
* Restarted the server
* Added a foo.css to the .info file for testing

Nothing of this works. The subtheme does not recognize my custom css files.

What could have gone wrong here?

# Answer
> 0 votes
I forgot to turn the subtheme on in the theme settings.

---
Tags: theming
---


# Question
Title: How do you write a drush alias for a local Vagrant box?
I'm trying to write a simple drush alias to connect to a Drupal site running on a local Vagrant instance.

I have the following in a file called `~/.drush/l.aliases.drushrc.php`:

```
$aliases['o'] = array(
  'parent' => 'l',
  'root' => '/vagrant/docroot',
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => '-p 2222 -i ~/.vagrant.d/insecure_private_key',
  'uri' => '127.0.0.1:8080',
);

```

The alias is found. `drush sa` returns:

```
l
l.o

```

However, when I `drush @l.o status` it doesn't connect to the remote host:

```
PHP executable        :  /usr/local/bin/php
PHP configuration     :  /usr/local/etc/php/5.3/php.ini
PHP OS                :  Darwin
Drush version         :  6.1.0
Drush configuration   :

```

I have confirmed that this command successfully connects to vagrant:

```
ssh vagrant@127.0.0.1 -p 2222 -i ~/.vagrant.d/insecure_private_key

```

Debugging output doesn't show an SSH command so far as I can tell:

```
SIG-106:ilob justin$ drush --debug @l.o status
Bootstrap to phase 0. [0 sec, 3.78 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 3.98 MB] [bootstrap]
Loaded alias @l.o from file /Users/justin/.drush/l.aliases.drushrc.php [0.01 sec, 3.99 MB]                                                                        [notice]
Cache MISS cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4 MB]                                                                             [debug]
Cache SET cid: 6.1.0-commandfiles-0-807b6772846e18b2741e8d5b7119b4cc [0.01 sec, 4.02 MB]                                                                           [debug]
Bootstrap to phase 0. [0.05 sec, 9.56 MB]                                                                                [bootstrap]
Found command: core-status (commandfile=core) [0.08 sec, 9.56 MB]                                                                                [bootstrap]
Loading outputformat engine. [0.13 sec, 9.6 MB]                                                                                [notice]
Calling hook drush_core_status [0.14 sec, 9.65 MB]                                                                                [debug]
Returned from hook drush_core_status [0.14 sec, 9.66 MB]

```

I know I must be doing something stupid but I just can't see it.

# Answer
I was able to use drush alias with following configuration:

Let's assume two things:

* vagrant box has some sort of static ip (can be private, for example: 192.168.56.101)
* IP of vagrant is available in symbolic form (for example, we have single line in /etc/hosts with ip and hostname). (for example: test.site.local).

Step 1: We need to copy settings, generated by vagrant ssh-config command into $HOME/.ssh/config

```
Host test.site.local
    IdentitiesOnly yes
    UserKnownHostsFile /dev/null
    StrictHostKeyChecking no
    PasswordAuthentication no
    IdentityFile [path to vagrant private insecure key]

```

Step 2: With such configuration, my alias was in following form:

```
$aliases['example'] = array(
   'root' => '/var/www',
   'uri' => 'test.site.local',
   'remote-host' => 'test.site.local',
   'remote-user' => 'vagrant',
   'ssh-options' => "-i path_to_insecure_private_key"
);

```
> 6 votes

# Answer
The character `~` is expanded by Bash. Drush does not provide this same service, so you should replace `~` with the path to your home directory.

So, for example:

```
$home = drush_server_home();
$aliases['o'] = array(
  'parent' => 'l',
  'root' => '/vagrant/docroot',
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => "-p 2222 -i $home/.vagrant.d/insecure_private_key",
  'uri' => '127.0.0.1:8080',
);

```

That's untested, but it should work, baring any simple typo's.

**UPDATE:**

I think I see a Drush bug here. Drush is going to assume that 127.0.0.1 is going back to the local machine, and will decide not to use ssh w/out even considering the implications of the -p in ssh-options. This is going to require a patch to Drush to fix. `function drush_is_local_host()` in environment.inc.

**ISSUE ON GITHUB:**

Please put any comments regarding potential fixes in the Github issue, Drush backend invoke does not consider port number when deciding local vs remote.
> 3 votes

# Answer
I got around this by simply doing a check for Drush in my local settings.php file via `php_sapi_name() == 'cli'` and updating my database and memcache connection strings to Vagrant, like this:

```
if (php_sapi_name() == 'cli') {
  $databases['default']['default']['port'] = '3307';

  $conf['memcache_servers'] = array(
    '127.0.0.1:11212' => 'default',
  );
}

```
> 3 votes

---
Tags: drush, virtual-machine, ssh
---


# Question
Title: Can I use view to filter by fields in referenced node?
I have 2 node types: Project and Designer. I have a third node type Contribute with a body that explain the contribute and a field node reference with maximum 2 values that "links" the designer to the project that he contribute. I can reuse Contribute to link 2 Projects, or 2 Designers, but I can't do this:

In the Designer page I want 2 blocks: one containing the Contribute nodes that link that designer with some Project; one containing the Contribute nodes that link that designer to other Designer s.

With Views I can only create one single block listing all Contribute nodes that links the current node (from URL) to another node, I want to filter from the type or the tags of the nodes referenced in the field.

Thank you.

# Answer
You want to look at adding Relationship(s) to your View.

You also likely want to look at Views Field View:

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

Or Views Field:

> Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.
>
> Features
>
> * Author chooses a view and display from a list.
> * View arguments are supplied through tokens.
> * Administrators may restrict which views may be assigned.
> * Administrators may supply a common value that will be used for all entities in a content type.

Using either of these modules you can figure out your relationships for the views you want and for instance using ViewsField you can add a View to the Designer Content Type with 2 new Views: Contributed Project Nodes views, and a Similiar or Linked Designers View. You can pass the Designers `uid` as a token to filter these views.
> 2 votes

---
Tags: views, nodes
---


title: Mapping a UID on custom module content

text:
# Question
Title: Mapping a UID on custom module content
Dear Drupal Enthusiasts,

I was hoping that one of you may be able to solve a problem I'm having with the Feeds module and its unique identifiers.

Basically, I would like to be able to target a field with a unique identifier like you can do with any ordinarily created content-type. However, I want to do this on a custom module (which has its own form of unique identification).

In other words, I have a field in my custom module that is unique, but Drupal does not know that this field is unique. How do I both tell Drupal that this custom module contains a unique field and identify that field as unique so that I can update content rather than delete it and replace it every time I wish to import data?

Any guidance would be most helpful!

Thanks!

# Answer
So I was able to resolve this problem with a simple fix - though it took a good deal of time to find it, so I figured I'd post it here to inform others in the event they have a similar difficulty.

I simply used the `Field validation` module which gives the user the capability of selecting his/her own UID for any field instance...quite straightforward.

Hope that helps!
> 0 votes

---
Tags: feeds
---


# Question
Title: Is the Search API module able to do range facets on numeric values?
I'm using Drupal Commerce, Search API, and Facets API; I'd like to put the product prices as a facet. Configuring my search API index, I managed to get this facet, but the Search API module doesn't seem capable of handling price ranges facets. This is how the facet looks like.

* 1230,23
* 340,21
* ...

I'd like it to be like the following.

* From 10 to 100
* From 100 to 200
* ...

It seems that there is existing code for handling ranges, but not decimal ranges.

Did I miss something?

# Answer
> 3 votes
commerce\_search\_api sounds like exactly like what you're looking for. Be aware of the commerce \>= 1.4 dependency as of this writing.

The module includes a product display index (configurable at admin/config/search/search\_api/index/product\_display):

> * Auto-generated search index that includes all product display node types\* and related product data.
> * Auto-generated facets for all node type categories and product attributes.

I've used the price facet filters, with and without the search\_api\_ranges widget, with great success.

# Answer
> 2 votes
This was asked long time ago, but as I have just landed here, let me add another answer - it seems that Facet API Ranges is the module you are looking for:

What it could give you:

Configuration options:

---
Tags: commerce, search
---


title: Drupal 7 computed field value in view

text:
# Question
Title: Drupal 7 computed field value in view
I'm really stuck displaying content type's computed field in view. Computed field value calculated properly and stored in database (value is a generated HTML code), but in view I get HTML just printed out as text. Looking through the page source code I found that HTML tags are encoded and looks like that `<a href="LINK_HERE">` So I'm wondering how to display custom field's HTML in view (seems to me that was a some custom module for this purpose?)?

# Answer
**Solved** Seems that I should to check the "Formatter" dropdown menu, it has a "Unsinitized" which perfectly works in my case.
> 0 votes

# Answer
In Views, try this:

* add the field as normal, exclude from display
* create a new field, Global:Custom Text
* add the field name as a Replacement Pattern

It's likely that for security reasons it is psuedo-sanitizing the html. Global: Custom Text should display it as is, but I haven't tried it under these circumstances, so it may not.
> 0 votes

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


title: Change <ul> class on one specific menu?

text:
# Question
Title: Change <ul> class on one specific menu?
I'd like to change the class from "menu" on one specific menu I have showing up as a block on about 3 pages in a Drupal 7 site. I've been researching but can't seem to figure out the best way to go about doing this.

# Answer
> 3 votes
You can do this with theme\_menu\_tree() hook in your theme's template.php file. Or with a more specific version of `theme_mene_tree()` hook like `MYTHEME_menu_tree__MYMENU()`.

```
function MYTHEME_menu_tree__MYMENU(&$variables) {
    return '<ul class="nav newclass">' . $variables['tree'] . '</ul>';
}

```

See more here https://gist.github.com/gagarine/3201854

**UPDATE:**

if menu machine name have hyphne like main-menu then change hyphen to underscore, like `MYTHEME_menu_tree__main_menu()`

# Answer
> 0 votes
If you need add class to your primary or secondary tabs you need change theme callback of `theme_menu_local_tasks()`. Use `hook_registry_alter()` to change callback. If you need change menu links, drupal has `theme_links()` which has `$variables['attributes']` where you can set class for ul. For this solution you need create function `mymodule_preprocess_links()` and set `$variables['attributes'] = array('class' => array('my-class'))`.

P.S. look at `theme_links()` or`theme_menu_local_tasks()` function to implement some solution.

---
Tags: routes
---


title: Load just one field from node

text:
# Question
Title: Load just one field from node
I have x nodes with field named "thefield". My script is checking "thefield" and if he does so the right value is updated.

How can i get from node just one field for check and didnt load full entity (node\_load)?

# Answer
> 1 votes
I would use a db\_query to find all nodes that that field appears on and then update them with a node\_load here is the code:

```
$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
    $node = node_load($record->entity_id);
    // update node
}

```

# Answer
> 0 votes
You can either do it programmatically or using views.

Using Views : Create a view page and under the fields section add the following fields:

Node id and the specific field you would like to update.

Update the filter condition as follows: Node type = 'YOUR NODE TYPE' AND "Your required field" = NOT NULL

The output of this view will be the node ids of all those node which will be having a values assigned to the specific field.

If this didn't helped you, please let me know, will solve it in a different way

Thanks

# Answer
> 0 votes
```
$nid = 1;
$thefield = db_select('field_data_field_thefield', 'f');
  ->fields('f',array('entity_id'))
  ->condition('f.entity_id', $nid, '=');
  ->execute()
  ->fetchField();

if($thefield){
  Do Something...
}

```

You could use a db\_query instead of db\_select to make it even quicker

# Answer
> 0 votes
If you want to update any field in node , then better to use `node_load()` function. Because if you use any custom **select** or **update** query then

* first thing you need to update it in all the tables (main and revision tables).
* Second thing, drupal events will not trigger that is attached with updation.

If you still want to do it manually by `db_select()` and `db_query()`

Hope it will help!

# Answer
> 0 votes
The field API allows you to load/attach just one field in a list of entities with `field_attach_load()`. This approach is field storage agnostic, invokes field-level hooks, and reads from the field cache if possible.

---
Tags: nodes
---


# Question
Title: How to get url alias of a link, when rewriting field output in Views
I have an image field in Views, for which I must use "Rewrite output" option. The output of the image field is this:

```
<a href="/taxonomy/term/[tid]" title="Album "[name]"" class="vignette-wrapper">
[field_image]<span class="vignette"></span></a>

```

So, it contains a link to taxonomy term. But I would like this link to be the custom url for this taxonomy term, instead of raw Drupal path. My Pathauto pattern for taxonomy term is:

```
[term:vocabulary]/[term:parents:join-path]/[term:name]

```

But in Views, the `[term:parents:join-path]` token is not visible on the list of Replacement Patterns.

How to achieve this?

# Answer
The Global Redirects module (drupal.org/project/globalredirect) would be one potential solution! It will automatically redirect all links on your site that are like that globally.
> 1 votes

# Answer
I put

```
function [theme-name]_preprocess_views_view_field__[view-name]__tid(&$vars) {
  $vars['output'] = drupal_get_path_alias('taxonomy/term/' . $vars['output']);
}

```

in `template.php` after adding the 'TID' field to the View. This also needs a copy of views-view-field.tpl.php, renamed according to the Theme Information provided by the View, in the theme folder in order to invoke the pre-process hook.
> 0 votes

---
Tags: 7, views, tokens, path-aliases
---


title: Webform Module and Elements Module

text:
# Question
Title: Webform Module and Elements Module
I have a hook that i wrote to include the elements fields (i.e, telfield) in a webform. The field doesnt take on the same css as the rest of the fields which means I probably need to add a style to the CSS for it. However, I'm trying to figure out a way to implement this globally so that I will be accepted as a regular form component since I have over 40 different themes that this will be applying to.

This is an attempt to avoid having to go into each them and adding the style.

Thanks,

# Answer
> 0 votes
there is no way to add a stylesheet and be global for all the themes you have inside sites/all/themes

The unic way is that all your different 40 themes were subthemes of one parent theme then you can have your styles in the parent theme and all your subthemes will inherit the styles of the parent, there is no other way...

---
Tags: webforms, forms
---


# Question
Title: Shipping calculator for shipping service
In my Product Add page, Seller can select Shipping service. I am using FedEx, USPS and UPS for my website. Here there would be a link for shipping cost calculation. By clicking on that link, it would open up a Shipping Calculator window from where Seller can add product dimensions and weight and select from available shipping services. By clicking on submit button, window would be closed and Selected Shipping Service and it's cost would be added into Textbox.

Is there any Shipping Cost calculator available in Drupal?

# Answer
I think you're looking for a module that do a very specific behavior, some shipping providers don't offer this option and if they do, **maybe** the drupal module doesn't implement it yet.

The basics of calculating shipping is knowing what the item measures and weights, for that you've got the modules Physical field and Commerce Physical product. With that you've got a field for dimensions and another one for weight, that would help you communicate with your shipping providers to get a quote before the user goes on with the checkout.

* Commerce Fedex module seems to offer integration with the physical modules mentioned above.
* Commerce USPS also claims support for physical modules in the project description page
* Commerce UPS also seems to provide physical module support.

Once you've got everything set up and your products have the information needed, you can start filtering out the shipping methods offered for every context and user. Depending on the visual requirement and behaviors you'll need to customize it further, but these collection of modules should provide a basic shipping calculation service.
> 1 votes

---
Tags: commerce
---


title: Sorting with Voting API

text:
# Question
Title: Sorting with Voting API
I know a lot has been written on this issue already but I found no clear answer.

Here it is:

With the Voting API and another module such as Fivestars or Rate, how do you rank the results within results?

Let me give an example: With views, I can have a proper display of all the nodes that have received, say, 5 stars followed by all those that received 4 stars and so on. So the nodes are grouped properly.

But to rank the nodes within each group (i.e.: The 5 star node that have received the most number of votes being displayed first followed by the 5 star node that come in second position, etc. How does one set that in views?

At the present, I have no sorting within each star group so a node that has received one 5 star vote comes before one that has received three 5 stars, followed by one with that received two (1-3-2.)

My setting are:

Relationships: Content: Vote results -- Value type: No filtering -- Aggregation function: Average vote. Sort criteria: Vote results: Value (desc.)

It looks like I need an additional sorting mechanism but i can't find it.

Any one has an answer for this? I am not a programmer but a site builder. :)

Thank you. :)

# Answer
Never mind I think I finally found the solution:

In addition to the settings above, I added a second relationships: Content: Vote results. It's the same relationship as before but instead of "Average vote" in the Aggregate function, I have "Number of votes." So as to avoid confusion, I also changed the identifier to: "Vote results (rank in group)"

So, I have two relationships, almost identical except for the Aggregate functions.

Then, in addition to the sort criteria described above, I added the same criteria again except that I chose the second relationship ("Vote results (rank in group)") instead. Order is also descending.

And that gave me the desired results: Nodes are properly ranked within the groups.

You can test this by enabling **Text to display under the stars: Both user's and average vote** in the rating field.

:)

Hope that helps.
> 0 votes

---
Tags: views, rating
---


# Question
Title: How to turn off panels in-place edit bar
I know this maybe a silly question but how do you hide panels in-place editor bar?(The bar that has layout adjustment buttons.) I found a post that said there's a on/off setting on general settings page that I can use to hide it but I couldn't find that option. I need to hide it because that toolbar is covering Theme developer checkbox. I can't disable the module either because it's in used. Any suggestion?

# Answer
Click on the "Panelizer" tab of your content type then click on "Full page override" (or whatever view mode that is panelized" and then under settings you will see:

```
Standard
In-Place Editor

```

Click the standard.

The In-Place Editor setting is what is creating the tool bar at the bottom.
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Tag/Label an image in an image field with Taxonomy terms?
Is it possible to tag images as you upload them on to a node in a multiple values image field?

```
Image a node with a set of 3 images:
image_1.jpg (tagged with: red)
image_2.jpg (tagged with: blue)
image_3.jpg (tagged with: red)

And another node with 2 images:
image_A.jpg (tagged with: red)
image_B.jpg (tagged with: green)

```

What I'm aiming to do is to be able to pull all the images tagged with the tag "red" in a view.

```
RED IMAGES
image_1.jpg (tagged with: red)
image_3.jpg (tagged with: red)
image_A.jpg (tagged with: red)

```

Is there a module that performs this? Images have to be uploaded into the image fields. They cant be uploaded as nodes.

# Answer
> 0 votes
I would suggest using a field collection for this. This creates a collection of fields that you can add and do exactly what you are looking to do.

---
Tags: taxonomy-terms, files, media
---


# Question
Title: How do you add a prefix to an existing drupal database for single site use?
I have a drupal 7 site running on a webserver, it is currently using a database that was created with out a prefix.

I am attempting to restore that database to a new drupal instance from a shared hosting provider. I am using the Backup and Restore Module to move the database. One thing I have no apparent control of is that their "quick install script" creates a new drupal database with a "drupal\_" prefix.

Do I need to convert my existing database to have that prefix, because as it seems now my migrated changes are not even being read since it probably has both sites data sitting side by side, and the database information I want to be reading entries from don't have the prefix? Is that reasoning correct? If so how do I convert my Drupal database to the same one but now with the necessary prefix applied throughout?

# Answer
If you have phpMyAdmin the simplest way is to:

* go to the "Structure" tab (where there is the list of tables).
* select all the tables (with the "Check All" checkbox at the end of the list)
* in the dropdown list close to the "Check All" select the action "Add table prefix" (or "Replace table prefix" if that is the case)
* insert the prefix, press the button and let it do all the work.

After that remember to specify the prefix in the site\default\settings.php

```
array (
  'database' => 'sample_drupal_db',
  'username' => 'sample_drupal_usr',
  'password' => 'sample_drupal_pwd',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => 'prefix_', // <<== prefix here
),

```
> 3 votes

# Answer
Your reasoning sounds correct to me. You could try to edit your database dump, adding the prefix to all table names, and run the import again. This will surely work but it's also easy to make a mistake, so you may have some trial-and-error before you succeed.

Another option would be to go into the new database with a tool like phpMyAdmin, drop the prefixed tables and alter the non-prefixed ones adding the prefix.

A third method (which may or may not collide with the automatic installer you used) is to edit the settings.php and remove the prefix from the database array. While this is probably the fastest solution for now, I'm not sure if it will last in the ling run, for instance when the automatic installer does an upgrade.
> 1 votes

# Answer
If it is just the database with the 'drupal\_' prefix, you do not need to create a table prefix.

The database dump created by the Backup and Restore module does not include any database definition.

If you need it, you can extract the mysqldump file and add the following to the top of the file:

```
CREATE DATABASE IF NOT EXISTS 'drupal_mydatabase';
USE 'drupal_mydatabase';

```

Otherwise, just change your database credentials in settings.php, and use the Backup and Restore module to reload your database.
> 0 votes

# Answer
The script below was posted on http://ruleant.blogspot.com/2009/03/rename-multiple-tables-in-mysql.html# by Dieter Adriaenssens .

This PHP script automates the renaming of multiple tables in a MySQL database. It lists all tables in a MySQL database, which contain a defined string pattern. The script creates and executes a series of SQL statements, which rename the table by replacing the search pattern in the original table name with another pattern in the new table name.

This script can easily be modified to rename multiple databases, or when stripping the original pattern (f.e. a prefix) and adding a new pattern (f.e. a suffix) is needed.

```
<?php
$db_server = "localhost";    // hostname MySQL server
$db_username = "username";   // username MySQL server
$db_password = "password";   // password MySQL server
$db_name = "database";       // database name

$pattern = "pattern_";          // search string for example: "drpl_"
$new_pattern = "new_pattern_";  // replacement string.
                            // can be empty. For example "" for no db prefix

// login to MySQL server
$link = mysql_connect( $db_server, $db_username, $db_password);

if (!$link)
{
  die('Could not connect: ' . mysql_error());
}

// list all tables in the database containing the search pattern
$sql = "SHOW TABLES FROM `" . $db_name . "`";
$sql .= " LIKE '%" . $pattern . "%'";

$result = mysql_query ( $sql, $link );
if (!$result)
{
  die("Invalid query: " . mysql_error( $link ));
}

$renamed = 0;
$failed = 0;

while ( $row = mysql_fetch_array ($result) )
{
  // rename every table by replacing the search pattern
  // with a new pattern
  $table_name = $row[0];
  $new_table_name = str_replace ( $pattern, $new_pattern, $table_name);

  $sql = "RENAME TABLE `" . $db_name . "`.`" . $table_name . "`";
  $sql .= " TO `" . $db_name . "`.`" . $new_table_name . "`";

  $result_rename = mysql_query ( $sql, $link );
  if ($result_rename)
  {
    echo "Table `" . $table_name . "` renamed to :`";
    echo $new_table_name . "`.\n";
    $renamed++;
  }
  else
  {
    // notify when the renaming failed and show reason why
    echo "Renaming of table `" . $table_name . "` has failed: ";
    echo mysql_error( $link ) . "\n";
    $failed++;
  }
}

echo $renamed . " tables were renamed, " . $failed . " failed.\n";

// close connection to MySQL server
mysql_close( $link );
?>

```

After running the script, you'll have to edit your settings.php to rename the db\_prefix setting. After the script is run, you may get a pdo error: "PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table '\[database\].semaphore' doesn't exist ... in lock\_may\_be\_available()". If this happens: 1) rename your settings.php to something like settings-old.php; 2) copy the default.settings.php to the sites/default folder and rename it to settings.php. This will cause the install script to run. When prompted for your database settings, enter the name of your existing database. The install script will inform you that the database already exists and offer to take you to your site.
> 0 votes

---
Tags: database, migrations
---


# Question
Title: How to add value in to multiple value field (entity reference)?
Im inserting into user field reference to other users. This is my code, but it is overiding all values of field, i just want too add value and keep values added before.

```
<?php
global $user;

$user->field_profile_access['und'][]['target_id'] = 34;
user_save($user)

?>

```

# Answer
I think this line is wrong:

```
$user->field_profile_access['und'][]['target_id'] = 34;

```

You could try with:

```
$user->field_profile_access['und'][] = array('target_id' => 34);

```

or this:

```
$next = count($user->field_profile_access[LANGUAGE_NONE]);
$user->field_profile_access[LANGUAGE_NONE][$next]['target_id'] = 34;

```

I used `LANGUAGE_NONE` instead of `'und'` here, but that's not the problem.

Or even better, using the Entity API. That example is for a field collection, but the idea should be useful for any entity, including nodes.
> 1 votes

---
Tags: 7, entities
---


# Question
Title: When are '$form_state['values'] copied to '$form' on rebuild?
as far as I understand it whenever you submit and rebuild a form (e.g. 'Add another item' on fields with infinite cardinality) something like this happens:

1. User submits a form with filled values
2. User input is copied to $form\_state
3. Element validation happens
4. Form validation happens
5. `drupal_get_form` is called (form is being rebuild)
6. **???** old user input from $form\_state is copied to every `$element[#value]`
7. Individual elements of the form are created in `$element[#process]` callbacks
8. Rebuild form is shown to a user

My question is, when and how is user input from the old form transferred into the new one?

From what I've been able to understand by reading the documentation it must happen somewhere in `drupal_build_form` before the element `#process` callback is called. But when exactly that I haven't been able to find.

//I know about this FAPI flowchart if anyone could point me in the right direction on it I'd appreciate it.

# Answer
> 4 votes
Nothing like "??? old user input from $form\_state is copied to every $element\[#value\]" happens. Simply `$form_state['input']` is kept so that when the form is built the values are filled in based on that.

---
Tags: 7, forms
---


# Question
Title: Is there an efficient way to dermine whether a node can be viewed by all users?
I am trying to use the Drupal node access API to determine whether a node is subject to an access restriction. That is: I want to make sure that the node can be viewed by *any* authenticated user (provided the authenticated user is granted the right to `view published content`).

The function `node_access('view, $node, $account);` returns `TRUE` if the user object `$account` can access `$node`, and `FALSE` otherwise, so I can get the correct result stored in `$view_for_all` with the following snippet of code:

```
$accounts = entity_load('user');
$view_for_all = TRUE;
foreach ($accounts as $account) {
  if (!node_access('view', $node, $account)) {
    $view_for_all = FALSE;
    break;
  }
}

```

However, looping through all accounts will be very slow if there are, say, 50000 users. I am looking for a *more efficient* way to do this.

# Answer
> 0 votes
This is surely impossible. Modules can decide on the fly which nodes are visible. https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook\_node\_access/7

# Answer
> 0 votes
If you are needing to check node\_access records, then you may be able to examine them similarly to how devel\_node\_access does. In the end, all nodes have grants added to the node\_access table, so if there are grants that deny or restrictively add access, then you can probably see it there.

Another option would be to have a dummy account that is an authenticated user, and used as the test case. This will fail, of course, if you need to detect grant rules that *deny* access to authenticated users who would otherwise be entitled. It's a sticky situation.

The hardest part about this question is that it seems as though you are looking for a general solution to a specific problem, and I'm not quite sure that a general solution exists.

---
Tags: users
---


title: Proximity for OpenLayers

text:
# Question
Title: Proximity for OpenLayers
It has a bug that keeps dumping errors to the logs. There is a patch, but the patch removes the distance field. The module isn't maintained.

Does anyone know of other modules that can be used with OpenLayers and views to plot locations within a particular radius?

# Answer
> 0 votes
Use the geofield module 2.x. It contains proximity capabilities

# Answer
> 0 votes
Here is a link to instructions on Drupal.org for creating proximity search using Open Layers.

It's fallen a little behind updates to the process, but I'm going to try and update it very soon.

https://www.drupal.org/node/1714680

---
Tags: 7, javascript
---


title: How to fix Feature with Panels

text:
# Question
Title: How to fix Feature with Panels
I am managing a website that makes extensive use of panels. I had a "system" panel page with Title = 'Registration Template' and a path of 'registration/%registration'.

Somehow, in updating the features on the LIVE site, I managed to loose this panel page. It is not available on the LIVE site. I can recreate a feature with "registration\_view\_panel\_context" this under Page Manager.

But when I move this feature to the live site, it does not become available to me as a panel. It is included in the feature, but the feature is overridden. I am unable to "revert" the feature.

* Despite being labeled as a "system" page, the 'Registration Template' is not available to me.
* As a "system" page, I do not have the option of exporting it from my local site.
* And when I try to revert the feature on LIVE - nothing happens.
* If I try to create a new panel page on LIVE with this path - "registration/%registration" I get a message "that path is already in use. This system cannot override existing paths."

This panel page is still available to me and works on my local site, but I can't figure out how to move it back onto the LIVE site.

Any ideas?

EDIT: Solved this problem myself (not myself, but with local help :-) See below for answer.

# Answer
> 0 votes
It turns out I needed to recreate this "system" page as an "existing page" using the - Page Manager Existing Pages - module (drupal.org/project/pm\_existing\_pages). I am not entirely sure why, but this solved my problem.

---
Tags: panels, features
---


title: Drush is unable to update my site

text:
# Question
Title: Drush is unable to update my site
I'm trying to update my drupal core though drush. But how hard i trie, it won't work. I''m using drush pm-update but it fails. Below the output of the drush debug.

Tnx in advance

```
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.05 sec, 4.34 MB]                                                                                [bootstrap]
Initialized Drupal 7.28 root directory at /var/www/my-site.nl-dev/web [0.06 sec, 5.95 MB]                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.07 sec, 5.96 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.12 sec, 6.47 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.13 sec, 6.7 MB]                                                                           [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.15 sec, 6.72 MB]                                                                               [bootstrap]
Successfully connected to the Drupal database. [0.15 sec, 6.72 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.16 sec, 7.55 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_login() [1.12 sec, 41.71 MB]                                                                                [bootstrap]
Found command: pm-update (commandfile=pm) [1.21 sec, 42.14 MB]                                                                                [bootstrap]
Including /usr/share/drush/commands/pm/updatecode.pm.inc [1.21 sec, 42.17 MB]                                                                                [bootstrap]
Refreshing update status information ...
Done.
Update information last refreshed: ma, 07/28/2014 - 21:53

Update status information on all installed and enabled Drupal projects:
 Naam                       Geïnstalleerde versie  Proposed version  Status
 Alchemy                    7.x-1.0-beta1          7.x-1.0-beta1     Actueel
 Drupal core                7.28                   7.30              SECURITY UPDATE available
 Content Analysis           7.x-1.0-beta6          7.x-1.0-beta6     Actueel
 Context                    7.x-3.2                7.x-3.2           Actueel
 Chaos tool suite (ctools)  7.x-1.4                7.x-1.4           Actueel
 Keyword Research           7.x-1.0-alpha4         7.x-1.0-alpha4    Actueel
 Localization update        7.x-1.0                7.x-1.0           Actueel
 Metatag                    7.x-1.0-beta9          7.x-1.0-rc1       Nieuwe versie beschikbaar
 Nice Menus                 7.x-2.5                7.x-2.5           Actueel
 Piwik Web Analytics        7.x-2.5                7.x-2.5           Actueel
 Site map                   7.x-1.2                7.x-1.2           Actueel
 Site verification          7.x-1.1                7.x-1.1           Actueel
 Superfish                  7.x-1.9                7.x-1.9           Actueel
 Token                      7.x-1.5                7.x-1.5           Actueel
 Webform                    7.x-3.20               7.x-3.20          Actueel
 Wysiwyg                    7.x-2.2                7.x-2.2           Actueel
 XML sitemap                7.x-2.0                7.x-2.0           Actueel
 Busy                       7.x-1.5                7.x-1.5           Actueel

NOTE: A code update for the Drupal core is available.
Drupal core will be updated after all of the non-core modules are updated.

Code updates will be made to the following projects:
WD php: Notice: Undefined variable: print in pm_update_packages() (line 237 of /usr/share/drush/commands/pm/updatecode.pm.inc). [1.27 sec, 43.04 MB]            [notice]
Metatag [metatag-7.x-1.0-rc1]

Note: Updated projects can potentially break your site. It is NOT recommended to update production sites without prior testing.
Note: A backup of your package will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue? (y/n): y
Starting to update Metatag code at sites/all/modules/metatag... [13.69 sec, 43.02 MB]                                                                           [notice]
Executing: svn info '/var/www/my-site.nl-dev/web/sites/all/modules/metatag' [13.69 sec, 43.03 MB]                                                        [notice]
  svn: '/var/www/my-site.nl-dev/web/sites/all/modules/metatag' is not a working copy
Calling mkdir(/var/www/my-site.nl-dev/web/backup, 511)
Calling mkdir(/var/www/my-site.nl-dev/web/backup/modules, 511)
Calling mkdir(/var/www/my-site.nl-dev/web/backup/modules/20140729205514, 511)
Calling rename(/var/www/my-site.nl-dev/web/sites/all/modules/metatag, /var/www/my-site.nl-dev/web/backup/modules/20140729205514/metatag)
Downloading project metatag ... [13.92 sec, 43.05 MB]                                                                                [notice]
Executing: wget -P . http://ftp.drupal.org/files/projects/metatag-7.x-1.0-rc1.tar.gz [13.92 sec, 43.06 MB]                                                      [notice]
  --2014-07-29 20:55:28--  http://ftp.drupal.org/files/projects/metatag-7.x-1.0-rc1.tar.gz
  Resolving ftp.drupal.org... 140.211.166.134
  Connecting to ftp.drupal.org|140.211.166.134|:80... connected.
  HTTP request sent, awaiting response... 200 OK
  Length: 87802 (86K) [application/x-gzip]
  Saving to: “./metatag-7.x-1.0-rc1.tar.gz”

       0K .......... .......... .......... .......... .......... 58%  104K 0s
      50K .......... .......... .......... .....                100%  221K=0.6s

  2014-07-29 20:55:29 (133 KB/s) - “./metatag-7.x-1.0-rc1.tar.gz” saved [87802/87802]

Downloading metatag-7.x-1.0-rc1.tar.gz was successful. [14.92 sec, 43.06 MB]                                                                                [notice]
Md5 checksum of metatag-7.x-1.0-rc1.tar.gz verified. [14.92 sec, 43.06 MB]                                                                                [notice]
Executing: gzip -d metatag-7.x-1.0-rc1.tar.gz [14.92 sec, 43.06 MB]                                                                                [notice]
Executing: tar -xf metatag-7.x-1.0-rc1.tar [14.95 sec, 43.06 MB]                                                                                [notice]
Calling unlink(metatag-7.x-1.0-rc1.tar)
Project metatag was updated successfully. Installed version is now 7.x-1.0-rc1.
Backups were saved into the directory /var/www/my-site.nl-dev/web/backup/modules/20140729205514/metatag. [15.02 sec, 43.06 MB]                        [ok]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.06 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.08 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Including /usr/share/drush/commands/core/clear.cache.inc [15.02 sec, 43.09 MB]                                                                               [bootstrap]
Calling call_user_func(drupal_flush_all_caches)
'all' cache was cleared [16.99 sec, 49.06 MB]                                                                                [success]
Undefined variable: print in pm_update_packages() (regel 237 van /usr/share/drush/commands/pm/updatecode.pm.inc). [16.99 sec, 49.06 MB]                         [notice]
Including /usr/share/drush/commands/pm/updatecode.pm.inc [17 sec, 48.88 MB]                                                                                [bootstrap]
Refreshing update status information ...
Done.
Update information last refreshed: ma, 07/28/2014 - 21:53

Update status information on all installed and enabled Drupal projects:
 Naam                       Geïnstalleerde versie  Proposed version  Status
 Alchemy                    7.x-1.0-beta1          7.x-1.0-beta1     Actueel
 Drupal core                7.28                   7.30              SECURITY UPDATE available
 Content Analysis           7.x-1.0-beta6          7.x-1.0-beta6     Actueel
 Context                    7.x-3.2                7.x-3.2           Actueel
 Chaos tool suite (ctools)  7.x-1.4                7.x-1.4           Actueel
 Keyword Research           7.x-1.0-alpha4         7.x-1.0-alpha4    Actueel
 Localization update        7.x-1.0                7.x-1.0           Actueel
 Metatag                    7.x-1.0-beta9          7.x-1.0-rc1       Nieuwe versie beschikbaar
 Nice Menus                 7.x-2.5                7.x-2.5           Actueel
 Piwik Web Analytics        7.x-2.5                7.x-2.5           Actueel
 Site map                   7.x-1.2                7.x-1.2           Actueel
 Site verification          7.x-1.1                7.x-1.1           Actueel
 Superfish                  7.x-1.9                7.x-1.9           Actueel
 Token                      7.x-1.5                7.x-1.5           Actueel
 Webform                    7.x-3.20               7.x-3.20          Actueel
 Wysiwyg                    7.x-2.2                7.x-2.2           Actueel
 XML sitemap                7.x-2.0                7.x-2.0           Actueel
 Busy                       7.x-1.5                7.x-1.5           Actueel

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.
Do you really want to continue? (y/n): y
Executing: svn info '/var/www/my-site.nl-dev/web/drupal-7.30' [30.11 sec, 49.21 MB]                                                                      [notice]
  svn: '/var/www/my-site.nl-dev/web/drupal-7.30' is not a working copy
Calling mkdir(/var/www/my-site.nl-dev/web/backup, 511)
Drush command could not be completed. [30.16 sec, 49.25 MB]

```

# Answer
You didn't show the command line that you're running, but it looks like you're using the various --svn\* options to pm-update. I don't think these are working well right now; try to do the update without them, and do your version control operations by hand after the update completes.
> 2 votes

---
Tags: drush, updating
---