# Question
Title: Using Views to List a Member's Organic Groups (7.x-2.3)
I am migrating a site from using OG 7.x-1.4 to OG 7.x-2.3. The migration seemed to go fine, but it broke the view that shows the current users group (i.e. groups the user is a member of). In the original view for 1.4, it had a contextual filter:

* (OG membership from OG group) We pass to the "Entity ID" the User ID.

And the following relationships:

* OG group: OG group from Node
* (node being the OG group) OG group: OG membership from OG group

However, the new Organic Groups 7.x-2.3 now uses the OGMembership data model and I cannot figure out how to recreate this view using OGMembership, as I am not clear exactly how it works and I cannot seem to find any in-depth documentation for this kind of thing.

# Answer
This is how to get the OG membership ID:s to start with.

Add new view. Show -\> OG membership (important!) Then in some display add a contextual filter -\> OG membership: Entity id. Provide default value -\> Type -\> User ID from logged in user. Override title: %1's groups. Specify validation criteria -\> User.

Now you have the list of ID:s.

Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -\> Group Node from OG membership. Add a field -\> Content: Title. Relationship -\> Group node from OG membership.

Now you have the titles too. Add some filters and sort criterias to taste.
> 11 votes

# Answer
Here is the export for a view that does the job as described by Kari Kääriäinen above.

```
$view = new view();
$view->name = 'my_groups';
$view->description = 'List of Groups I\'m Subscribed To';
$view->tag = 'default';
$view->base_table = 'og_membership';
$view->human_name = 'My Groups';
$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['title'] = 'My Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$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['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: OG membership: Delete link */
$handler->display->display_options['fields']['delete_membership']['id'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['delete_membership']['field'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['label'] = 'Remove';
/* Field: OG membership: Edit link */
$handler->display->display_options['fields']['edit_membership']['id'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['edit_membership']['field'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['label'] = 'Edit';
/* Field: OG membership: Rendered OG membership */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_og_membership';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 0;
/* Contextual filter: OG membership: Entity id */
$handler->display->display_options['arguments']['etid']['id'] = 'etid';
$handler->display->display_options['arguments']['etid']['table'] = 'og_membership';
$handler->display->display_options['arguments']['etid']['field'] = 'etid';
$handler->display->display_options['arguments']['etid']['default_action'] = 'default';
$handler->display->display_options['arguments']['etid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['etid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['etid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['etid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'my_groups';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'My Groups';
$handler->display->display_options['menu']['description'] = 'Groups that I am subscribed to';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['my_groups'] = array(
  t('Master'),
  t('My Groups'),
  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 »'),
  t('Remove'),
  t('Edit'),
  t('Rendered OG membership'),
  t('All'),
  t('Page'),
);

$view = new view();
$view->name = 'my_groups';
$view->description = 'List of Groups I\'m Subscribed To';
$view->tag = 'default';
$view->base_table = 'og_membership';
$view->human_name = 'My Groups';
$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['title'] = 'My Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$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['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: OG membership: Delete link */
$handler->display->display_options['fields']['delete_membership']['id'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['delete_membership']['field'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['label'] = 'Remove';
/* Field: OG membership: Edit link */
$handler->display->display_options['fields']['edit_membership']['id'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['edit_membership']['field'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['label'] = 'Edit';
/* Field: OG membership: Rendered OG membership */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_og_membership';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 0;
/* Contextual filter: OG membership: Entity id */
$handler->display->display_options['arguments']['etid']['id'] = 'etid';
$handler->display->display_options['arguments']['etid']['table'] = 'og_membership';
$handler->display->display_options['arguments']['etid']['field'] = 'etid';
$handler->display->display_options['arguments']['etid']['default_action'] = 'default';
$handler->display->display_options['arguments']['etid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['etid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['etid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['etid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'my_groups';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'My Groups';
$handler->display->display_options['menu']['description'] = 'Groups that I am subscribed to';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['my_groups'] = array(
  t('Master'),
  t('My Groups'),
  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 »'),
  t('Remove'),
  t('Edit'),
  t('Rendered OG membership'),
  t('All'),
  t('Page'),
);

```
> 0 votes

---
Tags: organic-groups, views
---


# Question
Title: Get number of items in cart of current anonymous user
I need to get the number of items in cart of current anonymous customer on the site. I am using Drupal 7 and Drupal Commerce.

# Answer
To load the current anonymous user cart, you can use `commerce_cart_order_load` something like this should suffice:

It gets the product count as separate line items and the product quantity including number of items per line item.

```
// Can leave blank or provide UID
$uid = 0; // anon
$product_count = 0;
$product_quantity_count = 0;

// Load cart order
if ($order = commerce_cart_order_load($uid)) {
  // Let's use the wrapper because it rocks
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Loop over line items and increment product counter
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    // If line item is a commerce product type
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      // Increment counters
      // Individual product line item
      $product_count++;
      // Number of items of product line item (quantity)
      $product_quantity_count += $line_item_wrapper->quantity->value();
    }
  }

  // Debug output
  drupal_set_message(t('User %uid has %count products in cart with a total of %quantity items',
    array('%uid' => $uid, '%count' => $product_count, '%quantity' => $product_quantity_count)));
}

```
> 3 votes

---
Tags: users, commerce
---


title: private files in drupal 6

text:
# Question
Title: private files in drupal 6
I have a sub directory in my files directory which I want to store private images. I display the images with their watermark, via the imagecache modules.

I thought I could make the directory (with the original images) hidden to the public simply by dropping an .htaccess file in the folder, with

```
deny from all

```

but the files are still publicly accessible. What am I missing?

# Answer
> 0 votes
If you want to basically prevent hotlinking images, you can try the following in your `.htaccess` file

```
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

```

---
Tags: 6, .htaccess, files
---


# Question
Title: Custom entity api create options list for checkboxes without field api
I want to create a checkbox widget in my custom entity to select multiple options.

I don't want to use the field api, instead I want to use my custom table with multiple columns, one of them shall have the values which were chosen.

For select I use the following:

```
$info['pricedefault']['properties']['preis_zeiteinheit'] = array(
'label' => t('Time unit'),
'description' => t('Preis Zeiteinheit'),
'type' => 'integer',
'schema field' => 'preis_zeiteinheit',
'options list' => 'zeiteinheit_options_list',
'translatable' => TRUE,
);

```

and

```
function zeiteinheit_options_list(){
return array(0=>t('0'),1 => t('YEAR'),2 =>t('MONTH'),3=>t('WEEK'),4=>t('DAY'));
}

```

But how to write a checkbox function with the correct table column?

Thx in advance,

maen

# Answer
> 0 votes
To store multiple value property values, without the field API, you may find it easier to create a generic extended properties table for one-to-many relationship with the base table.

e.g a table

```
Table: my_entity_properties

Columns: entity_id | revision_id | name | value

```

You can then store the extended properties in that table in the `save` function for your entity - each field value will be a row with the property name and value pair. You then load them in the `attachLoad` function, grouping by the revision\_id and property name to load the values for that entity revision.

---
Tags: entities
---


# Question
Title: How to skip the description step when uploading a file for a specific field?
in the media module's settings, there's a checkbox called "Skip available fields" that lets you skip filling out fields that are attached to your media when you add one.

In some cases, we need to let users enter a description for files that are uploaded and in other cases, no.

Does anybody know how to skip the available fields for a specific field of a specific content type ? What kind of code or hook implementation is required, etc. ...

Thanks !

# Answer
You could probably acheive that by implementing

`hook_field_attach_form`

and setting the required values (e.g `#required => TRUE` or unsetting the description element.).

The entity\_type and entity values are available for conditionally showing / hiding data there.
> 0 votes

---
Tags: media
---


# Question
Title: Hide the Drupal /user/register form from spam, but leave open registration to Commerce/Ubercart
Commerce/Ubercart require account creation to buy product. That's fine - I want that.

But I do not want user/register open to the public. Efforts to use Honeypot/Captcha/Mollom are still letting in lots of spam user registration.

What is a hook\_form\_alter I could use in a module to entirely remove the user/register form and make user/register page blank, without disabling open registration for Ubercart/Commerce? I would then add a block to this page instructing humans to buy a product to create an account.

Make sense? Please advise on the code. THANKS!

# Answer
Basically you can keep user registration functionality, notification emails etc.. and prevent access to the user register page by either altering the registration form, or better yet, the page callback for the entire page.

e.g:

```
/**
 * Implements hook_menu_alter
 **/
function MODULE_menu_alter(&$items) {
  // Deny all access to the user/register page.
  // Administrators can still create user accounts via admin > people
  // Notification emails etc.. are still operational
  // and Commerce / Ubercart can create user accounts following checkout etc..
  $items['user/register'] = array(
    'access callback' => FALSE,
  );
}

```
> 1 votes

# Answer
I think your way is not so good. Try this module "BOTCHA Spam Prevention"
> 0 votes

# Answer
if you're using Drupal 7 and you don't want public registration available:

* go to /admin/config/people/accounts
* about half way down the page is :REGISTRATION AND CANCELLATION
* here you can set the terms of registration - it sounds like you would want Administrators Only

As an alternative (in case that method prevents new registration under Commerce):

* using Rules, set up a rule based on the current path to redirect to the front page. Since Rules is already installed for Commerce it doesn't require any new modules, and will appear as though that page doesn't exist
> 0 votes

---
Tags: commerce, users, forms
---


title: Infinite scroll pager in Drupal 7

text:
# Question
Title: Infinite scroll pager in Drupal 7
I want to add infinite scroll page in search result pages. I am using Drupal 7.

To achieve it i followed this link.

When i do exactly as per the step given on this page, but i am not able to get it working.

Here is the HTML generated on my search result page.

Now to apply the pager in this page i made the following changes in the scripts given in the above link.

1. Remove .autopager class as i will have to add .pager class
2. Remove the imagesLoaded function as there are no images in the result

So after removal js will be like this. In his code i have added the .pager class. I am not able to get the pager and what should i write instead of **viewsInfiniteScroll**

```
   (function ($) {
  Drupal.behaviors.viewsInfiniteScroll = {
    attach: function (context, settings) {
      $(function(){
        var $container = $('div.pager');
      });
    }
  };
})(jQuery);

```

# Answer
> 2 votes
After lots of brainstorming and googling one user Marc from drupal.org suggested me the working solutions. Thanks to Marc for the solution.

Here is the solution:

To set it up, you will need a couple of steps: REM: This method don't use the "Infinite Scroll Module", it's a rewrite of the stuff. In this method I choosed to integrate it in the theme, you could also create your own module (wish would be probably better .... )

1) download https://github.com/desandro/imagesloaded (jquery.imagesloaded.min.js) place it in your theme folder `YOURTHEME/js` This will make sure all images are loaded before activate the infinite scroll

2) download https://github.com/paulirish/infinite-scroll (jquery.infinitescroll.min.js) place it in your theme folder YOURTHEME/js In order to make it work with Drupal search modify it as follow: Search `match(/^(.*?page=)2(\/.*|$)`/ replace it by `match(/^(.*?page=)2(&.*|$)`

3) Create a new js (ex:infinitescroll.js) with the content of the below jquery & place it in your theme folder `YOURTHEME/js` Rem: You will probably have to change the img path

4) modify `YOUR_THEME.info` and add

* scripts\[\] = js/jquery.imagesloaded.min.js
* scripts\[\] = js/jquery.infinitescroll.min.js
* scripts\[\] = js/infinitescroll.js

5) flush the cache

6) cross finger & try .... it should work if not ... it's time to debug with firebug ...

Jquery code which you should place in **infinitescroll.js**

```
(function($){
    Drupal.behaviors.viewsInfiniteScroll = {
            attach: function (context, settings) {
              $(function(){
                if (this.processed) return;
                this.processed=true;
                if ($('.search-results').length==0) return;
                var $container = $('.search-results');
                $container.imagesLoaded( function(){
                  $container.infinitescroll({
                    navSelector  : 'ul.pager',    // selector for the paged navigation
                    nextSelector : '.pager-next a',  // selector for the NEXT link (to page 2)
                    itemSelector : '.search-results',     // selector for all items you'll retrieve
                    animate      : true,
                    msgText  : Drupal.t("Loading new results..."),
                    img: '/sites/default/themes/bartik/images/ajax-loader.gif',
                    donetext:Drupal.t('No more results to load.'),
                },function(arrayOfNewElems,state){
                    //YOUR CALLBACK STUFF .. To re-attach behaviour if needed

                    })
            })
          });
          }
        };
})(jQuery);

```

# Answer
> 1 votes
Why not use Infinite Scroll or Views Infinite Scroll?

# Answer
> 1 votes
You can easily use Views Infinite Scroll module.

Or combine Views Load More with Waypoints modules.

# Answer
> 0 votes
You can use the GD Infinite Scroll module to add infinite scroll or load more button on non-view paged list, can also work with views.

> Provide an administration to use the infinite scroll jQuery plugin : auto-pager on custom pages using drupal pager.

---
Tags: paging
---


# Question
Title: domain-name.com/user and other URLS not loading
When I go to my `domain.com/user` I get a blank page, where as usually that was the URL I go to to log in and change content. I came across this thing: https://www.drupal.org/node/256410, but I do not know if it is the same issue. I tried uploading a new `.htaccess` file to no avail. Any thoughts/ suggestions?

# Answer
You should enable apache's rewrite mod. and then restart your apache server. Then, goto configuration and check clean URL. After that your site will be using clean URL.
> 0 votes

---
Tags: uri
---


title: Removing file from form breaks site

text:
# Question
Title: Removing file from form breaks site
I created a module that hooks into the admin menu and allows you to upload a specific file for the site to use.

It allows you to upload a file, and change a file, but as soon as you remove a file and click submit I get the error:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file\_managed} (filesize, status, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> 1 \[:db\_insert\_placeholder\_2\] =\> 1412011464 ) in drupal\_write\_record() (line 7202 of /var/www/html/includes/common.inc).

I think Im missing a step when it comes to managing files in a form. Here is the relevant module code:

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

    $form = array();

    // File selection form element
    $form['csv_file'] = array(
        '#name' => 'file',
        '#type' => 'managed_file',
        '#title' => t('Choose a CSV File'),
        '#description' => t('Upload your Daily Nav CSV here'),
        '#upload_location' => 'public://',
        '#default_value' => variable_get('csv_fid', ''),
        '#upload_validators' => array(
            'file_validate_extensions'=> array('csv'),
        ),
    );

    $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
    return $form;
}

function read_more_news_admin_form_submit(&$form, &$form_state) {

    // Saving the file, setting it to a permanent state, setting a FID variable
    $file = file_load($form_state['values']['csv_file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);

}

```

# Answer
> 1 votes
The value of $form\_state\['values'\]\['csv\_file'\] is empty (0) when you remove the file. You need to do a sanity check on $file after file\_load not only for that reason but also as a good coding practice.

```
function custom_admin_form_submit(&$form, &$form_state) {
  // Saving the file, setting it to a permanent state, setting a FID variable
  $file = file_load($form_state['values']['csv_file']);
  if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);
  }
  else {
    variable_set('csv_fid', '');
  }
}

```

---
Tags: forms, files, database
---


# Question
Title: Update Two select box when change another select box
I have drupal form with three select box i want to change select box 2nd and 3rd after change value of 1st select box.

ex: i have Three select box

1) Cruise line

2) Destination

3) Ship Id

When user select any value of Cruise line then i want to update value of 2) Destination and 3) Ship id

2nd and 3rd select box value are dependent on 1st select box

your answer really appreciated

Thanks in advance

# Answer
> 0 votes
Finally I have found answer for updating multiple field after changing values of select box

```
function callback_function($form, &$form_state)
{
  $commands = array();
  $commands[] = ajax_command_replace('#element1', drupal_render($form[any form element]));
  $commands[] = ajax_command_replace("#element2", drupal_render($form[any form element]));
  return array('#type' => 'ajax', '#commands' => $commands);
}

```

In your ajax callback add `ajax_command_replace()`. This function have two arguments, first argument is element id (ex: div,span etc that's you want to replace) second argument is HTML or data that's that you want to place at place of element.

# Answer
> 1 votes
Try one of the following module

Simple hierarchical select

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Hierarchical Select

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Or you can also achieve that by writing a custom module :)

---
Tags: forms, javascript, ajax
---


# Question
Title: Conditionally show fields viewing a node (not in the node add form)
I know conditional fields can be use to create CCK optional fields, but I need something similar to display part of a node, according to user decisions.

I will have a question "do you like cats?", then the user will be shown another question according to what they answer to the first one, and so on.

I was thinking to create this all in one node

* field1 -\> answer 'yes' -\> show field2,
* field1 -\> answer 'no' -\> show field3),

but I guess this could be done the same with multiple nodes

* node1 -\> answer 'yes' -\> show node2,
* node1 -\> answer 'no' -\> show node3.

Do you have any module to suggest me to reach my goal?

# Answer
If you haven't solved this yet, the Webform Conditional module might help.

> This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.
> 1 votes

# Answer
You can use the Conditional Fields module. This works with CCK in Drupal 6 and the States API in Drupal 7.
> 0 votes

# Answer
With the example given I guess taxonomy can be used to tag nodes and then later on filter them on basis of tagged term.So using views to list your nodes and exposing the taxonomy terms as exposed filter might be helpful here.
> 0 votes

# Answer
Field Formatter Conditions should work for you. I use it all the time for cases like this. On the "Manage Display" tab for each field in a view mode, you can determine to either show or hide a field based on another field's value. Very helpful.
> 0 votes

# Answer
You can use the Entityform module, combined with Conditional Fields.
> -1 votes

---
Tags: 6
---


# Question
Title: Make almost duplicate copy of node when submitting
We have a meeting room booking system that needs one extra feature added. Meeting rooms 1 and 2 have a removable wall so people can book Room 1, Room 2 or Rooms 1 and 2. What I need is a way during booking for the option to book one or both rooms.

My plan: Offering separate booking forms for Room 1 and Room 2 and just have a field where they can check off if they need the other room booked with it. If this box is checked, it will create a duplicate booking with a new ID and the room number (Term reference list) changed.

From my reading, I think I need to use node\_save() to do this? I am not sure where to call this from though. I assume I need to call it from one of the hook\_node\_\* things (as we already do for some other custom code)?

Basically, how do I create a duplicate node when submitting a form with almost identical data but one field is changed before it saves the copy?

Thanks!

# Answer
> 0 votes
Drupal core doesn't provide hook *after* a node has been saved, but you can use `hook_node_presave()` like

```
<?php
function mymodule_node_presave() {
  $var = $node->original->field_my_field['und'][0]['value'];
  // field_my_field could be the checkbox value, if both rooms should be booked
  if ($var == true) { make_a_copy_but_change_a_value(); }
}
?>

```

Using this hook, you can look for your extra checkbox value (if the second room should be booked, too) and create a copy of the node object. But beware, at this point (`hook_node_presave`) the original node is not yet fully written to the database. However, the cool thing is that it fires both on node save and node update, so if you need to do something both on the creation and the updating of a node (e.g. if a booking of *both* rooms changes).

To actually use a hook *after* node insertion, you may want to try the Hook Post Action module as it provides special hooks. Drupal core does not provide such hooks, `hook_node_insert` and `hook_node_update` are both fired *after* the sql query for insertion is scheduled for execution but due to the transactional system the data is not yet in the database.

# Answer
> 0 votes
You can use the hook\_node\_presave with node-\>is\_new.

```
<?php
  function yourmodule_node_presave() {
    if (isset($node->is_new)) {
     // If node is inserted  first time
      $room_2 = $node->field_my_field['und'][0]['value']; //Get the checkbox value
      if ($room_2 == true) {
       //create new node
       }
    }
  else{
  // Perform your action if node is updated as you should not create duplicate
  //room2-node at room-1 node update.
  }
  }
   ?>

```

---
Tags: nodes
---


# Question
Title: do thumbnail image styles lower the page load
This may not be a Drupal specific question, but when I use image styles to resize from a full to thumbnail size, will the page load still behave as if its a hiqh quality image, or does it lower the page load?

I'm trying to figure out if there should ever be a reason to provide two upload fields on a content type, one for a high quality image and one for a lower one.

# Answer
Uploaded images are scaled depending on the preset you choose for display. Thus, a typical high resolution image which might have 8 MB is reduced to maybe 150 kB when using a thumbnail preset. This of course lowers the bandwidth, the original image is not loaded.

So, there is no need to create a second image field. If you haven't seen it yet, you might want to take a look at the Colorbox module. It lets you choose to display an image as a thumbnail and only upon clicking on that preview the full image is loaded (or just another size you defined).

Just a note: Colorbox is not the only module that is providing that feature, there are a lot of similar modules, the original was called Lightbox. On drupal.org, there's a page comparing all available lightbox clones.
> 1 votes

# Answer
Using thumbnail image, your page load time will be decreased. You should use only one field to upload image.You can use different image styles in drupal.

By default, drupal provides your three images styles.

1)Thumbnail

2)Medium

3)Large

You can also create more image styles at following page.

Click on Configuration-\> Media-\>Image Style. Click on Add style link.
> 1 votes

---
Tags: media
---


title: Ajax Request Failing

text:
# Question
Title: Ajax Request Failing
I've got a perplexing issue which has left me quite confused. I've got a form which has a link on it and when the user clicks the link it is supposed to open up an AJAX popup form and display some data in the form.

It is working just perfectly about 90% of the time. But of late, a few users are complaining that when they click the link, the popup appears but the data is not being displayed. Instead, they just get the loading sign and it just goes on forever.

I decided to test this myself and after a few tries I was able to replicate this myself. In my JS Console, I've got no response back and just have the request headers. As for my code, what happens is, when the popup is displayed initially, I just have the loading throbber going and I send a .get request to my Drupal function to retrieve the data. Once the data is retrieved, we replace the throbber with the data display. You can see this being done in the code below:

```
$('a.myModule_test_request', context).live("click", function(event) {
        //Store the matched div jquery object in a variable
        var $this = $(this);

        event.preventDefault();

        //Get the complete url for the Test Request drupal function
        var testurl = Drupal.settings.basePath + 'myModule/TestRequest/';
        //Get the nodeid from the link
        var linkurl = $this.attr("href");
        //We use a regex to extract the nid, which is at the end of the url
        var match = /\d+$/.exec(linkurl);
        var nid = match[0];
        //The complete url for the Test Request drupal function
        testurl = testurl + nid;

        //Create a temporary div and turn it into a modal dialog
        var $myModule_Item_TestRequest_modal_dialog = $('<div id ="myModule_Item_TestRequest_' + nid + '"></div>');

        //Make the height and width of the dialog 95% of the screen size
        var dialogWidth = ($(window).width() * 0.95);
        var dialogHeight = ($(window).height() * 0.95);

        $myModule_Item_TestRequest_modal_dialog
          .addClass("myModule_test_request_dialog")
          .addClass("myModule_dialog")
          .dialog({
            modal: true,
            title: $this.text(),
            resizable: true,
            draggable: true,
            height:dialogHeight,
            width:dialogWidth,
            bgiframe: true,
            open: function () {
              //Add an id attribute to the close button, when the dialog opens, which will be used later to close the dialog and detach behaviors
              $(this).parent().children().children('.ui-dialog-titlebar-close').attr( 'id', 'myModule_Item_TestRequest_Dialog_Close');
              //Add an id to main div of dialog box.

              $(this).parent('.ui-dialog').attr( 'id', 'myModule_Item_TestRequest_Dialog');
              //Add the myModule_test_request_dialog and myModule_dialog classes to main div of dialog box as well
              $(this).parent('.ui-dialog').addClass("myModule_test_request_dialog_wrap myModule_dialog");

            }
          });

          //Add positioning for the div
          $myModule_Item_TestRequest_modal_dialog.position({
            my: "center",
            at: "center",
            of: window
          });

          //Display the throbber in the dialog while the form loads
          $myModule_Item_TestRequest_modal_dialog.html('<div class="myModule_throbber"><img src="' + throbberImage.src + '" width="48" height="48" alt="Loading.."><p>Loading..</p></div>');

          //Load the html returned from the testurl function and attach behaviors to the new content.
          $.get(testurl, function(data) {
            $myModule_Item_TestRequest_modal_dialog.html(data);
            Drupal.attachBehaviors($myModule_Item_TestRequest_modal_dialog);
          });

          //When the dialog close button is clicked, detach behaviors and remove the dialog
          $('#myModule_Item_TestRequest_Dialog_Close').click(function() {
            Drupal.detachBehaviors($myModule_Item_TestRequest_modal_dialog);
            $myModule_Item_TestRequest_modal_dialog.dialog('destroy').remove();
          });
      });

```

After troubleshooting this, I figured out that when the popup hangs, there is absolutely no request being logged for that particular click in the Apache request log. How could this happen? I know the function is working all the way until that .get request because I've got the popup loaded and the throbber displayed, but what happens after that? It's appears as though it is failing to even send the request to Apache. Do requests go ignored in jQuery?

Hope you guys can give me some pointers on why this could happen. Any help would be highly appreciated.

# Answer
It appears to me that you have not yet enclosed your script as described in this post. That might be it?

```
(function($) {
Drupal.behaviors.myBehavior = {
  // your function goes here, I think.
};
})(jQuery);

```
> 0 votes

---
Tags: javascript, ajax
---


title: List all content of the same Author

text:
# Question
Title: List all content of the same Author
I have a view on a node page. How do I get it to list all content that has the same author as the current node?

# Answer
> 4 votes
Are you using 6 or 7? In 6 you'll need to add an Argument; in 7 a contextual filter. Either way, it works pretty much the same.

1. Create a block display.
2. Add the fields you want (usually just the title for a simple list.)
3. Add either an argument or contextual filter for the author uid.

Then under "Action to take if argument is not present", choose provide default value. For the default value, choose PHP Code, and add this code to the box:

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $uid = $node->uid;
}
return $uid;

```

Save your view; then clear all caches.

Note that the use of contextual filters renders the preview unusable; you'll need to actually add your block to a page to see it.

# Answer
> 1 votes
did you happen to reach a solution? This view settings works for me. It shows the content of the author of the current page.

# Answer
> 0 votes
Can't you just add a filter and set the author id (uid) to whoever the page belongs to?

---
Tags: views
---


title: "What links here" for Beans

text:
# Question
Title: "What links here" for Beans
I'm using an Entity Reference field (unlimited entries) and a View to include desired Beans on node pages. How can I create a view similar to node/%/backlinks which allows me to see all the nodes that reference a particular block?

So far, I have a View of Content. It includes a relationship to the Referenced Entity (Block) and a Contextual Filter on Block ID. I want to include this View as a menu item on the Block itself, but blocks aren't displayed with their BID, they use a transliterated version of the label as an alias.

I need to find a way to access the Block ID from the alias, or somehow expose a transliterated version of the Label through Views.

# Answer
> 0 votes
I think your problem is that you are focusing on the label. You need to use a contextual filter of **'Block: Block Delta'**. Then you can add a menu tab to views using this path:

```
block/%/back-links

```

---
Tags: views, entities, blocks
---


# Question
Title: How to insert checkbox value in MySQL database
```
$languages_knows=array(
'English' =>t('English'),
'Hindi' => t('Hindi'),
'Marathi' => t('Marathi')
 );

$form['languages_known'] = array(
'#title' => t('Language Spoken'),
'#options' => $languages_knows,
  '#type' => 'checkboxes'
);
function lawyer_register_form_submit($form, $form_state)
{
//Does something with successfully submited form fields.
global $user;
 $user = db_insert('lawyer_details')
->fields(array(
'first_name' => $form_state['values']['first_name'],
'middle_name' => $form_state['values']['middle_name'],
'last_name' => $form_state['values']['last_name'],
'languages_known'=>$form_state['values']['languages_known'],
))->execute();

```

Please help me.they gives error

> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: INSERT INTO {lawyer\_details} (first\_name, middle\_name, last\_name, street\_address, city, country, phone, email\_id, speciality, languages\_known) 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);

# Answer
'checkboxes' are array - serialize values on insert (and unserialize when get it), something as

```
'languages_known'=>serialize($form_state['values']['languages_known'])

```

edit:

full working code for example form

```
function mymodule_menu() {
  $items['test-form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access callback' => TRUE,
  );

  return $items;
}

function test_form($form, &$form_state) {

  $languages_knows=array(
    'English' =>t('English'),
    'Hindi' => t('Hindi'),
    'Marathi' => t('Marathi')
  );

  $form['languages_known'] = array(
    '#title' => t('Language Spoken'),
    '#options' => $languages_knows,
    '#type' => 'checkboxes'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function test_form_submit($form, &$form_state) {
  //Does something with successfully submited form fields.
  global $user;

  $user = db_insert('lawyer_details')
    ->fields(array(
      //'first_name' => $form_state['values']['first_name'],
      //'middle_name' => $form_state['values']['middle_name'],
      //'last_name' => $form_state['values']['last_name'],
      'languages_known'=>serialize($form_state['values']['languages_known']),
    ))->execute();
}

```

also you need to have install file, same as mymodule.install with table/field schema:

```
<?php

function mymodule_schema() {
  $schema['lawyer_details'] = array(
    'description' => 'Details comments here.',
    'fields' => array(
      'id' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Some identifier.',
      ),
      'languages_known' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => 'Some description here.',
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

```

then delete your table, uninstall module (uncheck, save, uninstall) and install again.

test

hint: see https://www.drupal.org/node/159605 for schema field definition
> 0 votes

---
Tags: 7
---


# Question
Title: Sub Menu's are not coming under main menu
I am using this code to fetch menu's in drupal. I have given Home as parent menu and other are sub menu's like submenu1, submenu2 etc. But in front end they are not coming under Home menu. Only Home menu appear on front end.

```
<?php if ($main_menu): ?>
     <?php
          // This code snippet is hard to modify. We recommend turning off the
          // "Main menu" on your sub-theme's settings form, deleting this PHP
          // code block, and, instead, using the "Menu block" module.
          // @see https://drupal.org/project/menu_block
          print theme('links__system_main_menu', array(
            'links' => $main_menu,
            'attributes' => array(
              'id'=>'s5_nav',
              'class' => array('menu'),
            ),

          ));
          ?>
    <?php endif; ?>

```

# Answer
> 0 votes
You can use Nice Menus to solve your issue.

---
Tags: commerce
---


title: My Theme Is Lost

text:
# Question
Title: My Theme Is Lost
My theme was working earlier, now when I go to the site, it just shows a basic homepage without the theme. I looked at the files and they are all there including the page.tpl.php file.

Not sure what would make that happen. Any ideas?

# Answer
> 0 votes
Did you disable your theme? Try navigating to Appearance on the top Menu Bar, and see which theme is enabled, and if your theme is still recognized by Drupal.

It may be just a matter of reenabling it from that interface.

# Answer
> 0 votes
Is your theme still presents in the /sites/all/themes path ? If yes, i guess he's disable in your apparence administration.

---
Tags: theming
---


title: Pop-up for view bulk operation?

text:
# Question
Title: Pop-up for view bulk operation?
Normally View Bulk Operation (VBO) will lead to separate page for asking details and performing actions.

Is there any module readily available to show pop-up for views bulk operations. Searches did not help.

# Answer
You may check my post answer. You can apply your condition. I think this may help you to solve your query.
> 0 votes

---
Tags: 7, views, javascript, actions
---


title: "Page not found" on hook_menu() items

text:
# Question
Title: "Page not found" on hook_menu() items
I have create simple hook\_menu but when i clear cache retrieve Page not Found

```
function sanabel_calculator_menu() {
  $items = array();
  $items['iban_generator'] = array(
    'title' =>  t('IBAN'),
    'page callback' => 'iban_generator',
    'access callback' => true,
  );

  return $items;
}
function iban_generator(){
  $branch = $_GET['branch'];
  $accountNumber = $_GET['accountNumber'];
  $number_format = "11192427" . $branch . "00" . $accountNumber . "192400";
  $checkdigit = 98 - ( $number_format % 97 );
  $iban = 'JO' . $checkdigit . 'BJOR' . $branch . '00' . $accountNumber;
  $output = '<table border="1" > <tbody> <tr> <td>' . t("Account Number") . '</td>
    <td>' . t('IBAN') . '</td></tr>
    <tr>  <td>' . $accountNumber . '</td><td>' . $iban . '</td></tr>
    </tbody></table> <p>'. l(t('Back'), $back_form) .'</p>';
  return drupal_set_message($output);
}

```

How can fix this problem ??

# Answer
> 1 votes
Follow this checklist and it will work:

* Make sure your module is called `sanabel_calculator`. If it isn't, change `sanabel_calculator_menu()` to `MODULE_NAME_menu()`. It's wise to use your module name to prefix all functions that it defines, as a rudimentary namespacing system. You might want to change `iban_generator()` to `sanabel_calculator_generator()` as part of that, to avoid confustion in the future.
* Return something meaningful from your function. `drupal_set_message()` can return `NULL`, and other than that will only ever return a plain array. This is not acceptable as a page callback result, which needs to be a render array (or, less ideally, a string).
* Make sure the module is enabled
* Clear Drupal's caches

As an aside, consider defining a proper access callback or at least arguments for your page. It may not matter, but it's a good practice to get into.

If it still doesn't work after that, follow the steps again through again. If it still doesn't work, you've got something wrong with your installation. Try to install the module on a fresh copy of Drupal to confirm that.

# Answer
> 1 votes
you should return $output;

```
function iban_generator(){
  $branch = $_GET['branch'];
  $accountNumber = $_GET['accountNumber'];
  $number_format = "11192427" . $branch . "00" . $accountNumber . "192400";
  $checkdigit = 98 - ( $number_format % 97 );
  $iban = 'JO' . $checkdigit . 'BJOR' . $branch . '00' . $accountNumber;
  $output = '<table border="1" > <tbody> <tr> <td>' . t("Account Number") . '</td>
    <td>' . t('IBAN') . '</td></tr>
    <tr>  <td>' . $accountNumber . '</td><td>' . $iban . '</td></tr>
    </tbody></table> <p>'. l(t('Back'), $back_form) .'</p>';
  return $output;
}

```

---
Tags: 7, routes
---


# Question
Title: Getting redirected to the referenced node instead of the created node after node save
I have two organic nodetypes. One of the types has a prepopulated reference field referencing the other nodetype. This means that when i create a node of OG type A it will automatically reference to OG type B.

My problem however is that when i save nodetype A it i get redirected to nodetype B.

I am looking for a way to (using rules ) redirect to nodetype A (the node just created, which is the normal workflow).

Help appreciated..

# Answer
> 0 votes
As a workaround i created a rule (rules module) where i redirected the user upon saving new content. In my action i used this piece of code:

`global $user;
$uid = $user->uid;
$result = db_query ( "SELECT * FROM {og_membership}
WHERE etid = :uid
and entity_type = 'user'
order by gid DESC", array (':uid' => $uid ) );`

Then i used this for my page redirect:

`<?php print "node/".$_SESSION['ses_user_group_gid']; ?>`

---
Tags: entities
---


# Question
Title: How to give href links in custom modules for multilingual site?
I've created a custom module,having a href links like follows.

Let's say the following link appears on `example.com/somepage/another-page/nid`

```
t('<p><a class="stn" href="/my-page">Back to My Page</a></p>');

```

The above links works by default but it won't work if user is in Spanish version (`example.com/es/somepage/another-page/nid`).

If user click on the link it redirects to default lang version (`example.com/my-page`)

I tried `$GLOBALS['base_url']` but it doesn't work in this case.

So my question is how can I give href link for multilingual? Any ideas would be much appreciated.

# Answer
> 1 votes
You have a mistake in your code.

Wrong:

```
t('<p><a class="stn" href="/my-page">Back to My Page</a></p>');

```

Correctly

```
'<p>' . l(t('Back to My Page'), 'my-page', array('attributes' => array('class' => array('stn')))) . '</p>';

```

For more information see function l();

# Answer
> 0 votes
Simply use `l` function:

```
l(t('Back to My Page'), 'my-page', array('attributes' => array('class' => array('whatever-class-you-need-if-any))));

```

It is there to take care about all that irritating details for you.

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


# Question
Title: How to delete a content in a view with view rules?
I got two views that displayed two different type of contents. Content A got a field "Title" and content B got the same field. I want to find and delete any number of content of type B that got the same title of a content A. I try to do this with view rules module with some view loops. I found some content B that got a title equal to a title of content. How to delete them?

# Answer
> 0 votes
Depending on your needs you could potentially use Views Bulk Operations (also known as VBO).

---
Tags: views, rules
---


title: Custom template for media

text:
# Question
Title: Custom template for media
I am using media module and using it in WYSIWYG. Is it possible to customize the display of media image? Is there any template file I can rewrite or any hook to call? I found file\_entity.tpl.php. but it doesn't seem the correct one. Please suggest.

Thanks

# Answer
Credit for most of this answer to this article: http://forumone.com/insights/styling-inline-images-with-drupals-wysiwyg-and-media-modules/ First I went and edited the relevant displays and added a caption field (which is what I was trying to do)

Then used hook\_media\_wysiwyg\_token\_to\_markup\_alter() to change the output, in my case I needed to catch the situation where the image got floated in the WYSIWYG, and float the parent element rather.

```
<?php
function MODULENAME_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
    if (($element['content']['#bundle'] == 'image')) {
        // check if a caption has been set
        if(!empty($element['content']['field_caption'])){
            if(isset($element['content']['file']['#attributes']['style']) && strstr($element['content']['file']['#attributes']['style'], 'float')){
                // move floats to the wrapping element
                $element['content']['#attributes']['style'] = $element['content']['file']['#attributes']['style'];
                // remove inline style on image
                $element['content']['file']['#item']['attributes']['style'] = '';
                // add class to wrapping element so we can style it
                $element['content']['#attributes']['class'][] = 'media-with-caption';
            }
        }
    }
}

```
> 2 votes

---
Tags: 7, hooks, theming, wysiwyg, media
---


title: I've created a Webform. Whats next?

text:
# Question
Title: I've created a Webform. Whats next?
I am completely new to Drupal. And I would really appreciate if someone could help me out here.

I used the "WebForm" module, and created a form. The data went into the database perfectly fine, as it appears under the results page.

Lets assume that this is a "Contact Us" form, that looks like this

Name: ***_*\__*_*\__*_***

Subject: ***_*\__*_*\____**

Message: ***_*\__*_*\__**

3 labels, 3 input fields. Easy enough.

I am trying to create a table for all users to see.

Name | Subject | Message

user1 | Hello | Thank you for helping me out

user2 | Goodbye | Drupal is great

If I were to use raw php, I would essentially be writing a SQL statement to Select all the data from the database, and use a For loop to generate these data into the table.

But how do I do this in Drupal? It seems impossible, and I cant seem to find 1 relevant documentation to generate this result.

Is there a webform extension that does this? Or am I expected to create a view to generate these data? If so, how?

Any help would be greatly appreciated.

# Answer
He Hui,

Currently the webform module does not provide integration of its submissions data with the views module. You can see the status of this issue here: http://drupal.org/node/680386. There is plenty of interest and work on the issue, but it is not functionality that currently exists. By default, the only fields views will let you get to for the submissions are the sid, date created and a few others, but you can't get to the actual fields.

You can actually use additional modules to get to your webform submissions data in a round-about way, and there is lots of information online from folks who have made it work. For Drupal 7, here is a sample post with instructions: http://drupal.org/node/1658784. As you can see, you'll need three additional modules to get that functionality!

Hope this helps.
> 2 votes

# Answer
When you have your webform in place the submissions will be shown under /node/YOUR-NODE-ID/webform-results. The table view you describe is a feature available under /node/YOUR-NODE-ID/webform-results/table.

You can also go to the node, click Results and then Table to view the same page.
> 0 votes

# Answer
You can make use of webform\_get\_submissions and retrieve all your submissions in your code and then subsequently make use of the hook\_theme as shown in this comment to render out your table.
> 0 votes

---
Tags: 7, views, forms, webforms
---


# Question
Title: Problem with using a taxonomy and taxonomy term referece field to organize my site content
I have created a taxonomy called category in order to organize my website with Drupal 7.

I have tier 2s like cómo-aprender-inglés (how to learn English). If I create a basic page and select cómo aprender inglés as the term reference I create the following node `http://www.brays.es/es/cómo-aprender-inglés/cómo-aprender-inglés`. However, I would like the node to appear as `http://www.brays.es/es/cómo-aprender-inglés`. Is this possible?

At the moment:

1. I am hiding the node title so that a user navigating the site cannot access the full node view (cómo-aprender-inglés/cómo-aprender-inglés).
2. I have prevented that URL from being picked up by search engines by selecting this option in the Metatag module. I think my solution is a bit messy and I don't think it is the best option. What can I do?

Thanks in advance.

# Answer
> 0 votes
When you want to automatically generate paths for nodes/taxonomies, using a specific 'pattern', the module Pathauto is the way to go.

By using the token of the selected/entered taxonomy term on the node, you can create the requested URL.

---
Tags: taxonomy-terms
---


# Question
Title: Is there an AJAX command I can use to debug PHP variables without breaking AJAX call?
I know the list of Ajax framework commands. Every one of them is doing something useful. But sometimes I want, for debug, include a piece of debug data in my AJAX response. I want it to be unobtrusive, so `var_dump` is out. I need to wrap my debug data in some kind of command. On the other hand, I will view it using JS console, so I don't want it to actually change anything on my page. And changing something hidden with CSS is not feasible - I'm not in charge of CSS here. So it leaves me with commands approach.

Which command could I use for this purpose?

I was thinking about `ajax_command_append` with selector that will never be found, but I don't want to introduce any additional errors in my JavaScript Console.

Debugging it with xdebug is not, currently, possible, and I would rather avoid spending time and resources on creating VM, when what I need is something I can do with simple `var_dump` on non-AJAX pages.

# Answer
As far as I know, there isn't such logging or "nulling" Ajax command. That doesn't mean you can't build any! I for example, have created some custom Ajax commands, and also a `eval()` so I can run some quick codes.

**1: Define the JS action**

You need to add a new JS file, or merge as necessary. Note this `document.ready` event is important (this is just the definition, so no need to be a `behavior`).

```
(function($){
    $(function() {
        Drupal.ajax.prototype.commands.js_eval = function(ajax, data, status) {
            eval(data.script);
        };
        Drupal.ajax.prototype.commands.console_log = function(ajax, data, status) {
            console.log(data.var);
        };
    });
})(jQuery);

```

**2: The Ajax render array**

Assuming you are aware of the `ajax_render()` and JS renderable arrays, it's time to create your own custom command.

```
function mymodule_ajax_command_js_eval($script) {
  return array(
    'command' => 'js_eval',
    'script' => $script,
    'my_custom' => 'my custom value',
  );
}
function mymodule_ajax_command_console_log(&$var) {
  return array(
    'command' => 'console_log',
    'var' => $var,
  );
}

```

Above PHP function is not really a hook, and can be any name you want. For the sake of convention, I'm using `ajax_command` in the function name. In the return array, `command` will be called from `Drupal.ajax.prototype.commands` scope. You can pass additional variables, and they will be in the `data` for JS to access (`data.my_custom`, `data.script`, likewise.)

**3: Now call it!**

Now that you have the JS and PHP ends, time to call the function!

```
$output = array();
// $output[] = ajax_command_append('#some_random_id_that_you_d_normally_use', $html);
$output[] = mymodule_ajax_command_js_eval("alert('Big Bang Theory S8!)");
$output[] = mymodule_ajax_command_console_log($stuff_you_d_normally_dpm);

print ajax_render($output);
exit;

```
> 2 votes

---
Tags: 7, ajax, debugging
---


title: embed boostrap into another theme

text:
# Question
Title: embed boostrap into another theme
could someone answer this question for me please

I will sound a bit simple, but if you'd had the past week, actually two weeks, that I've had with this client, you would understand.. so here is the simple question, can I incorporate bootstraps features into a preset, non-responsive theme. here are the details took on new client who has a site where the front-end was not completed. They have a custom app that they are basically encasing in drupal. It's a codeIgniter custom application and they got all of that working inside of drupal so it looks like it was drupal created instead of outside/external application; and the theme chosen for for the site is the Business theme \[can be found here: \].

Here is where I come in-- once they got their custom app and drupal to play together, they starting looking into all the other features of drupal itself and decided to move their entire company site into drupal. Now, I don't know why the original developers didn't pick a responsive theme to work with, assuming they were trying to find something simple that would wrap nicely around this custom app, anyway, in discussions, I can tell, no, I know, the client is going to want the cool responsive "stuff" that comes with bootstrap and with drupal the obvious choice is bootstrap theme.

Since I am just starting the job and am not a themer, more a programmer, I don't want to risk just dumping/disabling the "Business theme", installing and setting up Bootstrap, then configuring it to work around this custom app, I want to know -- can I install bootstrap, the library, not the theme, and then use it in my site as needed, it, along with views\_bootstrap, carousel\_bootstrap.. all the bootstrap stuff? Seems like the answer would be yes, but again, you just don't know what these last two weeks have been like moving stuff from one server to another.

so here is what, on a very high level, I am thinking I'll need to do in the not too distant future, create new pages/nodes, add panels, views, etc and I want to be able to use bootstrap with these.. Of course I know you can almost literally do anything, but want to know how feasible and will anything blowup in my face later going this route

# Answer
Here is what i ended up doing and it is working, but the true answer will be to strip out this original theme and start it from scratch with bootstrap, but due the time constraints, that is not an option right now, so what I did was: Each page/node that you create, includes a unique class name, in addition to the class drupal provides, I created one or two more and each page that I created, I referenced it in my stylesheet, thus forcing my other pages to use the style I wanted.
> 0 votes

---
Tags: bootstrapping
---


# Question
Title: Converting existing autocomplete field to custom Drupal field
I have an existing autocomplete field outside of Drupal that uses jQuery UI's autocomplete functionality and makes a call to a custom PHP script to parse the input and return formatted data as JSONP. I need to migrate this field to Drupal.

I've created a custom field module, but I can't figure out how to bind the JS functions if the field allows multiple values. At the moment, I have the IDs of the HTML elements I need to use set with the name-'.$delta.' to append the delta to the ID name. Is there a way to bind JS functionality to a field in Drupal like a custom field behavior call or will I need to create a function in my JS to manipulate the ID and extract the delta that way?

I need one function to run when the field is presented as a widget (node/edit), and a different function to run when the field is presented as a formatter (node/view).

Also, is there a hook to tell Drupal about my JSON service PHP file, or do I just drop it in an includes folder in my module and link to it from my JS file?

# Answer
> 0 votes
I ended up solving this by using hook\_menu() to create an AJAX tie-in with a custom callback function and then tied the form field to the AJAX path with 'autocomplete path' =\> '/...' in the field parameters. No need for any custom JS to make it work.

---
Tags: entities, ajax, javascript
---


# Question
Title: How to know the "name" of an input field of a commerce checkout form?
I need to find the name of an input field of a commerce checkout form to use in:

```
form_set_error('NAME-HERE', t('Field cannot be left blank'));

```

The html of the field is:

```
<div class="field-type-text field-name-field-cif-nif-id field-widget-text-textfield form-wrapper" id="edit-customer-profile-billing-field-cif-nif-id">
    <div id="customer-profile-billing-field-cif-nif-id-add-more-wrapper">
        <div class="form-item form-type-textfield form-item-customer-profile-billing-field-cif-nif-id-und-0-value">
             <label for="edit-customer-profile-billing-field-cif-nif-id-und-0-value">CIF/NIF/ID <span class="form-required">*</span></label>
             <input class="text-full form-text" type="text" id="edit-customer-profile-billing-field-cif-nif-id-und-0-value" name="customer_profile_billing[field_cif_nif_id][und][0][value]" value="" size="20" maxlength="20">
        </div>
    </div>
</div>

```

I tried with all of these, but it didn't work.

```
customer_profile_billing[field_cif_nif_id][und][0][value]

customer_profile_billing_field_cif_nif_id_und_0_value

customer_profile_billing-field_cif_nif_id-und-0-value

customer-profile-billing-field-cif-nif-id-und-0-value

customer_profile_billing_field_cif_nif_id

```

If I use

```
dpm($form_state['values']);

```

I get this:

# Answer
> 2 votes
Give a try to this:

> form\_set\_error('customer\_profile\_billing\]\[field\_cif\_nif\_id', t('This field failed validation'));

---
Tags: forms, commerce
---


# Question
Title: Multiple aliased pages for same taxonomy term (e.g. blog/term1 and images/term1)
I have some taxonomy vocabularies that are used on different content types (blog posts, images, businesses etc.).

I want to create a main page for each content type listing, and filter those listings by taxonomy terms, creating multiple aliased pages.

For example:

1. BLOG:

* main blog page listing all blog posts and some related blocks @ /blog
    * blog sub-pages for each vocabulary/term listing blog posts with that term @ /blog/vocabulary/term
2. ACTIVITIES:

* main page listing all businesses @ /activities
    * activities sub-pages for each vocabulary/term applied to the businesses @activies/vocabulary/term

The problem I am having is to have aliases and metatags set automatically using the taxonomy data.

I would like "content-type/vocabulary/term" (not "vocabulary/term/content-type"), and to still be able to use "vocabulary/term" (default Views or Panels taxonomy term templates) as general pages listing all content types.

Is this possibile?

# Answer
> 1 votes
The problem with dynamically creating every page is with the "content type", Drupal does not support dynamic arguments (wildcards) as the first part of a path, so there really isn't much you can do about that.

But let's approach it a little different, actually you should be able to use the taxonomy view that comes disabled with views by default to achieve what you are looking for, I would create a new page and:

* enable it
* create a contextual filter "Content: Type"
* add relationship "Content: Taxonomy terms on node" and require it
* add contextual filter "Taxonomy vocabulary: Machine name" using the relationship
* rearrange the contextual filters: "content type", "vocabulary", "term id(with depth)", term id("depth modifier")
* edit "Content: Has taxonomy term ID (with depth)", in the section for "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" change "Filter Value Type" to "term name"
* edit the path for the page (browse/%/%/%)

save your view and that should do it.

Again, remember that we can't use a dynamic path argument as the first part of a path in drupal which is why I added "browse".

---
Tags: views, taxonomy-terms, panels, path-aliases
---


# Question
Title: How can I build the results of a view in code then send them to the view?
Say I have a content type, nodes, that I want to serve through a view.

The problem is, the results are based on a series of complex requirements and conditions that aren't easily controlled through the Views UI. That is, I would like to determine which nodes to output in the view in code - is there a hook I can use to effectively build up the results, which are then fed through to the 'dumb' view?

In this way, I can do all my complex querying and calculations in code, then simply provide an array or similar of objects that the view will treat as its results, and simply spit them out?

EDIT: This doesn't necessarily have to be mediated through views, it's just I can't build the query I want in views easily because it's got a lot of moving parts.

# Answer
> 0 votes
Use `hook_views_query_alter()`.

> Alter the query before executing the query.
>
> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified

---
Tags: 7, views
---


# Question
Title: How to translate field collection which has unlimited values?
My configuration: latest dev entity translation and field collection module + patch.

I tried:

**1.** Entity translation is on just for taxonomy term and node, but not for field collection (it triggers notice: not translatable because of valid base path...) I have taxonomy term with field collection (unlimited value). In FC field there are just two fields that needs to be translated. FC and fields inside FC have set "enable field translation by users".

With these settings I can create a term, set values to FC fields on default language and save. Then I can translate and set values to FC fields for second language and save. All good when checking if it did saved 2 different values - each for own language. Then I create view which is used on panels and is using termID as context filter. View has relationship on FC field and I added FC fields to show. **What happens:** on view when I preview with term ID (context filter) I get correct result for the language in URL (en/admin/structure/views..). Also when I change URL to another language prefix I get translated fields in that language. But translated fields don't show on actual term pages.

**2.** Beside what I described in 1, I also enable entity translation for field collection. Notice about valid base path is still there, but I applied patch and i don't get errors when adding or translating FC.

With this configuration I create fresh FC with new fields and enable field translation for all of them. On term I set some values for FC fields and save it. I repeat this step when translating. But when I save translations and open them they are empty. On the next fill they remain. But the view for this configuration is still not showing right values for selected languages.

Does anyone have any hint what I am doing wrong? I really need to fix this issue on my site and I am short on time.

## What I need is to translate FC field (and it's fields) which can have unlimited values.

# Answer
> 0 votes
I think that I found a workaround for this problem. Check my post at drupal.org.

# Answer
> 0 votes
Field Collection is under development and there are still some issues to fix. Obne of those is related to this:

Field Collection: Field translation (entity\_translation) support

Although the issue is wider than your question your issue is included and is one of the errors that must be fixed before closing the issue.

---
Tags: i18n-l10n, entities
---


# Question
Title: Date field in view Filter Criteria, where date may be blank
I have a date field attached to a content type and it's not a required field. I want to use this date to control the display of the content using a view and it's filter criteria.

Some content may have blank dates and some may have a start and end date.

Is there a way I can set up the view to check for all of these conditions?

* content is published
* AND content type is TYPE
* AND Start date is blank OR Start date is not blank AND start date is \<= NOW
* AND End date is blank OR End date is not blank AND end date \>= NOW

# Answer
The conditions I had set above were too many

* content is published
* AND content type is TYPE
* AND Start date is blank OR Start date is not blank AND start date is \<= NOW
* AND End date is blank OR End date is not blank AND end date \>= NOW

and should have been:

* content is published
* AND content type is TYPE
* AND Start date is blank OR start date is \<= NOW
* AND End date is blank OR end date \>= NOW

because the NOT blank is implied.

Using the 'And/Or, Rearrange' feature of the Filter Criteria, I was able to create 3 groups joined by AND's with Group 2 and 3 joined by OR's. Like so:
> 2 votes

---
Tags: views, datetime
---


# Question
Title: How to restrict completion of only one field within a field group
Is there a simple way to have several fields within a field group; such a way that only one field in the group can be populated.

**Example use Case** Field group is called 'Insert Media'.

The group contains \- an image field \- an audio field \- a video field

The user may complete one field, but can not complete multiple fields within the group.

# Answer
I have not expressly done the exact use case you've requested. I recommend you look at the following blog post describing the Drupal States API, including newer additions made to that API for `OR`ing and `XOR`ing conditions:

http://www.metaltoad.com/blog/drupal-7-form-api-using-states-multiple-conditionals-and-or-and-xor

For simple multiple-condition clauses the States API follows this convention:

```
'[field-selector]' => array('[evaluate]'),
'[field-selector2]' => array('[evaluate]'),

```

For more complex conditional logic you can write the following array structure:

```
array('[field-selector]' => array('[evaluate]')),
'[OR/XOR]',
array('[field-selector2]' => array('[evaluate]')),

```

Be aware that the version of jQuery being used on your site could be important for these conditionals to work (again see the blog post).

If the above does not meet your needs I recommend you look at the Field Conditional States module:

> The working states that are supported by FCS are:
>
> * visible / invisible - Hides/Shows a form element
> * enabled / disabled - Grays out a form element
> * required / optional - Makes a form element required to be able to submit the form
> * checked / unchecked - Checks/Unchecks a checkbox (of course only applicable to checkboxes)
>
> Fields to which these states will be applied, are called target fields or controled fields.
>
> To trigger these states there is a different set of trigger states (not to be confused with the states described above) that will trigger a state when applied to a control field:
>
> * empty - Triggers when the control field is empty
> * filled - Triggers when the control field is not empty
> * checked - Triggers when the control field is checked
> * unchecked - Triggers when the control field is not checked
> * value - Triggers when the control field's value is equal to a given string
> * !value - Triggers when the control field's value is NOT equal to a given string
>
> All of them are supported as long as they make any sense for the widget of the used control field. For example it doesn't make any sense to wait for a text field to be checked or for a checkbox to have the value "Hello World". So most (if not all) fields will only use a subset of these trigger states.

**Note:** that the states api and the field condition module are clientside modules -- they don't enforce the validation on the server. You'll likely also want to use a custom form validation function to assure that only 1 field is provided upon form submission.
> 1 votes

---
Tags: entities
---


# Question
Title: Set default frontpage to Front Page view
I've setted the Default front page to the View Front Page, but when I go to www.mydomain.com the page don't redirects to www.mydomain.com/frontpage.

When I go and write www.mydomain.com/frontpage the Front Page view is displayed.

What is going wrong?

# Answer
> 0 votes
you need to set it here:

http://www.DOMAIN.com/admin/config/system/site-information

You set the "Default Front Page Link" there.

When you hit your root (/) url, it will not "redirect" to that custom url you set, but it will auto render the url you inputted.

If you want to do a true redirect when hitting the frontpage you might have to do it via the .htaccess file as I'm not sure if there is module that can do a redirect from the frontpage.

---
Tags: views
---


# Question
Title: Drush pm-disable needs a higher bootstrap level to run
I keep having this periodic issue with the pm-disable (amongst other) commands in Drush. I have kicked the tires on configuring Drush -- I have the datbase connect set to 127.0.0.1, have php.ini in the ~/.drush dir, using MAMP PHP -- same results.

drush status indicates that it connects without issue. My all directory has user and group level read and write, my site directory has read level on user and group (no write). Do I need to enable different chmod settings in my homesite dir or what am I missing?

This is the pm-disable output when it fails.

```
The drush command 'dis views' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database
setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.31
 Site URI               :  http://mywellbeing.local
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database port          :  8889
 Database username      :  mydrupalsite
 Database name          :  mydrupalsite
 PHP executable         :  /Applications/MAMP/bin/php/php5.5.14/bin/php
 PHP configuration      :  /Users/cameronkilgorew/.drush/php.ini /Users/cameronkilgorew/.drush/php.ini
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/cameronkilgorew/mydrupalsite/repo
 Site path              :  sites/mydrupalsite.local

```

# Answer
> 1 votes
You're using drush 7.0-dev on php 5.5.14.

* Do you have php5-json package? That is required for php 5.5.
* Did you follow the extra instructions on github.com/drush-ops/drush related to MAMP? There's one about socket that seems relevant

# Answer
> 0 votes
From my experience this is when you're not running the drush commands from the root of the drupal install. I tend to get this error when I'm running Vagrant and I forget to `vagrant ssh` into my VM before I start trying to run drush commands.

---
Tags: drush
---


# Question
Title: CCK Date field not showing stored values in node edit form
After moving a Drupal 6.x site to a new server, I've found that a CCK date field being used by multiple content types is not displaying the values that are stored in the database for the field OR the default value as defined under content management and date field when creating a new node. The field is just blank. For stored nodes, the values are still there when viewing the node, they just disappear when editing it.

I've found two similar issues, but both relate to multilingual support in Drupal 7: 1. Why some fields values are getting empty when editing a node? 2. https://www.drupal.org/node/1146056

ANSWER: I upgraded the Date API module to 6.x-2.10 and the problem was fixed.

# Answer
> 0 votes
I'll assume you have the latest Date module version installed, 6.x-2.10. There is a similar issue in the module's queue here. Run phpinfo() and see if Memcached is installed on your new server. Uninstalling the extension could possibly solve your problem.

---
Tags: entities, nodes
---


# Question
Title: Migrate user passwords salted and hashed with md5
I have quite complex migration for some legacy non drupal site to migrate it into D7. The whole migration works fine but it turned out that source user passwords are salted and hashed with MD5. Because they are salted I can't do this in my migration class:

```
 $this->destination = new MigrateDestinationUser(array('md5_passwords' => TRUE));

```

I've found this solution which boils down to reimplementation of original hashing algorithm in new drupal site. I don't like this solution because it decreases security of the site and throws away whole D7 password hashing code.

Something tells me that the only way to migrate those old passwords and keep the drupal hashing algorithm is to copy-paste whole `includes/password.inc` and add *"temporary"* hashing algorithm from the old non-drupal site in similar way drupal core handles old MD5 passwords without salt.

Or maybe there is a better way to migrate those old passwords?

# Answer
> I don't like this solution because it decreases security of the site and throws away whole D7 password hashing code.

How does this decrease security? The D7 hashing function is pluggable, you can migrate the fields without (re)hashing them by setting `$this->md5Password = FALSE` and then using your own hash function from the legacy system, as commented on in the issue you posted:

https://www.drupal.org/node/1326450#comment-5192996

You're still using the Drupal API to perform authentication and more than likely the legacy hashing technique while not stellar is probably not brain dead.

Now, if you don't like side-stepping the default Drupal7 password semantics -- then don't. Or do it for a temporary amount of time as you mentioned and inform your users of a pending system-wide password reset. This happens alot all over the net even recently on Drupal.org.

You may force all site users todo a password reset and setup strict password enforcement using the Password Policy module:

> A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.
>
> Example: an uppercase constraint (with a parameter of 2) and a digit constraint (with a parameter of 4) means that a user password must have at least 2 uppercase letters and at least 4 digits for it to be accepted.
> 1 votes

---
Tags: 7, security, migrations, users
---


# Question
Title: Display content from mymodule_page in two regions
Is the way, to put mymodule page content in region **content**, and **sidebar** programmatically without using blocks?

ex.

```
function mymodule_page(){
    $page['content']['my'] = array(
         '#type' => 'markup',
         '#markup' => 'Test',
          ),
    $page['sidebar']['item'] = array(
          '#type' => 'markup',
          '#markup' => 'Test'
       );

 return $page;
}

```

# Answer
**No, not really, that's exactly what blocks are for.** Without blocks, your module would need to send it's content to a region. And module should never need to know what theme you are using. If you would use a theme that doe snot have region you need, you would encounter an error.

Having that said, yes, you theoretically can do it. You would need to replicate what core module Block is doing, so it is way too broad to reliably cover in an answer. You can see Block's code if you want. You will use tens or hundreds times more man-hours to get this done than if you will just create a block with default region, or you will end up with significantly less stable and reliable code, but if it is something you really, really want to try, it is not impossible.
> 0 votes

---
Tags: nodes, theming
---


title: drupal_add_js weight

text:
# Question
Title: drupal_add_js weight
I've written a javascript that for some reason whenever I run it, it removes any hover events. Since I am running my site with nice menus I would like to run my script as high up in the $script array as possible.

I added this line to the template.php:

```
drupal_add_js('sites/itascacg.com/themes/custom/icg/js/fixtitles.js',array('type' => 'file', 'weight' => -19));

```

since according to the documentation I've read jQuery itself is at weight -20, but no matter what weight I give my script i won't float any higher on the list.

does anybody have anybody have any ideas how to push my script up, or at worst push all the other scripts down?

P.S. I'm using drupal 7

# Answer
In what function in template.php are you adding this? A preprocess function I hope.

Anyway, you have to set the 'group' option as outlined on the drupal\_add\_js page. eg.

```
drupal_add_js('sites/itascacg.com/themes/custom/icg/js/fixtitles.js',array('type' => 'file', 'weight' => -19, 'group' => JS_LIBRARY));

```
> 3 votes

# Answer
`drupal_add_js` states

> **weight**: A number defining the order in which the JavaScript is added to the page relative to other JavaScript with the same 'scope', 'group', and 'every\_page' value.
>
> The exact ordering of JavaScript is as follows:
>
> 1. First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
> 2. Then by group.
> 3. Then by the 'every\_page' flag, with TRUE coming before FALSE.
> 4. Then by weight.
> 5. Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal\_add\_js() that happened later in the page request gets added to the page after one for which drupal\_add\_js() happened earlier in the page request.

Weight is at number fourth. Please update your scope, group and every\_page parameters.

Secondly try a very smaller number for weight i.e -100000. It may work for you.
> 2 votes

---
Tags: theming, javascript
---


title: Drupal Submenu on left sidebar

text:
# Question
Title: Drupal Submenu on left sidebar
I have added primary links and enable as expaned . Which is working fine for me

```
> About
>  - test1
>  - test2
>  - test3

```

Now i want when i click on about or nay test1, test2, test3 page

I want a block on left sidebar containing sub menu items

```
test1
test2
test3

```

Anybody have an idea how to do this

I am using Bootstrap 3 sub theme

Thanks

# Answer
> 2 votes
You can use Menu Block Module. It will display your menu as a block.

1) Create a new menu block.

2) Select parent menu as a "About".

3) Select its region and page visibility to about page url (and inner pages urls too if you want to display it on inner pages.)

4)Click on save.

---
Tags: views, theming
---


# Question
Title: Compare two views that present two different content type and delete nodes
this question is like this: How to delete a content in a view with view rules?

I didn't know why but i make this question with another account that i cannot got access now So the problem is: I got two views. View A and View B. View A rapresent contents of type A (30 contents for example) and view B rapresent contents of type B (30 contents for example). By comparing the various nodes contained in these two views i want to found (among the nodes contained in the view B) contents with the same title of some nodes caontained in the view A and delete them. After this operation, View A got 30 nodes and View B got 3 nodes because got 27 nodes with same title of some nodes in the View A. I try to do this in a Rule with view loop but i didn't know how to delete nodes with the same title. I try with VBO but i cannot make this process i think, cause i need to delete nodes selectively

Thanks and sorry for the duplicate post (i need to do this cause i cannot reply with old account)

# Answer
> 1 votes
You can simply achieve that by using the Remove Duplicates module.

> This module helps the administrator to easily remove duplicate nodes according to one of the node fields.

---
Tags: views, rules
---


# Question
Title: "The pdf.js library could not be found." (PDF module)
I installed pdf.js with the PDF module in an effort to show pdf on the fly on my Drupal 7 site. I keep Drupal 7 constantly upgraded on Ubuntu on an instance an AWS.

I installed the module using drush which placed the module at `sites/all/modules/pdf`. I then copied pdf.js to: `sites/all/libraries`.

After installing I have created a new content type called PDF and I added a file field that is able to only include a pdf file.

I selected the display to show: "PDF: Default viewer of PDF.js". I then added a content with a PDF file in it selected and uploaded.

While trying to show it I get the message: `The pdf.js library could not be found.` And down the page: `pdf: Please download and install pdf.js`!

Can anyone help? Where do I put the JS file? Is there a problem with the FDF module?

# Answer
The path will be like this /sites/all/libraries/pdf.js.

pdf.js is a FOLDER not a FILE. It is very strange to have a folder with a DOT in the name.

I have attached a screenshot on the folder hierarchy that works.

SUMMARY:

The folder in your libraries folder must be named: pdf.js, you will have to rename the top folder of anything you download to pdf.js (in this instance pdf.js is not a FILE, but the container of the library) See screenshot for the correct file hierarchy.
> 1 votes

---
Tags: 7, files, theming
---


# Question
Title: Is EntityFieldQuery as sophisticated as the Database API?
I was wondering if `EntityFieldQuery` is just a layer of abstraction on top of the database query builder. For example can I use `addExpression` and `isNotNull` in an `EntityFieldQuery`, for example?

Or, is it separate and not as sophisticated.

# Answer
> 4 votes
> I was wondering if EntityFieldQuery is just a layer of abstraction on top of the database query builder.

Yes, that's exactly what it is. It's not subclass of `SelectQuery` or anything higher up the chain, though.

> For example can I use addExpression and isNotNull in an EntityFieldQuery, for example?

No, EFQ doesn't implement those methods. You can see what methods are available by looking at the source.

> Or, is it separate and not as sophisticated.

Yes it's separate, "not as sophisticated" can't really apply since the functional differences between EFQ and a `SelectQuery` are intentional. They're not supposed to do the same thing, an EFQ is intentionally limited to functionality that makes sense for entities only.

However, an EFQ will eventually run a `SelectQuery` anyway, which you can alter just like any other query. So you can make it as "sophisticated" as you need to.

---
Tags: database
---


# Question
Title: Create custom signup block with mailchimp module?
I'm looking for code examples for creating *custom* mailchimp signup forms that use the mailchimp api integration provided by the mailchimp module.

Context: I have a D7 site using a standard embedded sign-up form for mailchimp. I just recently switched the site to https, which unfortunately causes some browsers (e.g. firefox) to throw a scary message when a user clicks the submit button on the sign-up form, because standard mailchimp embedded forms can only use http.

The mailchimp module uses the mailchimp API, which allows secure connections, so that's the obvious solution. And the mailchimp module automatically provides a block for each list. But the module makes assumptions that I don't want. So, instead of the automatic block provided by the mailchimp module, I'd like to create my own block(s) with a sign-up form that uses the api, so that I have more control over the look and feel of the form.

Also, I know the webform mailchimp module provides a mailchimp component for webform, (there's a good write up here) but I'd like to explore creating my own forms as a first step.

# Answer
In the end, this is what I did:

1. Installed the mailchimp module and connected drupal to a list in mailchimp using normal instructions and an API key that mailchimp provides.
2. Created a new custom module that creates and displays blocks using standard hook\_block\_info and hook\_block\_view code.
3. Created a very simple form with hook\_form, with a companion submit function, hook\_form\_submit, and add this form to the block(s) created above.
4. In hook\_form\_submit, I open a connection to the mailchimp api with:

$q = mailchimp\_get\_api\_object();

Then subscribe the user with:

```
$success = $q->listSubscribe($list_id, $email, $merge_vars, 'html', TRUE, TRUE);

```

The above functions are documented in the mailchimp api.

So, in the end, I'm not really using the Drupal mailchimp module for anything other than providing access to mailchimp api over a secure connection (the drupal site is running https). The main advantage of this approach is complete control over the look and feel of the forms that appear in the blocks, and the actions taken when a user submits.

Another advantage: Because I'm using hook\_form\_submit to control processing once the form is submitted, I can add the form location (using request\_path()) to the merge variables that are passed back to mailchimp. That way, the form is the same on every page that it appears, but the location is passed back to mailchimp as part of the sign-up process.
> 7 votes

# Answer
I did something similar to @Dave Bruns in my hook\_form\_submit but added in the mailchimp\_addto\_queue function so this gets triggered when cron runs.

```
// Connect to MailChimp API.
$q = mailchimp_get_api_object();

// Send data to our Mailchimp list for this site.
$args = array(
  'list_id' => '91919191',
  'email' => $email,
  'merge_vars' => array('fname' => 'Lee', 'lname' => 'Woods'),
  'format' => 'html',
  'double_optin' => FALSE,
  'update_existing' => TRUE,
  'replace_interests' => TRUE,
  'confirm' => TRUE,
);
mailchimp_addto_queue('mailchimp_subscribe_process', $args);

mailchimp_subscribe_process($list_id, $email, $merge_vars, $double_optin, $format, $update_existing, $replace_interests, $confirm);

```
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to add drupal contributed modules into a custom module
I've done a custom module to generate some forms. There is a image field present. I would like to add cropping functionality in image field.

I've seen that is very interesting the Imagefield Crop module. I would like to use it in my code.

So, my question is: Is there any way to add this module functionality into my image field?

**Edit 1:**

This is my code:

```
$form['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
    );

```

It is necessary for our company to generate the forms in a custom module, because we need to process data in a special way, that with drupal content type is not possible.

So, I feel totally lost. It is posible to do something like a reference or something similar to use image\_crop??

Thank you in advanced.

# Answer
> 1 votes
If any module is providing its API, than you can use its api.Image Field Crop is not providing any API so you can call any method from that module directly. Don't forgot to add contributed module name as a dependency in your custom module info file.

---
Tags: 7, entities, media
---


# Question
Title: Calculate Star rating based on webform submissions
Is there a module to calculate Average Vote based on webform submissions?

Explanations:

I have a Webform which looks like this. So when a user submits the form i need a average value to be calculated which i can show as star rating some where on another page.

Does it need a custom module ?

Any clues ? thanks

# Answer
> 1 votes
Yes. You should create a fivestar field in your webform and than create a custom module which calculate the rating and save it to a fivestar field.

---
Tags: rating
---


# Question
Title: Field collection - Delete "Remove button" on line
I need to delete the "Remove button" on every edit field collection for specific role users. I have 3 roles (Admin, Project, Test). Just Admin and project can see the "delete" button and "add" button to remove lines or add a new line. The others roles are not allowed to delete or add new line in the field collection.

I tried to change some permissions (Administer field collections - Create and delete fields on field collections.) But it didn't work...

I need to use HOOK ? or maybe just JQuery ?

To complete my explication, here an example :

Thanks

PS : "Supprimer" = "Remove"

# Answer
> 0 votes
Write following code in your theme template.php file. It will added css classes to body of a specfic page.

```
    <?php

    function hook_preprocess_html(&$variables) {
      global $user;
      $args = arg();

        if( isset($args[0]) && ($args[0] ==  'your-page-url-first-argument')){ // Check ur page url parameters
        $account = user_load($user->uid);
        if(in_array("test", $account->roles)){
          $variables['classes_array'][] = 'test_user';
        }
      }?>

```

CSS:

```
.test_user [remove_button_class/id] {

  display:none

}

```

---
Tags: users, entities
---


title: Where are list_text conversions stored?

text:
# Question
Title: Where are list_text conversions stored?
I have a field in a content type that is a list\_text with a key/value pair where the key is stored in the database and the value is the text visible in the drop down menu.

I imported a large amount of data. When I look at the data in a view or view a node, the key shows up. However, after I edit the node, whether I've made changes or not, the value starts appearing in the view and in the node. I would like this to be the case for every node, but can't possibly go though and manually edit each node.

Can anyone tell me where in the database the info that tells Drupal to use the translate the key to its value is stored?

# Answer
> 0 votes
The Field CRUD API could be a better approach instead of handmade DB calls.

If you must: Field creats two DB tables for every field they are called field\_data\_field\_fieldname and field\_revision\_fieldname. The contents depends on the field type.

# Answer
> 0 votes
If you mean where the translations are stored, the tables are

locales\_source locales\_target

---
Tags: database, nodes
---