# Question
Title: Importing content from non-drupal database - help with SQL please
I have a website with guitar lessons that I am converting to drupal. I am new to drupal and have started getting familiar over the past few days. I created a content type for lessons and exercises, established categories via taxonomy, used Entity Reference to relate exercises and lessons (lessons can contain exercises or exercises can stand on their own) and created fields for exercises such as audio, video.

I now see that in the database there is no way to view lesson and exercise content as a whole. Everything is done via the node and field tables, and entity relations are through additional tables that I haven't discerned yet.

This database structure is making it hard for me to import all my lesson and exercise data, since in my previous site all fields associated with a lesson or exercise are in a corresponding lesson or exercise table.

I understand the drupal structure allows more power, and from reading this post about content types and database seems I would be crazy to expect to create a database table for my lessons and exercises. So then, how would I create SQL queries in drupal to perform the following task?

"Insert into the drupal structure a lesson content node, that is from a given category, that contains various fields I created in drupal, which have one-to-one relation to the fields in my source database table?"

Likewise, to get exercises squared away, how would I

"Insert into the drupal structure an exercise content node, that is from a given category, that is tied to a given lesson, that contains various fields, mapped one-to-one from source database to fields I created in drupal?"

I am really at a loss for how to compose the SQL. Any tips are vastly appreciated!

Regards

EDIT: here is the script I wrote, which seems to be populating everything as needed, but something is still missing...

EDIT2: I was missing some tables, so below is everything I did to import. Things seem to work but I have no idea if there is some other obscure setting I missed...

EDIT3: while the below worked, I ended up following the advice in the answers and used the API according to this post about adding nodes programmatically and this one which specifically talks about adding nodes with Entity Reference field. I then manually updated the node\_counter table because I wasn't sure how to do that via the API.

```
$pnuke = db_query("SELECT * FROM nuke_guitarlessons_guitarlessons WHERE 1");

$cids = array(8,10,11,13,14); // ignore these lesson categories
$catmap=array(); // this maps old cat ids to the taxonomy term ids
$catmap[] = 7;$catmap[] = 0;$catmap[] = 1;$catmap[] = 9;$catmap[] = 6;$catmap[] = 2;$catmap[] = 8;$catmap[] = 0;$catmap[] = 0;$catmap[] = 0;$catmap[] = 0;$catmap[] = 10;

db_set_active();

$lastid=4; // this just ensures that node ids are incremented as I want
while ($n = $pnuke->fetchAssoc()) {
    if (!in_array($n['cid'], $cids)) {
    $datets = strtotime($n['date']);
    $datenow = new DateTime();

    $title = $n['title'];

    db_insert('node')
    ->fields(array('vid' => $lastid+1, 'type' => 'lesson', 'language' => 'und', 'title' => $title, 'uid' => 1, 'status' => 1, 'created' => $datets, 'changed' => $datets, 'comment' => 0, 'promote' => 1, 'sticky' => 0, 'tnid' => 0, 'translate' => 0))
    ->execute();

    db_insert('node_revision')
    ->fields(array('nid' => $lastid+1, 'vid' => $lastid+1, 'uid' => 1, 'title' => $title, 'log' => '', 'timestamp' => $datenow->getTimestamp(), 'status' => 1, 'comment' => 0, 'promote' => 1, 'sticky' => 0))
    ->execute();

    db_insert('field_data_body')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'body_value' => $n['introtext'], 'body_summary' => '', 'body_format' => 'full_html'))
    ->execute();

    db_insert('field_revision_body')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'body_value' => $n['introtext'], 'body_summary' => '', 'body_format' => 'full_html'))
     ->execute();

    db_insert('field_data_field_lessonintro')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'field_lessonintro_value' => $n['description'], 'field_lessonintro_format' => 'full_html'))
    ->execute();

    db_insert('field_revision_field_lessonintro')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'field_lessonintro_value' => $n['description'], 'field_lessonintro_format' => 'full_html'))
    ->execute();

    db_insert('node_counter')
    ->fields(array('nid' => $lastid+1, 'totalcount' => (int)$n['hits'], 'daycount' => 1, 'timestamp' => $datenow->getTimestamp()))
    ->execute();

    db_insert('taxonomy_index')
    ->fields(array('nid' => $lastid+1, 'tid' => $catmap[(int)($n['cid']-1)], 'sticky' => 0, 'created' => $datets))
    ->execute();

    db_insert('field_data_field_category')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'field_category_tid' => $catmap[(int)($n['cid']-1)]))
    ->execute();

    db_insert('field_revision_field_category')
    ->fields(array('entity_type' => 'node', 'bundle' => 'lesson', 'deleted' => 0, 'entity_id' => $lastid+1, 'revision_id' => $lastid+1, 'language' => 'und', 'delta' => 0, 'field_category_tid' => $catmap[(int)($n['cid']-1)]))
    ->execute();

 $lastid++;
  }
}

```

# Answer
I would recommend trying the Migrate module. It's a bit harder to implement compared to a direct approach but much cleaner, too.

> The migrate module provides a flexible framework for migrating content into Drupal from other sources.

To get started you can check the documentation and more specifically the examples that the module comes with. I think the "beer.inc" one mostly covers migrating SQL tables to Drupal.

The concept of the module is that you define a mapping between a source and a Drupal destination and then you can import the data or rollback them in case something didn't work. There is also a UI to help you keep track of your Migration classes/settings.
> 1 votes

# Answer
You could use the Feeds module to import the content from that other database, similar to what is shown in this video tutorial, which shows how to import data as Drupal nodes.
> 0 votes

---
Tags: taxonomy-terms, entities, database, importing-exporting
---


# Question
Title: How to hook into access control of node/add menu handler?
Looking at Drupal code, I noticed the following function.

```
function _node_add_access() {
  $types = node_type_get_types();
  foreach ($types as $type) {
    if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
      return TRUE;
    }
  }
  if (user_access('administer content types')) {
    // There are no content types defined that the user has permission to create,
    // but the user does have the permission to administer the content types, so
    // grant them access to the page anyway.
    return TRUE;
  }
  return FALSE;
}

```

What is `node_hook()`? How can I implement this hook for additional access control?

# Answer
`node_hook()` is not an hook; it's a helper function Drupal uses to verify a content-type hook exists. In the code you are showing, the function is verifying the module implementing the `$type->type` content type implements `hook_form()`.

To alter the access control for a node, you have two options:

Implementing `hook_node_access()` is easier, but that hook is not used in node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.).

Notice that, since `_node_add_access()` is an access callback, you could change the access callback used by node/add. I suggest not doing it because that would by-pass all the node access control implemented by Drupal.

### Reference
> 0 votes

---
Tags: 7, nodes, hooks
---


title: How do I sell tickets?

text:
# Question
Title: How do I sell tickets?
I started a project that required me to create a site selling tickets to a nightclub for special events.

People attending the event must be able to buy a ticket or multiple tickets, and add a ticket holders name for each ticket. They are then sent a confirmation e-mail with their tickets attached as individual tickets with bar codes.

* I tried Ticket but this did not integrate with commerce as easily as I had liked.
* I tried the COD distribution which has ticket installed, and their own custom module to link it to commerce. However, I personally don't like distributions. I find they have too much un-needed stuff with them, and I don't like waiting on them to update core when security updates are needed.
* I also tried the Commerce Tickets module, which looked promising, but the ticket holder name data was not easily accessible, or available in views. As well as a series of bugs, and a maintainer who seemed non existent, this didnt seem like an option either.
* I also tried Commerce Booking but that didnt do what I wanted it to, and if the cart module is enabled a lot of errors are generated

Therefore I determined my only option was to create the functionality myself, hopefully using only contributed modules, and not too much custom stuff. I am posting an immediate answer to provide help for anyone in the same situation. I am not looking for other answers to this question unless you have something really cool to share!

# Answer
> 17 votes
Here is the method I used. It covered all of the functionality I needed, and we ended up with a very robust website, using popular well maintained modules, and getting the exact results we needed.

**Modules used**

1. Commerce
2. Commerce\_agree\_terms
3. Commerce\_autosku
4. Commerce\_cart\_expiration
5. Commerce\_event\_ticket (For PDF creation)
6. Commerce\_stock
7. Date API
8. Inline Entity Form
9. Rules
10. Views

These were the main ones. There are also modules these rely on, and others I used for other purposes. But I am trying to keep this to the ticket functionality only, rather than explain how to build an entire site.

**Method**

1. Enable all modules.
2. Create a commerce product called "Ticket" (Or re-name the default enabled product).
3. Manage the fields on the "Ticket" content type, and add a date field called "booking window". This should collect a start and end date, and will allow an admin to define when these tickets are available for sale.
4. Enable Commerce Stock on the Ticket Product to allow an admin to define the amount of tickets available for each ticket.
5. Create a content type called "Event".
6. Add an In-line Entity field allowing the user to create new products (Tickets). Allow unlimited values on this field if you wish (This allows a user to add an Early Bird Ticket, Standard, VIP etc.). We also disable "Allow a user to add existing products" as we want unique products to be created for every event. This is where the autosku module comes in handy for auto generation.
7. Add a date field for the event date.

*Once that is done, you have the basic functionality. You can create an "Event" node, add a ticket or multiple tickets (defining price, stock and booking window), add your event date and click save.*

**Next Steps**

1. Next you will need to manage the display for the content type "Event" and hide the display of the tickets field.
2. Create a new view Block Display called "Ticket Display" for products. Add a field to show products (Tickets) as an add to cart form.
3. Add a contextual filter "nid" and set the default value as "get content ID from URL".
4. Add a filter to the view for the product (Tickets) booking window start date and use relative date "now" to only show products with a start date less than "now" and another filter with end date greater than "now".
5. Go to structure \> blocks, find your view block display, and restrict the block to only show on "event" content types. This will now mean the tickets only show on their referenced nodes, and only if the booking window is open. They will also be disabled if out of stock.

**Adding a ticket holders names**

1. Manage the fields of the line items. Store \> Configuration \> Line item types \> Product (Ticket) \> Manage fields. Add a field for "Ticket holders name".
2. On the "Ticket holders name" field settings, make sure you select "Include this field on Add to Cart forms for line items of this type".

**Sending tickets to customers**

1. After enabling the commerce event ticket module, follow the modules instructions to generate a PDF for every ticket product.

For a full working demo of this, look here.. http://www.dev.thelhp.co.uk/ Please note this site is in development for now, but will try and charge you when it goes live!

# Answer
> 1 votes
I think you should consider adding 2 more modules to the list of modules you used, i.e. the Flag and Message modules. These modules would allow you to implement, with hardly any extra effort, additional features such as:

* Bookmarking of events (by each user).
* Something similar to a "like" button.
* I'm interested in receiving more info about a specific event.
* Keep me informed about similar events in the future.
* Etc.

I bet your sales/marketing people would really like to know which kinds of events have been "flagged" by which users, or all sorts of statistics about these events.

**Note**: both modules integrate very well with the Rules module also.

# Answer
> 0 votes
**Check out these modules :**

commerce\_booking

> This module provides tools to use Drupal Commerce as a powerful event booking system. Any entity can be an 'event' and a single booking can contain any number of tickets.

commerce\_event\_ticket

> Commerce Event Ticket automatically creates 'ticket' entities when customers purchase products in a Drupal Commerce store. There are submodules for creating ticket PDFs, and for validating tickets via a REST API.
>
> A separate ticket is created for every unit purchased. In other words, the number of tickets is equal to the line item quantity.
>
> Each ticket has a unique, random barcode.

---
Tags: commerce
---


# Question
Title: How do I figure out what module is using drupal_set_message()?
Some module is using `drupal_set_message()` to show a message at the top of the administrative pages.

I would like to figure out from where it is coming from. Is there any way to determine what module is creating it? How do I remove it?

# Answer
> 0 votes
Are there any messages in your error log? You should be able to see a module name there.

drupal\_set\_message has no parameter to add a module name to the message so there is no straight forward method of finding the module. You could copy the string from the message and search in the translation page (if you have the locale module enabled. Or throw the string at Google and see what you find. That usually helps!

# Answer
> 0 votes
Is the node the only thing that it's logging out? If that's the case then it may be hard to find out which module is outputting it. If not then I would suggest what rtome says in the comment, although slightly modified.

If you SSH into the root of your drupal install, and run "`find . -exec grep 'yourtexthere' {} \; -print`" then it will search every file for that line of text and print out which files have it.

If the node is the only thing being printed, however, then you may do better to disable the modules one by one (or several at a time) until the message goes away.

(btw watchdog and drupal\_set\_message are not the same thing. Watchdog is what is logged to through the command watchdog() and which you can find in admin/reports/dblog)

# Answer
> 0 votes
If you are asking to edit out the code calling `drupal_set_message()` from that module, I would rather suggest not doing it.
Disabling some messages is easy as installing the Disable Messages module, and setting it up. The module is described as follows:

> Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal\_set\_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.
>
> ### Features
>
> * Filter out messages that match a full text string exactly.
> * Filter out messages that match a regular expression.
> * Permissions to specifically hide all messages of a given type from any role.
> * Disable all filtering for specific users.
> * Disable all filtering for specific paths.
> * Apply filtering only for specific paths.
> * Debug system to get messages in the HTML without showing it to the end users.

---
Tags: 7
---


# Question
Title: Table not rendered using ajax_render in ctools modal window
This is a continuation from this question,where I'm wanting to display a form for searching Apache Solr and displaying the results with a pager. I've modified my approach to have the search run from the page function if there are values in the form. As I have it now, the search is run and results are returned just fine, but for some reason I can't get the table to render when I pass a render array through ajax\_render(). Here's the relevant code:

```
/**
 * Page callback for imgsearch modal popup window.
 */
function imgsearch_page($ajax, $id, $a, $b) {
  if ($ajax) {
    //Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Image Search Form'),
      'next_field_id' => $id,
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $search_form = ctools_modal_form_wrapper('imgsearch_form', $form_state);
    if ($search_form[0]) {
      $output = $search_form;
    }
    else {
      $build['search_form'] = $search_form;
    }
    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    if($form_state['values']['search_terms'] != '') {
      // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
      $results = nb_image_search_search($form_state['values']);

      if (is_array($results['images']) && count($results['images'] > 0)) {
        $next_field_id = $form_state['next_field_id'];
        // Create object to store file and target field info. To be stored in ctools cache.
        $file_info = new stdClass();
        // Generate the field name.  field_images is a multivalue field collection, so we just need the next available option
        // in the $field_images['und'] array. The second number (for field_image) will always be 0 since it
        // is a single value field.
        $file_info->fieldname['url'] = '#edit-field-images-und-' . $next_field_id . '-field-image-und-0-imgsearch-file-url';
        $file_info->fieldname['person'] = '#edit-field-images-und-' . $next_field_id . '-field-person-und-0-value';
        $file_info->fieldname['organization'] = '#edit-field-images-und-' . $next_field_id . '-field-organization-und-0-value';
        $file_info->fieldname['year'] = '#edit-field-images-und-' . $next_field_id . '-field-year-und-0-value';

        $file_info->fids = array();

        // Theme the results as a table.
        $header = array(t('Image'), t('File Name'), t('Add to field'));
        $rows = array();
        foreach ($results['images'] as $image) {
          // Create image style derivative for each image.
          $imagestyle = array(
            'style_name' => 'thumbnail',
            'path' => $image['filepath'] . $image['filename'],
            'width' => '',
            'height' => '',
            'alt' => '',
            'title' => $image['filename'],
          );
          $styled_image = theme('image_style', $imagestyle);
          $fid = $image['fid'];

          $rows[] = array(
            'image' => $styled_image,
            'name' => $image['filename'],
            'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $next_field_id, t('Select')),
          );

          $file_info->fids[$fid] = $image['filename'];

          // Cache values for Person, Organization, and Year if they exist.
          foreach (array('person', 'organization', 'year') as $field) {
            if (isset($image[$field])) {
              $file_info->meta[$fid][$field] = $image[$field];
            }
          }
        }
        //Cache image name in ctools object cache so it can be used later in nb_image_search_image_add()
        ctools_include('object-cache');
        ctools_object_cache_set('imgsearch', 'imgsearch_' . $next_field_id, $file_info);

        // Create a render array ($build) which will be themed as a table with a
        // pager.
        $build['imgsearch_table'] = array(
          '#theme' => 'table',
          '#header' => $header,
          '#rows' => $rows,
          '#empty' => t('There were no matching results found'),
        );

        // Attach the pager theme.
      /*pager_default_initialize($results['total_found'], $results['rows']);
        $build['imgsearch_pager'] = array('#theme' => 'pager'); */

      }
      else {
        $build['no_results'] = array(
          'markup' => '<div class="no-results>No images found</div>',
        );
      }
    }

    if (!$output) {
      $output = $build;
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('imgsearch_form', $id);
  }
}

```

What happens is that if the search has been run, the search form is in $build as the $form array, and the second array in $build is imgsearch\_table, which is a render array with #theme, #rows, and #header. However, I can't get the table to be rendered or displayed anywhere. I've been banging my head on this for way too long. What do I have to do to get my table to be rendered in my modal window, along with the form?

# Answer
> 0 votes
I finally got the table to render fine every time. Updated code:

```
function imgsearch_page($ajax, $id, $a, $b) {
  if ($ajax) {
    //Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Image Search Form'),
      'next_field_id' => $id,
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $search_form = ctools_modal_form_wrapper('imgsearch_form', $form_state);

    if (($form_state['executed'] && $form_state['ajax']) || isset($_GET['page'])) {
      // If the form has been submitted, there may be additional instructions
      // such as dismissing the modal popup.
      if (!empty($form_state['ajax_commands'])) {
        $output = $form_state['ajax_commands'];
      }

      if ($form_state['values']['search_terms'] != '' || isset($_GET['search_terms'])) {
        $page_num = isset($_GET['page']) ? $_GET['page'] : 0;
        // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
        if ($_GET['search_terms']) {
          $form_state['values']['search_terms'] = $_GET['search_terms'];
        }
        $results = nb_image_search_search($form_state['values'], $page_num);

        if (is_array($results['images']) && count($results['images'] > 0)) {
          $next_field_id = $form_state['next_field_id'];
          // Create object to store file and target field info. To be stored in ctools cache.
          $file_info = new stdClass();
          // Generate the field name.  field_images is a multivalue field collection, so we just need the next available option
          // in the $field_images['und'] array. The second number (for field_image) will always be 0 since it
          // is a single value field.
          $file_info->fieldname['url'] = '#edit-field-images-und-' . $next_field_id . '-field-image-und-0-imgsearch-file-url';
          $file_info->fieldname['person'] = '#edit-field-images-und-' . $next_field_id . '-field-person-und-0-value';
          $file_info->fieldname['organization'] = '#edit-field-images-und-' . $next_field_id . '-field-organization-und-0-value';
          $file_info->fieldname['year'] = '#edit-field-images-und-' . $next_field_id . '-field-year-und-0-value';

          $file_info->fids = array();

          // Theme the results as a table.
          $header = array(t('Image'), t('File Name'), t('Add to field'));
          $rows = array();
          foreach ($results['images'] as $image) {
            // Create image style derivative for each image.
            $imagestyle = array(
              'style_name' => 'thumbnail',
              'path' => $image['filepath'] . $image['filename'],
              'width' => '',
              'height' => '',
              'alt' => '',
              'title' => $image['filename'],
            );
            $styled_image = theme('image_style', $imagestyle);
            $fid = $image['fid'];

            $rows[] = array(
              'image' => $styled_image,
              'name' => $image['filename'],
              'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $next_field_id, t('Select')),
            );

            $file_info->fids[$fid] = $image['filename'];

            // Cache values for Person, Organization, and Year if they exist.
            foreach (array('person', 'organization', 'year') as $field) {
              if (isset($image[$field])) {
                $file_info->meta[$fid][$field] = $image[$field];
              }
            }
          }
          //Cache image name in ctools object cache so it can be used later in nb_image_search_image_add()
          ctools_include('object-cache');
          ctools_object_cache_set('imgsearch', 'imgsearch_' . $next_field_id, $file_info);

          // Create a render array ($build) which will be themed as a table with a
          // pager.
          $build['search_form'] = isset($search_form[0]) ? drupal_build_form('imgsearch_form', $form_state) : $search_form;
          $build['imgsearch_table'] = array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#empty' => t('There were no matching results found'),
          );

          // Attach the pager theme.
          $pager = pager_default_initialize($results['total_found'], $results['rows']);
          $build['imgsearch_pager'] = array(
            '#theme' => 'pager',
            '#parameters' => array(
              'search_terms' => $form_state['values']['search_terms'],
              //TODO: add params for Person, Organization, and Year.
              ),
          );

          $form_state['values']['title'] = t('Search Results');
          $output = ctools_modal_form_render($form_state['values'], $build);

          print ajax_render($output);
          drupal_exit();
        }
        else {
          $build['no_results'] = array(
            'markup' => '<div class="no-results>No images found</div>',
          );
        }
      }
    }
    elseif (!isset($output)) {
      $output = ctools_modal_form_wrapper('imgsearch_form', $form_state);
      // Return the ajax instructions to the browser via ajax_render().
      print ajax_render($output);
      drupal_exit();
    }
  }
  else {
    return drupal_get_form('imgsearch_form', $id);
  }
}

```

To be honest, I didn't really change anything in regards to the table generation, so I'm suspecting another change I made fixed it.

---
Tags: ajax, chaos-tool-suite, javascript
---


# Question
Title: How do I display social media buttons on new content pages on my Drupal Commerce site?
I have installed Kickstart Commerce 2. With the demo store, the social media buttons (facebook like, g+, and tweet buttons) are shown at the bottom right of the product page directly below the add to cart button, as shown in this kickstart demo store link, http://demo.commerceguys.com/ck/drinks/drupal-commerce-wake-you).

When I create a new product of a content type that was pre-created by the demo store, these social media icons show up the same way. But now that I have created my own content type for other products I choose to add to my store, this does not display. I thought it was a block, but no blocks seen to have this information.

How do I display social media buttons on new content pages on my Drupal Commerce site?

Thank you to anyone they can offer some direction in this please.

# Answer
> 2 votes
Kickstart 2.0 Distro uses the service links function. That's what you're seeing below the "add to cart" button. Pretty easy fix. Make sure the service links module is enabled and hit configure, or visit: .../admin/config/services/service-links.

At the top, you can just check the boxes on whichever content type you want these links displayed, as well as a bunch of other fun features below.

Enjoy!

# Answer
> 0 votes
There may be different solutions, One can be : Editing the "node content type" or "node-display content type" template and add the necessary code on bottom or on top of the node

node-nodetype.tpl.php

Additional information about how to edit the node content type: https://drupal.org/node/17565

# Answer
> 0 votes
If you are not using the demo site store, you will also need to enable the General Services module and then configure which services you want to show at `admin/config/services/service-links/services`. I have also noticed that the default layout on the product nodes is not ideal. You will have to theme the product page to get the layout you desire.

Additionally, only the admin user is given access to the social media links by default. You will need to give your users permissions using the Service Links -\> Access to Service Links.

---
Tags: commerce
---


# Question
Title: How can I remove "Show row weights" as well as the weight column in D7?
This answer shows how to remove the "Show row weights" text from a form. However, as the comment to this answer suggests, it doesn't remove the weight column as well.

How can I update the following code to also remove the weight column from my form?

```
<?php
/**
 * Implements hook_js_alter().
 */
function MODULENAME_js_alter(&$javascript) {
  unset($javascript['misc/tabledrag.js']);
}
?>

```

Or, is there a better way to do this? This seems like a hacked way of removing the row weights.

# Answer
> 3 votes
If you do not want to display those elements because it confuses users, you could simply hide them with CSS. Use Firebug or something alike to determine the correct classes in order to adapt the code underneath.

```
#YOUR-FORM-ID .tabledrag-toggle-weight-wrapper,
#YOUR-FORM-ID .field-multiple-drag {
  display: none;
}

```

---
Tags: 7, forms
---


# Question
Title: Let local drush call remote drush with `bash` or `sh`
I am trying to get database syncing with drush going. I installed drush on my webserver, but I only have the permission to run it with `bash` or `sh` before `drush`. (So with `./drush` I get `permission denied`)

It seems that my local drush calls the remote drush without `bash` or `sh`, so I get `permission denied` when I try `drush status` for my @bla.remote.

Is there a way to tell drush to use these commands or can you think of another way to bypass this problem?

Could I write an alias somewhere into drush?

# Answer
You will need to do something like this:

```
$aliases['myremotesite'] = array (
  'remote-host' => 'isp.example.com',
  'remote-user' => 'www-admin',
  'root' => '/srv/www/example.com/drupal',
  'uri' => 'http://example.com',
  'path-aliases' => array(
    '%drush-script' => '/home/www-admin/bin/my-drush',
  ),
);

```

Customize URIs, paths and sitenames to suit. Then, create a 'bin' directory in your $HOME (if you don't already have one), and make yourself a 'my-drush' script like this:

```
#!/bin/bash

bash drush $@

```

Once we commit https://github.com/drush-ops/drush/pull/1595, you will be able to simplify the above by copying the drush.wrapper script to your remote site's Drupal root, and prefixing its call to the Drush launcher with `bash`. That PR is close, but it's also Drush 8 only, so you might prefer making your own `my-drush` script, as shown above.
> 0 votes

---
Tags: drush
---


# Question
Title: Compare date field columns to restrict difference in days between the two
I have an ad space website, where a person can place an advert, but for a maximum of 30 days.

To do this, I have a date field with a calendar popup and collect an end date on field. So it's one field collecting both dates. I need to validate the input of the end date by comparing it to the first field (start date). I have the field validation module installed, but I'm not sure how to configure it.

How do I configure it? Or is there a better way to do this?

# Answer
The field validation module does what you want, the interface description can be confusing.

1. On your **Manage fields** screen click the **validate** action link for your relevant date field.
2. For your field you want to add a **Date range2** validation rule.
3. Name your rule in **Rule name** to a memorable description.
4. For **column** select *value2* to validate your end date.
5. For **Cycle of date** select *global* so you can validate against time relative to the start date.
6. For **Maximum date** set it to "+30 day" (or any `strtotime()` compatible relative string) so that the end date is, ***at most***, 30 days from the start date.
7. Set your your **Custom error message**.
8. Click **Save rule**.
> 0 votes

---
Tags: datetime, forms
---


title: Altering a Drupal Commerce Form

text:
# Question
Title: Altering a Drupal Commerce Form
I can't figure out how to alter the drupal commerce form. I created a module with a .module and .info file and have enabled 'devel'. I've also enabled this module. However, when I use the following code, or derivations thereof, no message appears in the message area no matter how many times I refresh the page. I've flushed caches and made sure $messages is set to display on the template.

```
<?php
  function module_name_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "commerce_checkout_form_checkout") {
      dpm($form_id);
    }
  }

```

Anyone know what the problem is here?

# Answer
Try *hook\_form\_alter()* like this;

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_form':
      ...
    break;
}

```
> 2 votes

---
Tags: commerce, forms
---


# Question
Title: How to translate taxonomy terms displayed via an exposed filter in views?
I'm using the Views, i18nviews, and Entity Translation modules. All of my terms have already been translated using Entity Translation. In views displays, the translated terms appear in the correct language except in exposed filters. In exposed filters, the terms always appear in the default language for the site.

A search of the issue queues reveals a thread of monstrous length here. So, while support for this is still a work in progress, is there any way (quick and dirty hacks are ok) to get this working today?

# Answer
Editing the View, try to add a new Filter Criteria and look for one you want to translate. There should be a duplicate entry, but the second indicates: (translated). You should use add this (exposed) filter, and delete the other one.
> 0 votes

# Answer
1. I de-activated entity translation for taxonomy terms in the interface here :

/admin/config/regional/entity\_translation

* This means that the translation of terms is dealt with entirely by the Taxonomy translation module
* It also means that the term can be translated directly from the term interface

2. I added a function to a custom module in order to order things alphabetically in the exposed filter as described here : How can I sort options in an exposed views filter alphabetically?
> 0 votes

---
Tags: 7, views, taxonomy-terms, i18n-l10n
---


# Question
Title: Drupal 7 - Dynamic Allowed Values Field Widget
I have a project I'm working on where each content manager/author would have a different set of allowed values on a select input for each node created. Is hook\_form\_alter the best method for me to dynamically generate the options? And what would the syntax kind of look like?

# Answer
> 0 votes
You might get it to work like so:

* Use the Select (or other) module, and
* Integrate it in a form or module using a Forms API element.

More details below ...

# About this module

Here is an excerpt about the Select (or other) module from its project page.

> Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few options (Option 1, Option 2, Option 3), and whenever somebody needs another one (not in the list yet), they just enter "Option 4". Here is a sample about it:

# Integration in a form or module

By only using the module as delivered, you wouldn't have a different set of options yet for each author. But the Select (or other) module can be integrated in any form or module, as shown also in the usage example within the Community Documentation of this module.

By enhancing that usage example to make the values for `value_1`, `value_2`, `value_3` depend on each user, you should get it to work.

---
Tags: 7, entities
---


title: i18n module is acting up weird

text:
# Question
Title: i18n module is acting up weird
I have a site with two languages (Dutch and English). However if I want to translate a Dutch node I must use the Dutch admin interface, and if I want to edit an English node I must use the English admin interface.

So let's say node/1 is in Dutch and node/2 is English, and my default language is Dutch. Now, if I go to /node/2/edit, so the edit form of the Enlish node in the Dutch language it redirects to /node/1/edit If I really must edit the English node I must go to /en/node/2/edit

Also the translated nodes are not present:  While I think it should also display which node ID's are the English and Dutch language on here. Like below:  The part in red is here like it should, but not on my production site as you can see in the first picture.

The second thing is that normally you can edit Dutch, Spanish, and English from the English admin pages. On my production site this I cannot do this. There I have to switch to the Spanish admin interface to translate to translate in Spanish, and I need to switch to English to translate to English.

What am I missing here.

# Answer
> 0 votes
A possible explanation for your problem might be because of your "language detection" configuration.

Check this configuration via *Configuration -\> Languages -\> detection and selection*: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.

# Answer
> 0 votes
And sometimes it is good to have someone ask for clarification.

It appears to be the translation\_overview module that is making it appear like this.

If I disable that module all works like it should.

---
Tags: i18n-l10n
---


# Question
Title: How to schedule an action to reliably be performed once every 5 minutes?
I have a need for a function to run every N minutes (it doesn't need to be EXACTLY every N minutes, but it should still occur within a reasonable amount of time, maybe N+/- 5 minutes)

I've been bouncing around between the DrupalQueue class, job\_scheduler, rules, actions, etc., and each time it seems like I run into a wall.

My current set up is that I use job\_scheduler\_trigger. I seem to have it setup correctly (using a basic UI created action of "Send email"), and I have it set to go every 5 minutes, but it NEVER fires. The "Next" run time just keeps incrementing itself properly, but the "Last" run time is always "Never". I have no idea what I'm doing wrong, or even if this is the best way to go about it.

# Answer
> 1 votes
Using Rules and Rules scheduler (submodule of Rules) seems to me "a" valid approach.

What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 5 minutes (instead of only after 1 hour). And you need to run cron every 5 minutes also (not hourly as in that tutorial).

And as explained also in that tutorial: *Initially execute the component manually* (from then on every other 5 minutes the rule will be executed again).

**Note**: How to schedule a regular job using Rules in Drupal 7 is another tutorial that covers this topic.

---
Tags: 7, rules
---


title: Drupal SMTP is not working

text:
# Question
Title: Drupal SMTP is not working
I am using STMP module for D7.

When i put test email abc@gmail.com, i have received the email but

When i check show original i am getting received from

```
Received: from usernem by myhost username with local (Exim 4.85)

```

Why it is so ?

Also i have enter wrong password and tried to send an email. i recieved the email

Seems SMTP is not working on my site

Below are my settings

# Answer
> 0 votes
Change and check

```
SMTP server: smtp.gmail.com
SMTP port: 587
Use Encrypted Protocol : Use TLS

Username: Your Email Id
Password: Your Password

```

For default email settings check

> /admin/config/system/mailsystem

---
Tags: 7, emails
---


# Question
Title: How to get Tb Mega Menu working in Chrome?
I have a website and integrated Tb Mega Menu for the navigation. But the problem is my dropdown is not working in Google Chrome, though it is perfectly working in Internet Explore, Mozilla. My version of Google Chrome is 45.0.2454.85 m.

How to solve this issue? I did search for this, but found nothing suitable.

# Answer
After so much time I found an answer. I Just increase the z-index for that li and the dropdown start working for me.
> -1 votes

---
Tags: navigation
---


# Question
Title: Creating a view that uses fields from two content types
I'm reeally struggling with this one. I just can't seem to wrap my head around the way Drupal and Views handles this pretty simple thing...

I have two content types:

* **Card**
* **Card Content**

**Card** has the following fields:

* *Title*
* *Body*
* *Display Order*
* *Linked ID*

**Card Content** has the following fields:

* *Title*
* *Body*
* *Linked ID*

In Views, I would like to display:

* **Card Content** \- *Title*
* **Card Content** \- *Body*
* **Card** \- *Display Order*

If I were to write this as an SQL statement, it would be simple:

```
SELECT a.title, a.body, b.display_order
FROM card_content AS a
  INNER JOIN card AS b
    ON a.linked_id = b.linked_id

```

How do I achieve this?
**Things to note**: I originally had the *Linked ID* as a select box, taken from a set of predefined taxonomy terms. I have since migrated these to *entity-reference*s, that pull the data from the taxonomy terms (if that makes sense)?

**EDIT**: Okay, to clarify things a little...

*Linked ID* is a select box that's linked to a taxonomy vocabulary. This is purely to limit what a user can input.

As requested, here are screenshots of my **Card** and **Card Content**.

# Answer
> 0 votes
You should create a `entity reference` field in **Card** name it as "card content ref"( reference it to "Card Content" content type ) , then in your views, add relation to "card content ref" then in your field list "Card Content - Title" and "Card Content - Body" field exists.

Also for tutorial and learning more about Realation between two content types read this article

# Answer
> 2 votes
Best way is to use entity reference

Below is the youtube link which will provide you step by step explanation of using entity reference module with views. https://www.youtube.com/watch?v=4Pdii7aFIvc

# Answer
> 1 votes
You can use this module..suitable for your requirement https://www.drupal.org/project/entityreference

# Answer
> 0 votes
We have 2 content types of A and B:

1. We add content type B to the Filter Criteria of the view.
2. Add an nid of content type A using Contextual Filter in the advance Options.
3. Add a relationship of content type B in reverse order in the relationship field in advance options.

---
Tags: entities, views
---


# Question
Title: How obtain the uid of the logged user as a related field in a view?
I have a view showing the nodes of a content type, and I want to show the user ID of the currently logged-in user as a field in view, but I can't find how to add the user ID of the currently logged-in user. I know that I can achieve this with the Views PHP module but I want to know if there is another way.

I have Views 3.11.

There is no relation between the content being shown, and the currently logged-in user; I just want to show the user ID of the user who is currently seeing the view.

# Answer
You can't without some custom module providing such a data field (such as views php as you've seen).

Unless the uid has some relations to the content type you're displaying (e.g. a user reference field, the node uid, etc.), there's no way to retrieve the current UID. Views is designed to pull in data from a base table (e.g. nodes, users, taxonomy, etc.) and display the fields directly attached to it or related to it through a relationship.
> 1 votes

# Answer
You can do this with the help of *relationships* in views by choosing `content:author`. This will give you uid get\_uid.

Other way of achieving this is by using views php filter. Views php field with code should do the job:

```
<?php
  global $user;
  print $user->uid;
?>

```
> 1 votes

# Answer
The uid of the current user as a field in view would be the same for each row of your view results, so I am presuming some other outcome than merely displaying this field.

My guess would be to use it as a rewrite rule to create a link that has the user id in it (I'm struggling to come up with another scenario - perhaps specify?)

For that use-case, I would use custom php field - it's the simplest. It does sound like you are looking for a contextual filter, rather. Set the default value to be the uid of the logged in user.
> 0 votes

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


# Question
Title: Request for new password when user login for the first time
I am using darland theme in drupal7 site and I want user to reset their password for the fist time when they login with temporary login credentials given by admin,i,e created user when he login for the first time he should able to see the reset password form and later he can use his account as required,!!how to resolve this issue??can anyone know?

And below screen shot which i have added is my login screen and the code showing up in the right page is cos i have added the code in page.tpl.php to solve above problem explained so now it looks like, however if i take off the code from page.tpl.php it will be removed.

# Answer
> 2 votes
# Options to set a password

First of all, the very only way for any user to change their password, is using either of these approaches:

* using `/user/xyz/edit` (with xyz = uid of the user), where there is an option to change your password. But: this can only be done for a logged in user (which assumes that the user succeeded in entering their (old) password).
* using a "one time login URL", as further described below.

# Requesting a new password

When you are not logged in, you can navigate to `/user/password` within your site (either for D6 or D7). That is where you will find the "request new password".

For a logged in user, in D7, who navigates to `/user/password`, you won't get the same "request new password" form however. Instead, you'll get something like so (`your.name@yourdomain.com` is the eMail Id to where the request new password eMail will be mailed to):

> Password reset instructions will be mailed to your.name@yourdomain.com. You must log out to use the password reset link in the e-mail.

# eMail a one time login URL

You may also want to look at what is configured as email templates when new users are created (located at `admin/config/people/accounts`). Such as the template for "a new user created by an administrator". By default (in D7) that template looks like so (bold markup added here):

> \[user:name\],
>
> A site administrator at \[site:name\] has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser:
>
> \[user:one-time-login-url\]
>
> This link can only be used once to log in and **will lead you to a page where you can set your password**.
>
> After setting your password, you will be able to log in at \[site:login-url\] in the future using:
>
> username: \[user:name\] password: Your password

So this one time login URL could be used by a new user. And if for some reason that URL doesn't work (anymore), then such user can still user `/user/password`.

**Variation**: any user (such as an admin ...) can use that URL and specify the eMail ID of the new user who has to set a new password (the eMail will arrive at the new user ... if the eMail ID is correct).

# Redirect on login when using a one-time login URL

One might consider adding links like `/user/password` and/or `/user/xyz/edit` (with xyz = uid of the logged in user) anywhere in your site (e.g. somewhere in your theme).

However, I'd use an approach using the Rules module to redirect on login when using a one-time login and password reset. How to actually do so (there are multiple solutions) is detailed in issue # 480584. Personally I'd go for a solution based on what is described in comment #37 of it.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

# Use the Force password change module

Another approach might be to use the Force password change module (available also for D8 now, **merci Jaypan!**). Here are some details from its project page:

> This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.
>
> Features:
>
> * Ability to force all users in a role to change their password.
> * Ability to force individual users to reset their password from their profile edit page (user/\[UID\]/edit).
> * Ability to set an expiry on passwords so that if users haven't changed their password within that time period, they will be required to do so.
> * Ability to force all new users to change their password on first-time login (site-wide setting for all new users).
> * Ability for admins to force individual users to change their password on first time login when creating a new user. (Note: If the global setting forcing all new users to reset their password is enabled on the module settings page, this checkbox will not appear as it is redundant).
> * Listing of stats on the user edit page (user/\[UID\]/edit) showing:
>
> + Whether the user has a pending forced password change.
>     + When the user last had their password forced to be changed.
>     + When the user last changed their password.
> * Status page for each role showing:
>
> + Password change details by user.
>     + The last time at which the role was forced to change the password.
>     + A form to force the password change for all users in that role.

Use `admin/config/people/force_password_change` and enable `Force password change on first-time login` (can also be configured for selected roles).

# Answer
> 0 votes
Check it to putting in theme file

```
function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_pass':
        print '<pre>';print_r($form); print '</pre>';
      break;
  }
}

```

# Answer
> 0 votes
There are two possibility / ways.

1. Add css.

```
#block-user-0 .item-list  { display: none;}

```
2. Show link in your module.

`if(isset($tabs['#primary'][1]['#link']['path'])
&&
$tabs['#primary'][1]['#link']['path'] == 'user/password')
{
show($tabs['#primary'][1]);
}`

Hope this can solve your problem.

---
Tags: users
---


# Question
Title: How to manage reservations with Drupal for something that is not something like a room?
I am looking for a reservation module for either Drupal 6 or 7. I know there is a really good looking module for room reservations for Drupal 7 but my use case is different. I am looking for a reservation/booking module that could be used for booking photographers or DJs. I have searched around but haven't really found anything suitable yet.

The Room Reservations module that is being created for Drupal 7 looks great, but it needs to be generalized so that the administrator could define what it is that needs to be booked. Right now it is hard coded for rooms only.

Does anyone know of such a module and more importantly worked with it?

# Answer
> 4 votes
**For Drupal 6** there is a stable release of Simple Reservation module.

> This module provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

**For Drupal 7** you can try Reservations API.

> The core focus in on the Reservations API that enables any Content Type to be reservable based on a variety of default settings. A **Reservation -\> Confirmation -\> Checkout -\> Checkin** workflows is included, but it is created entirely using Views. Additional modules can enforce custom validation, add pricing, or add additional availability to the basic hours of operation.

# Answer
> 0 votes
Check the following module: Booking Time Slots.

This module works as extension to Calendar and provides nice UI (customisable) for slot booking (reservation).

This is the screenshot of the UI exposed from the module.

### Drupal 6.x

You can customize how many slots are period (hour, half-hour or custom). You can easily override template files based on your needs. Once the user make the reservation of specified slot, it's booked.

### Drupal 7.x

For other modules, check: Comparison of Booking System modules

# Answer
> 0 votes
Below is a summmary of the modules and/or distributions you may want to look at for managing reservations, for something that is not a room (or a variation of that). These modules have a stable release, and can be used for either D6 or D7 (quotes are from their project pages):

* Availability Calendars (D6 or D7).

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
* Simple Reservation (D6 or D7).

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
* MERCI (D6 or D7).

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
* Resource Conflict (D6 or D7).

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

# Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

# How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards.

Here is the intro about it (from that page):

> ... contains a list of 23 criteria (=28-5) that might help to evaluate the maintenance and support of contributed modules. Below is an attempt to apply those criteria to each of the native charting modules ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Also note that I've ordered my shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.

**Disclosure**: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph),
I hope this does not violate the site's policy on self-promotion.

---
Tags: 7, bookings
---


title: Adding imagesloaded to packery module

text:
# Question
Title: Adding imagesloaded to packery module
With many responsive designs it is not possible to assign image dimensions as they will be determined by the view-port dimensions. However some scripts, such as Packery, require image dimensions to be known to enable them to arrange items correctly, without overlapping or leaving large gaps. One solution often suggested (e.g. at https://drupal.stackexchange.com/a/77330/14365) is to use imagesloaded.

I have looked at other Drupal modules such as Views Isotope and Field Slideshow which both use imagesLoaded. They each implement it in a different way and I am looking for the ***correct*** way to add it in to the Packery module.

My understanding is that: First, a call to add the imagesLoaded script needs to be added to the module file. (The script itself is added to the libraries directory within a folder named 'imagesLoaded'). Secondly, the `imagesLoaded()` must be declared with the JavaScript file which currently contains:

```
(function($) {
  Drupal.behaviors.packery = {
    attach: function(context, settings) {
      for (var packery in settings.packery) {
        var $container = $('#' + packery);
        $container.packery(settings.packery[packery].settings);
      }
    }
  };

}(jQuery));

```

Within the above I need to add in:

```
$('#container').imagesLoaded( function() {
  // images have loaded
});

```

Does the way that imagesLoaded is added within the module effect if it becomes a function? Adding the script side-wide is not really appropriate as it is only required in combination with the use of Packery. Does this mean it should be added in a certain way?

# Answer
> 3 votes
Super late but support for this request has been added in the latest commit of the Packery module: Commit 24856cf on 7.x-1.x by swim: Added imagesLoaded support on per settings basis.

Just toggle on/off on the settings page, and read the README.txt for the plugin placement. Here is a quote from the updated README.txt:

> ### ImagesLoaded support
>
> For imagesLoaded support please download the plugin from https://github.com/desandro/imagesloaded.
> Place the plugin in the libraries directory at sites/all/libraries/imagesloaded so that the file is at sites/all/libraries/imagesloaded/imagesloaded.pkgd.min.js.

---
Tags: javascript
---


# Question
Title: Add taxonomy field to a bundle programmatically
I'm currently developing a module which provides a content type called "Structural machinery" . This type should also provide a taxonomy term based on different manufacturers providing the machine (eg CAT or Komatsu) , I know how to create a taxonomy vocabulary programmatically but the question is how to attach a taxonomy field to my bundle.

this is the code used to implement the taxonomy term :

```
$term = new stdClass();
$term -> name = $t('Manufacture');
$term -> machine_name = 'manufacture';
$term -> description = $t('Description');
$term -> hierarchy = 2;
$term -> module = 'construction_machinery';
$term -> weight = 1;
taxonomy_vocabulary_save($term);

```

# Answer
First create your field

```
$field_name = 'field_manufacture';

$field = field_info_field($field_name);
if(!$field){
  $field = array(
    'settings' => array(
      'allowed_values' => array(
        0 => array(
          'vocabulary' => 'manufacture',
          'parent' => '0',
        ),
      ),
    ),
    'field_name' => $field_name,
    'type' => 'taxonomy_term_reference',
    'module' => 'taxonomy',
    'active' => '1',
    'cardinality' => '1',
  );
  field_create_field($field);
}

```

Then create your instance(s)

```
$node_types = array('page','whatever');
foreach($node_types as $type){

  $instance = field_info_instance('node',$field_name,$type);
  if(!$instance){
    $instance = array(
      'label' => 'Manufacture',
      'widget' =>
      array(
        'weight' => 3,
        'type' => 'options_select',
        'module' => 'options',
        'active' => 1,
      ),
      'field_name' => $field_name,
      'entity_type' => 'node',
      'bundle' => $type,
    );

    field_create_instance($instance);
  }

}

```

if you do var\_export the return from field\_info\_field and field\_info\_instance of an existing field, you can see how the field arrays are structured & use this structure when creating new ones.
> 5 votes

# Answer
Programmatically create a taxonomy and attach a field to it, then create a content type and attach that taxonomy to it.

```
<?php
// Machine name for our custom node
define('NODE_NAME', 'the_node_machine_name');
// Machine name for our custom taxonomy
define('TAXONOMY_NAME', 'the_taxonomy_machine_name');
function module_install() {
  _create_taxonomy();
  _create_content_type();
}
/**
 * Create a taxonomy and attach a field to it.
 */
function _create_taxonomy() {
  $t = get_t();

  $term = new stdClass();
  $term->name = $t('Name');
  $term->machine_name = TAXONOMY_NAME;
  $term->description = $t('Description');
  $term->heirarchy = 1;
  $term->module = 'module_name';
  $term->weight = 1;
  taxonomy_vocabulary_save($term);
 // Create a field
 $field = array(
    'field_name' => 'field_tax_fieldname',
    'type' => 'text',
    'label' => $t('Label')
  );
  field_create_field($field);
  // Attach the field to our taxonomy entity
  $instance = array(
      'field_name' => 'field_tax_fieldname',
      'entity_type' => 'taxonomy_term',
      'bundle' => TAXONOMY_NAME,
      'label' => $t('Label'),
      'description' => $t('Description'),
      'required' => true,
      'widget' => array(
        'type' => 'text_textfield',
        'weight' => 3
      )
  );
  field_create_instance($instance);

  // Done
}
/**
 * Create a content type and attach our created taxonomy to it.
 */
function _create_content_type() {
  $t = get_t();
  $node = array(
    'type' => NODE_NAME,
    'name' => $t('Name'),
    'base' => 'node_content',
    'description' => $t('Description'),
    'title_label' => $t('Title'),
    'custom' => TRUE
  );
  $content_type = node_type_set_defaults($node);
  node_add_body_field($content_type, $t('Article'));
  node_type_save($content_type);
  // Create a taxonomy field and use the taxonomy entity we created earlier
  $field = array(
    'field_name' => 'field_tax_name',
    'type' => 'taxonomy_term_reference',
    'label' => $t('Label'),
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => TAXONOMY_NAME,
          'parent' => 0
        )
      )
    )
  );
  field_create_field($field);
  // Add the field to the content type as a HTML select box.
  $instance = array(
    'field_name' => 'field_tax_name',
    'entity_type' => 'node',
    'bundle' => NODE_NAME,
    'label' => $t('Label'),
    'description' => '',
    'required' => TRUE,
    'widget' => array(
      'type' => 'options_select',
      'weight' => -10,
    )
  );
  field_create_instance($instance);

  // Done
}

```
> 3 votes

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


# Question
Title: What is the difference between "Autocomplete" and "Autocomplete (Tags style)" field widget type?
What is the difference between an "autocomplete" and an "autocomplete (Tags style)" widget. These options are present when I add an entity reference field for example.

# Answer
> 11 votes
For one term, there is no difference.

When you increase cardinality (i.e. allow unlimited number of values), with tag style you will put all tags in one textbox, just like you do with tags on this site, and with regular autocomplete you will need to put each one with it's own textbox.

---
Tags: 7, entities, ajax
---


title: Change a label in a View to a div?

text:
# Question
Title: Change a label in a View to a div?
How can I change the label for a view to be a div instead? Here is my HTML, its the "Sort by" label I need to change.

```
<form class="ctools-auto-submit-full-form views-exposed-form-author-content-panel-pane-1 ctools-auto-submit-processed" action="/" method="get" id="views-exposed-form-author-content-panel-pane-1" accept-charset="UTF-8"><div>

<!-- THEME DEBUG -->
<!-- CALL: theme('views_exposed_form') -->
<!-- BEGIN OUTPUT from 'sites/all/modules/contrib/views/theme/views-exposed-form.tpl.php' -->
<div class="views-exposed-form">
  <div class="views-exposed-widgets clearfix">
          <div id="edit-sort-bef-combine-wrapper" class="views-exposed-widget views-widget-sort-sort_bef_combine">
                        <div class="views-widget">
                    <div class="form-item form-type-radios form-item-sort-bef-combine">
  <label for="edit-sort-bef-combine">Sort by </label>
 <div id="edit-sort-bef-combine" class="form-radios"><ul class="btn-group"><li class="btn-group__item"><a href="http://localhost.site.com/news/author?sort_bef_combine=created%20DESC" class="btn btn--sort btn--active">Date</a></li><li class="btn-group__item"><a href="http://localhost.site.com/news/author-dobie?sort_bef_combine=value%20DESC" class="btn btn--sort">Popular</a></li></ul><input type="hidden" name="sort_bef_combine" value="created DESC"></div>
</div>
        </div>
              </div>
                    <div class="views-exposed-widget views-submit-button">
      <button class="ctools-use-ajax ctools-auto-submit-click js-hide btn form-submit" id="edit-submit-author-content" name="" value="Apply">Apply</button>
    </div>
      </div>
</div>

<!-- END OUTPUT from 'sites/all/modules/contrib/views/theme/views-exposed-form.tpl.php' -->

</div></form>

```

The template responsible is `views-exposed-form.tpl.php`. Within the template the code below prints the form:

```
    <div class="views-widget findhere ">
      <?php print $widget->widget; ?>
    </div>

```

I've done a `dsm` on the $widget but the array just contains the full HTML.

Ive looked at `hook_form_alter` and done a `dsm` on this but in the full form array I still cant see a way to change the form label to a different element.

# Answer
Looks like you are using better exposed filter module, it has option to configure the sorting label

so instead of Sort By `<div>Sort by</div>` it will not replace the label but give you a nested div if that works for you.
> 2 votes

# Answer
You can use Semantic Views

**Description form This module page:**

> This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.
>
> Some of Semantics Views functionality can be done in Views, but Views is restricted to use only predefined HTML element and can only style each Field but not wrap rows with any HTML you like.

And Also you can override `views-view-fields.tpl.php`
> 1 votes

---
Tags: theming, views
---


# Question
Title: Save Commerce Order and Customer Profile on validation fail
I'm using Commerce Postal Code Filter to blacklist some delivery postcodes.

When a delivery matches the blacklist validation fails and form\_set\_error is applied.

The problem here is that this means the Customer Order fields and Customer Profile Shipping fields are not saved.

I know this is normal, because failed validation in other tests could mean illegal entries.

For the postcode filter however, I'd still like to save data on failed validation. This will allow the client to see the user's input delivery address and telephone in order to make a call.

Any ideas how to go about this?

**Ideas** \- Set to validate, but change order status - could this make it serve first checkout page?

# Answer
> 0 votes
You can can implement hook\_form\_alter in your custom module and add one more validation handler on top of validation handlers stack, so your is called first.

Inside your validation function follow the way the module Commerce Postal Code Filter is putting the validation, I assume it should be as simple as calling a function. Now if depending on what value it returns you can programmatially update current order status.

---
Tags: 7, commerce
---


# Question
Title: Custom module permission option not available
I developed a custom module and enabled it from admin panel `https://site/administer/modules/list` . But at *permissions* page `https://site/admin/user/permissions` there is no option for the administer or other users to enable it.

As you can see my custom module named is *notification module* but there is no option to add permission for that.

**Edit**

I have *hook\_perm* as follows

```
function hook_perm() {
  return array(
    'access GA admin tab',
    'access check backend tab',
    'access GA admin menus',
    'access GA autocompletion',
    'bypass GA field verification',
  );
}

```

Is there any relevance for this to the administer permission?

**Update**

My bad , i was given the same hook\_permission values in another module , so it got overwritten with the other module , and my module permission got freezed !

# Answer
Here is to implement the hook permission

```
/**
 * Implements hook_permission().
 */
function form_example_permission() {
  return array(
    'administer your module' => array(
      'title' => t('Administer permission for your module'),
      'description' => t('Some description that would appear on the permission page..'),
    ),
  );
}

```
> 1 votes

---
Tags: 6, users
---


# Question
Title: Delete block settings when removing a block from hook_block_info()
My module creates blocks. These may come and go and I want to make sure I'm not leaving cruft behind, e.g. settings from the configure block screen for blocks that no longer exist (i.e. are no longer returned by my `hook_block_info()`).

I've noticed that removing a block and then adding a new one (with the same delta) magically brings up the old config.

What should I do in my module to clean out this config? (or is it somehow done for me in an occasional cron?)

# Answer
I hope this should work if I get your question right.

```
db_delete('block')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_node_type')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_role')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();

cache_clear_all(MODULE_DELTA, 'cache_block');

```

Where MODULE resembles your module name and DELTA resembles your block's delta.
> 1 votes

# Answer
Block configuration might be saving through variable\_set();

Run a query on your database, as

```
SELECT * FROM system WHERE name LIKE '%block%';

```

Replace %block% with your with probable block configuration form fields machine name, to check if there is a variable

Also in your custom module check the implementation side hook\_block\_save(), if any varibale\_set(); is there.

In case this is the problem you can implement hook\_uninstall inside which you can do variable\_delete('name\_of\_vraible\_to\_delete');
> 0 votes

---
Tags: blocks
---


# Question
Title: How to disable billing address in Drupal Commerce while using Paypal WPS
I'm setting up a very simple online shop for a charity. They'll use Paypal WPS and don't want to collect customer's billing address as those will be entered in Paypal anyway. Is there a way to remove the billing address from Drupal Commerce.

I'm only using PayPal, so the aforementioned answer doesn't apply.

# Answer
If you do not need Billing Address section at all, it should be as simple as dragging Billing Information under disabled from any of checkout/review step. Go to page 'admin/commerce/config/checkout' in order to disable Billing Section.

If you want Billing Address section to vanish conditionally based on payment method opted(in case you have multiple way of payment) then it is already answered here by Ryan himself.
> 2 votes

---
Tags: 7, commerce
---


title: Request for invalid marker set

text:
# Question
Title: Request for invalid marker set
I've installed gmap module and configured it so that I'm using custom markers. It worked well till today (I've re-deploy website).

I'm able to choose my custom marker 'Accountant' in a settings (see screen below).

However when I load map I get an error message: "Request for invalid marker set"

I've googled it and did not find a clear explanation what is wrong.

Please advise what could be an issue.

# Answer
There is an update "REGENERATE MARKER CACHE" option in gmap settings.

By pressing "Regenerate" button Drupal will update JS file stored in

```
/sites/default/files/js

```

Make sure you have access to that file.
> 0 votes

---
Tags: google-maps
---


# Question
Title: How to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment
I have written my first deployment\_module for a Drupal 7 site and installed it into a virtual host on my development server.

I would like to check to see if my hook\_update\_N() functions have been invoked correctly and so am wondering how to determine which is the latest hook\_update\_N() function invoked in a Drupal 7 environment.

I imagine some Drush command would be easiest way to find out. Failing that, it is probably set in the database somewhere.

Any ideas?

# Answer
It's in the system table. This query:

```
SELECT schema_version FROM system WHERE name='mymodule';

```

will let you know the last update hook successfully completed.

if you want to use drush, there's drush sql-query

```
drush sql-query "SELECT schema_version FROM system WHERE name='mymodule'"

```
> 3 votes

---
Tags: drush, updating
---


# Question
Title: How to use relations in Views to get Content type fileds when I use Taxonomy
Good day. I have Content type with Taxonomy field. Right now I try to build Views by this Taxonomy vocabulary. And I want to use (how?) relations to get access to Content type fields. So, idea is to have View by Taxonomy, but use fields of content type, which has this taxonomy as field.

# Answer
> 0 votes
Is this similar to what you want to do? https://www.drupalgardens.com/documentation/taxonomy/views

---
Tags: views
---


# Question
Title: Hide tab created by views if user has a specific role
I have a views page with a menu tab in user profile, I want to hide it for some user roles.
I tried with hook\_menu\_alter

```
function hide_tabs_menu_alter(&$items) {
    global $user;
    if (in_array('gerant', array_values($user->roles))) {
        $items['user/%user/infos']['type'] = MENU_CALLBACK;
    }
}

```
1. This doesn't hide the tab, but it works for other tabs -created by other modules- like user/%user/contact.
2. I wanted this user still be able to see this tab in other users profile.

### To add more information

There are two roles (*gerant* and *etudiant*). The permission should be *View own info page* which should be assigned to *etudiant*. *gerant* should not have it, but it should still be allowed to see user/%user/infos in *etudiant*'s profiles.

# Answer
Finally it worked for me using hook\_menu\_local\_tasks\_alter(), thanks to drupal developers community.

```
function hide_tabs_menu_local_tasks_alter(&$data) {
  if (arg(0) == 'user' && is_numeric(arg(1))) {
    $uid = arg(1);
    $account = user_load($uid);
    if (in_array('gerant', array_values($account->roles))) {
      foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "user/%/infos") {
          unset($data['tabs'][0]['output'][$key]);
        }
      }

    }
  }
}

```
> 1 votes

# Answer
You can't check anything about the user in hook\_menu or hook\_menu\_alter. Whether or not a user has access to a given path is not determined at the time those hooks are run; instead, those hooks give you a chance to tell the system what functions should be called to determine access when the path is eventually accessed. That's the purpose of the `access callback` and `access arguments` options.

First, you need to determine the actual path that is registered. Since it's Views, the path is `user/%views_arg/infos` if you have validation turned on for the contextual filter, and `user/%/infos` if you don't have any validation for the contextual filter.

So try something like this:

```
function hide_tabs_menu_alter(&$items) {
  $items['user/%views_arg/infos']['access callback'] = 'hide_tabs_user_info_access_callback';
  $items['user/%views_arg/infos']['access arguments'] = array(1);
}

function hide_tabs_user_info_access_callback($uid) {
  if (($account = user_load($uid)) && ($role = user_role_load_by_name('moderator'))) {
    return !user_has_role($role->rid, $account);
  }
  return FALSE;
}

```

Also, since Views actually adds these paths in hook\_menu\_alter itself, you need to ensure your module runs after Views. So your module needs to either have a higher weight than Views, or implement `hook_module_implements_alter`. So add this to your module as well:

```
function hide_tabs_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    $implementation = $implementations['hide_tabs'];
    unset($implementations['hide_tabs']);
    $implementations['hide_tabs'] = $implementation;
  }
}

```
> 0 votes

# Answer
You can give a try to this module tabtamer

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
> 0 votes

# Answer
How about creating 2 views. One with a tab and the other one without the tab.

View #1 has access role of anonymous, view #2 has access role of authenticated.

PS: By default views has access of permission, so click on access and change that to role.
> 0 votes

# Answer
The Views module uses `hook_menu_alter()` to add its pages. That is why `hide_tabs_menu_alter()` doesn't work: `views_menu_alter()` is invoked after `hide_tabs_menu_alter()`, and the changes made from your module are overridden from the Views module.
You need to change the order hooks are executed, implementing `hook_module_implements_alter()` or changing module weight.

```
function hide_tabs_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu') {
    $group = $implementations['hide_tabs'];
    unset($implementations['hide_tabs']);
    $implementations['hide_tabs'] = $group;
  }
}

```

As side note, rather than checking for a role, you should:

* Create a user permission you assign to a specific role you use for those users who should see that page/view
* Through the user interface, create a new role you assign just to those users who should see that page/view

To create a new user permission, your module needs to implement `hook_permission()` (Drupal 7.x) or `hook_perm()` (Drupal 6.x or previous). In your specific case, the permission would be two:

* View own info page
* View any info page

This is similar to what the Node module does, which defines the following permissions for each content type: *edit own $type content* and *edit any $type content*.

In your case, you cannot use `user_access()` as access callback, since that function can just check a single permission, which is then applied to every user. The code you would use should be similar to the following one.

```
function hide_tabs_user_info_access($account) {
  global $user;

  if ($account->uid == $user->uid) {
    // The logged-in user is viewing the page for their own account.
    return user_access('view own info page', $account);
  }
  else {
   // The logged-in user is viewing somebody else's page.
     return user_access('view any info page', $account);
  }

  // The previous lines can be simplified to the following one.
  // $permission = ($account->uid == $user->uid ? 'view own info page' : 'view any info page');
  // return user_access($permission, $account);
}

```

This is the code I would write.

```
function hide_tabs_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu') {
    $group = $implementations['hide_tabs'];
    unset($implementations['hide_tabs']);
    $implementations['hide_tabs'] = $group;
  }
}

function hide_tabs_menu_alter(&$items) {
  if (isset($items['user/%user/infos'])) {
    $items['user/%user/infos']['access callback'] = '';
    $items['user/%user/infos']['access arguments'] = array(1);
  }
}

function hide_tabs_user_info_access($account) {
  global $user;
  $permission = ($account->uid == $user->uid ? 'view own info page' : 'view any info page');

  return user_access($permission, $account);
}

```

(I will leave as exercise the implementation of `hook_permission()`.)

Another error in your code is checking in `hook_menu_alter()` if the currently logged-in user has a role. That doesn't work because `hook_menu_alter()` is not always invoked; it is invoked when the information returned from `hook_menu()` needs to be re-build. You are not checking the role the logged-in user has, but the role of the user who is logged-in when Drupal re-builds the `hook_menu()` information.
> 0 votes

---
Tags: views, routes
---


# Question
Title: How to run drush make on remote using relative path?
I'm writing a script where I'd like to run .make file, but it fails with the following error:

```
$ drush @remote.test make --no-core profiles/foo/contrib.make --yes
Calling proc_open(ssh drush@remote 'COLUMNS=278 drush  --verbose --yes --root=/var/www  make profiles/foo/contrib.make   --no-core 2>&1' 2>&1);
file_get_contents(profiles/foo/contrib.make): failed to open stream: No such file or directory make.utilities.inc:487

```

despite the file exists. I don't want to hardcode absolute path, as I'd like to use the same command for other remotes.

The command fails, because current directory of drush is set to *HOME* folder, instead of webroot (which is correctly passed internally via `--root`). This example could be related to issue where drush shell alias is downloading the project into wrong directory.

So the question is: **How I can use `drush make` to execute .make file on remote host using relative path?** As it seems to work fine on local.

I'm using drush 7.0-dev on local and remote.

# Answer
For workaround, the following command should work:

```
$ drush @remote.test make --no-core $(drush @remote.test dd)/profiles/foo/contrib.make

```

Command `drush dd` will return the webroot path and pass it to outer command.
> 2 votes

# Answer
I had a slightly different problem of running drush from behat and needing to switch to a relative path (docroot) on different environments:

```
drush --root=$(pwd)/docroot [DRUSH COMMAND HERE]

```

where `$(pwd)` **p**rints the **w**orking **d**irectory
> 0 votes

---
Tags: drush
---


# Question
Title: Restricting blocks to certain URL paths without sub paths
How can it be achieved, to make a block appear for the URL path `/foo/*` but not for `/foo/*/bar`?

# Answer
That's not possible with the default path visibility condition.

If you need that, then you need to write your own condition plugin that allows to both have a white and a blacklist instead of just one or the other.
> 1 votes

---
Tags: 8, blocks
---


# Question
Title: Implement user editable personal pages with subpages
So I would like to have this structure:

```
/users/jhon
# A page (default blank) which can be edited by jhon

/users/jhon/project
# A page which can be created and edited by jhon and
# should be linked to in a menu in /users/jhon

/users/jhon/project/sub-project
# The same as above and should be linked to
# in a menu in /users/jhon/project

```

So I was starting to work on the `profiles`, but it don't feels like the right way..

# Answer
> 1 votes
You might not be aware of it, but this is a rather broad question.

Drupal is quite different to other CMS's. You don't create pages according to a certain URL structure. In a way, it's the opposite.

Your users just create content with relations/references to other content. How and where that is shown is up to you, not them.

One way to do this is to have two node types, "Project" and "Sub project" for example. Users create projects and they can create sub projects and select the parent project using an entity reference field.

Then, all you need is to set up alias patterns using custom code or the pathauto module (An inofficial D8 port can be found here, use on your own risk) so that it results in those URL's.

You can add plenty of things on top of it with views, custom code and so on: links to create sub-projects from a project, listing projects and subprojects but defining the content structure (and only after that the URL structure) is where you have to start.

---
Tags: 8
---


# Question
Title: Removing Email Address Required Field for Anonymous Users in Drupal Commerce
I have an email address field that shows up at the top of my commerce checkout form for anonymous users. It's a required field. However I've added my own email address field to the form further down the page in the billing information area. I don't want the account information fieldset and associated email address field at all because only anonymous users use the site.

Does anyone know where I can find this email address field...is it in views somewhere? I'd just hide the whole fieldset but the field is required so I need to actually remove it from the code somehow.

# Answer
You can disable Account info section by dragging it to disable section by visiting page 'admin/commerce/config/checkout'.

As in the screenshot Account Information is in Disabled instead of Checkout which is default configuration.

But remember there is a default rule which tries to create an account for anonymous user using the email id, you might have to disable it, or may have to turn in conditional.
> 2 votes

---
Tags: commerce
---


title: How to bulk delete nodes by ID?

text:
# Question
Title: How to bulk delete nodes by ID?
I have a large csv of nodes that need to be deleted from the database.

I need something like feeds but for deleting. I know this can be accomplished easily via a custom module but I'm just wondering if there's a module or feed extension I can use.

# Answer
One solution here, that is slightly different from your question, is to use Views/Views Bulk Operations (VBO) & contextual filters on a custom View.

VBO contains an operation for bulk deletion. You can create a contextual filter for *Content: Nid* with the **Allow multiple values** option selected. If you've created a page view, that would allow you to navigate to http://example.com/my\_node\_delete\_vbo\_view/1+2+3 wherein you can view all the nodes you want to delete, select them all, then apply the Delete item VBO operation.

The only work involves taking your CSV, slicing it down to just the node column, and replacing the character delimiters.
> 1 votes

# Answer
bulk delete This module will delete any nodes of a certain node-type using the batch api. It is advised to use the Views Batch Operations module (VBO) for a small number of nodes. But if you have to delete 10.000 nodes this module might be a better option.
> 1 votes

---
Tags: feeds
---


# Question
Title: Why are most of my Timefields blank when editing a node?
I have a node with four timefields. When I want to edit the node, all the timefields, except the first one (that has a default value), are blank.

I found this issue still doesn't solved: https://www.drupal.org/node/1970252

How can I solve this? I could populate the missing fields via javascript?

Altenatives of timefield module?

# Answer
Some of the starting pointers I can think of.

1. Ensure there is no custom code altering the form field. Search for hook\_form\_alter/hook\_form\_FORM\_ID\_alter in your custom modules.
2. Check your drupal error logs, if there is any error log related to timefield.
3. Check your browser console, if there is a JS error.
4. Check the timefields module issue queue if there is already such error reported, that would be the best place to start from.
5. Try installing timefields module on vanilla drupal and check if the same issue persist, in that case add this in the issue queue of module.
6. Make sure all timefields get data when saved for first time, debug using devel module,go to 'devel/php' page and run `dpm(node_load('your_node_id'));`, see inside node object if those fields have value or not.
7. "Like s there anyway the possibility to keep the values of the fields somewhere, so I could populate the missing fields via javascript?" Yes, you can only if field values are getting saved to database, in fact simple would be to do at php level something like

```
function my_module_form_alter($form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    if(isset($form[#node]->nid)) {
      $form['yourtime_field']['#default_value'] = $form['#node']->yourtime_field['und'][0]['value'];
    }
  }
}

```

**But this is not the solution, this will be re-attempt of what drupal already trying to do. Best would be to identify why values are not showing by default.**
> 2 votes

---
Tags: nodes
---


# Question
Title: Seeking a Better way to Create a Collapsible Fieldset
I'm creating a collapsible fieldset on my home page and have put the following code in a block (structure \> blocks):

```
<script type="text/javascript" src="/misc/form.js"></script>
<script type="text/javascript" src="/misc/collapse.js"></script>

<form>
  <div>
    <fieldset class="collapsible form-wrapper">
      <legend>
        <span class="fieldset-legend">Legend</span>
      </legend>
      <div class="fieldset-wrapper">Content</div>
    </fieldset>
  </div>
</form>

```

It actually works what I did using the 'Full HTML' text format. I did it this way though only because I don't know the preferred way.

I imagine this would normally be done (for security reasons or something...) by creating a module or via a preprocess function.

Am I wrong to second guess myself here? Maybe it's standard practice to do what I've done above.

Any guidance is appreciated. Thanks.

# Answer
> 1 votes
Form submit would not work unless you have an action for it.

You should rather do it in Drupal way, you will need following.

1. Create Custom Module in drupal.
2. Block API to create your custom block
3. Forms API. to create a custom form and call it in your custom block.

Here goes a demo module which will help you understanding the API https://github.com/arpitr/demo\_block\_form

Installing the module will give you a block which will look like as

---
Tags: theming, javascript, blocks
---


title: update a node field when flagging

text:
# Question
Title: update a node field when flagging
I want to achieve the following : I have a node 'proposal' with a flag 'accept' and another node 'project'. I want when a user flag the 'proposal' with the 'accept' flag, a field value in the 'project' node is updated. I wrote this code but it seems not to work

```
function mymodule_flag_flag($flag, $entity_id, $account, $flagging)
{

$node =  node_load($entity_id);
$freelancer = $node-> uid;
$project_node = node_load($node->field_projet['und'][0]['target_id']);
$wrapper = entity_metadate_wrapper('node', $project_node);
$wrapper->field_freelancer->value = $freelancer;
}

```

# Answer
> 0 votes
I do not see that you are saving the project node, after changing field value.

```
function mymodule_flag_flag($flag, $entity_id, $account, $flagging) {
  $node =  node_load($entity_id);
  $freelancer = $node-> uid;
  $project_node = node_load($node->field_projet['und'][0]['target_id']);
  $wrapper = entity_metadate_wrapper('node', $project_node);
  $wrapper->field_freelancer->set($freelancer);
  // You missed
  $wrapper->save();
}

```

---
Tags: flags
---


# Question
Title: Views content pane - return half the results
I'm trying to work a view into a panels layout and would like to break up the list of results with another type of panel in the middle. Is it possible to create a views content pane returning the first half of all results, then a second views content pane returning the second half? Or is there another way to do this?

I can imagine some options using a custom template for the view, but I'd prefer to do this through Drupal config if possible.

# Answer
> 0 votes
When editing your view, click on (+Add) button at the top and select block. So now you should have 2 blocks.

In block 1, for **pager**, select **Display a specified number of items**, then for **items to display, put 10 and leave offset 0.**

In block 2, do the same, except you need to put an **offset 10**, so it starts displaying at row 11.

Then add block 1 and block 2 to your panel.

**EDIT: Possible solution when you don't know the number of items**

**In summary**: We are going to move row x and everything below that using jquery.

* You would have to use php in the template file and divide the view total count by 2 and round up the answer (cause you might have 21 in total).
* Add a Global view result counter field, to your view. So now we are able to target each row.

So for example if total is 21 then /2 = 10.5, roundup to 11. The 11 will be saved as a variable.

Then just do an if statement if

```
( $fields["counter"]->raw = $variable) { print "<div class"move"> ... all the other stuff }

```

Then use the total to close the div at the last row.

Then just do an if statement

```
if ( $fields["counter"]->raw = $total) { print all the other stuff ... "</div>" }

```

You would also have to print the calculated number (11) inside a div, so then we can grab the total using jquery.

If your middle pane varies in height, you would have target the div and calculate the height with jquery so then we can add this number to the jquery `$('.move').css()`

Also, you would need to caculate the height of the "move" div and and assign that to the last panel div.

Lastly, you move the "move" div using jquery `.css()` by the height of the middle pane + 5 or so more px.

---
Tags: views, panels
---


# Question
Title: multidomain, multilanguage, keep indicization, multiheadache
I am trying to figure out how to migrate a website with multidomain and multilanguage settings, keeping SERPs.

PREFACE: I have 17 website all identical, except language, in pure html. All 17 website got good SERP positions... site.com site.de site.fr site.ch site.co.uk site.pt site.ca ...

PROBLEM:

I have installed drupal, create the template and fill up the CMS with all content necessary. I have used the i18n module to translate the website. Basically I have one node for each content.

node/1 ABOUT US node/2 QUI SOMMES NOUS node/3 CHI SIAMO node/4 QUIENES SOMOS

They are linked so when I click on the languageflag the content change based on the languauge: site.com/fr/qui-somme-nous.html site.com/en/about-us.html site.com/es/quienes-somos.html site.com/it/chi-siamo.html

The old web pages are structured like this:

site.fr/qui-somme-nous.html site.co.uk/about-us.html site.es/quienes-somos.html site.it/chi-siamo.html

and now the source of enormous headache...

How can i set up drupal in order to got on the same drupal installation the different topdomain and different multilanguage content, keeping the search engine position?

Hoping to have enough explain my situation.

Cheers

# Answer
One way to would be to build this with domain access use a different domain for each language to meet your criteria. Repoint the old urls to the new ones.

Another way would be by indicating the language in the url. Read more about it here: http://indico.cern.ch/event/216222/contribution/10/attachments/345315/481614/multilingual-training.pdf Start at page 37.

Probably a few other ways.
> 1 votes

---
Tags: i18n-l10n, domain-access
---


title: Fatal error while upgrading

text:
# Question
Title: Fatal error while upgrading
While upgrading to Drupal 7.39 from 6.37, after copying the new files over into the site's directory, when I tried to navigate to the website I see a blank page with the following error: `Fatal error: Cannot redeclare template_preprocess_block() (previously declared in /home2/mccotter/public_html/test/includes/theme.inc:2042) in /home2/mccotter/public_html/test/modules/block/block.module on line 1038`

I have not yet run update.php, and when I try to the page appears blank. I was unable to sign in as the maintenance user, but I set `$update_free_access = TRUE`.

For reference, the site that I am attempting to upgrade is jailtraining.org/test

# Answer
Pre-First back up your site.

First upgrade to the most recent version of Drupal 6. The follow instructions here to move to Drupal 7:

https://www.drupal.org/documentation/upgrade

Have trouble? Explain where you are in the process at that point so one might help.
> 1 votes

---
Tags: 7, upgrading
---


# Question
Title: How to add comments per picture in a photo album?
I have an activities content type that I want to add a photo gallery to (in the same content type). However I want comment capabilities per picture. How can I achieve this?

# Answer
Would build this by creating a single content type with only one picture per node with the comments turned on just as you did. Then build a view for your gallery with the comment as a link included.
> 0 votes

---
Tags: comments, media
---