# Question
Title: Remove field-collection-view and field-collection-container fromt field output
I am using the following modules:

* Paragraphs
* Field Collection

I am trying to Foundation 5 classes to re-create the zurb foundation orbit slider with unlimited slides. Initially my problem was limiting what seems to be unnecessary Drupal `<div>` tags and classes so I could control the HTML output as much as possible. My workaround was simply installing Fences which gave me great results. I have the debugging turned on in the settings.php file to just make sure my naming conventions are correct and to make sure my code is outputting correctly. So far it is but with one slight problem.

So far I have spent days trying to nut out why the output of my field collection "field\_add\_image" is rendering a containing div of `<div class="field-collection-container clearfix active">`, nested within that is another containing div which the field collection out is located. Each item is nested within another div tag like so `<div class='field-collection-view clearfix active">`. This has an unlimited field which can be added to a paragraph item.

I went into the field collection module to identify where the classes to these containing div's were added which seem to be using the `field_collection_field_formatter_view()` which I found in the function within the module file.

I have installed Fences as well, which may be conflicting. the settings of Fences is set to:

* Override the default wrapper markup with Fences lean markup (single div wrapper)
* Use Drupal's default classes" set as the default classes

All the fields are outputting the correct HTML output which is great, but for the life of me I cannot remove those two containing divs.

Here is the folder structure of the files I have copied from the systems folder within Drupal core and placed in templates folder. Below is the naming conventions I used with the machine names.

### Theme name

jacob\_d7\_theme

### Field collection name

field\_add\_image

### Paragraph Bundle

paragraphs-item--scrolling\_image.tpl.php code below

```
<ul class="example-orbit" data-orbit>
<?php print render($content['field_add_image']); ?>
</ul>

```

### Fields in field\_add\_image

* Banner Image: field\_3\_col\_img1
* Caption: field\_caption

Templates folder includes

### Paragraphs

paragraphs-item--scrolling\_image.tpl.php

### All code in document

```
<ul class="example-orbit" data-orbit>
<?php print render($content['field_add_image']); ?>
</ul>

```

### Fields

* field--field\_add\_image.tpl.php
* field--field\_caption.tpl.php

Both of these field files have the same code in them to remove any unneccesary div containers for fields.

```
<?php foreach ($items as $delta => $item): ?>
<?php print render($item); ?>
<?php endforeach; ?>

```

I have also experimented with but with no avail.

* field--field\_add\_image--scrolling\_image.tpl.php
* field--field-add-image--scrolling-image.tpl.php

I am not sure what I am missing as all the custom template files that I have made work they just keep getting contained by those two divs.

# Answer
> 4 votes
I managed to find the answer.

Through adding this function I replaced the containing `<div class="field-cllection-container>` with nothing "".

```
function jacob_d7_theme_field_attach_view_alter(&$output, $context) {

  // First check we're dealing with a field collection field.
  if(!empty($output['field_add_image'])) {
    // Now check for our specific field collection field.
    if ($output['field_add_image']['#field_name'] === 'field_add_image' ) {

      // Alter the prefix.
      $output['field_add_image']['#prefix'] = '';
    }
  }

}

```

then to remove the containing div for each field item I created a file called `field-collection-view.tpl.php` with only the following code. to remove the `<div class="field-collection-view clearfix">`.

```
<?php
  print $element['#children'];
?>

```

---
Tags: 7, theming, entities
---


# Question
Title: Dynamic select list in the form (dependent dropdown)
I'm using Drupal seven. I want to make the options in a select list be dependent on the value chosen in another select list in a form. I'm sure this has been asked many times before, but I am having difficulty finding a clear answer for how to do this.

The form is for users to enter a work history. They need to select a squadron which is a node reference to the squadron field type, and this is in a drop-down list. However, the squadron, is dependent upon a city drop-down list. Users first need to select a city which will then filter the options for the squadron. In the squadron content type, I created a taxonomy for city which gets tagged to the squadron.

I would be very grateful for any pointers as to the best way (simplest?) to go about this, or for any useful resources online which would help.

# Answer
You can use Ajax to accomplish this. Drupal 7 has good Ajax support now. On your first select list (city) you'll need to add Ajax information. Then, the second select list can be populated based on the information in the first. You can also even hide the second select list until an option in the first is selected, and I'll explain how to do that in a bit. First, to set up the basic form:

```
$form['city'] = array(
  '#type' => 'select',
  '#title' => t('City'),
  '#options' => $options,
  '#ajax' => array(
    'event' => 'change',
    'wrapper' => 'squadron-wrapper',
    'callback' => 'mymodule_ajax_callback',
    'method' => 'replace',
  ),
);
$form['squadron_wrapper'] = array('#prefix' => '<div class="squadron-wrapper">', '#suffix' => '</div>');
$form['squadron_wrapper']['squadron'] = array(
  '#type' => 'select',
  '#title' => t('Squadron'),
  '#options' => $squadron_options,
);

```

This is just the basic setup of the elements. Now you'll need a way to determine what options should go in squadron. First you need to make your Ajax callback identified in 'city' select list. In most cases you can just return the element that wraps the ajax element, in this case $form.

```
function mymodule_ajax_callback($form, $form_state) {
  return $form;
}

```

Now, when the 'city' select list changes it will rebuild the squadron-wrapper part of the form. Your 'city' value will now be in $form\_state\['values'\]. So, when the form is rebuilt we need to determine what options to give to the select list based on the value of 'city'.

```
// Get the value of the 'city' field.
$city = isset($form_state['values']['city']) ? $form_state['values']['city'] : 'default';
switch ($city) {
  case 'default':
    // Set default options.
    break;
  case 'losangeles':
    // Set up $squadron_options for los angeles.
    break;
}

// If you want to hide the squadron select list until a city is
// selected then you can do another conditional.
if ($city !== 'default') {
  $form['squadron_wrapper']['squadron'] = array(
    '#type' => 'select',
    '#title' => t('Squadron'),
    '#options' => $squadron_options,
  );
}

```
> 27 votes

# Answer
Many thanks to jordojuice above. With his help I managed to find a solution. I also refered to the example at http://public-action.org/content/drupal-7-form-api-dependent-lists-and-ajax-form-submission. I eventually used the code below which worked in a custom module. For some reason I couldn't find any of my values in the $form\_state values, but was able to find them in $form. Finally, when I tested, I was getting an error message that Drupal had detected an illegal choice in the drop-down. I got round this by commenting out line 1290 in form.inc:

`form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));`

The final code I used was:

```
<?php

function sappers_squadron_form_work_history_node_form_alter(&$form, &$form_state) {
        //echo '<pre>';
        //print_r ($form);
        //echo '</pre>';

        $squadron_options = array();

        if(isset($form['field_wkhist_city']['und']['#default_value'][0])) {
            $city = $form['field_wkhist_city']['und']['#default_value'][0];
        }
        else {
            $city = 0;
        }

        $squadron_options = sappers_squadron_squadrons($city);

        $form['field_wkhist_city']['und']['#ajax'] = array(
            'event' => 'change',
            'wrapper' => 'squadron-wrapper',
            'callback' => 'sappers_squadron_ajax_callback',
            'method' => 'replace',
        );

        $form['field_squadron']['und']['#prefix'] = '<div id="squadron-wrapper">';
        $form['field_squadron']['und']['#suffix'] = '</div>';
        $form['field_squadron']['und']['#options'] = $squadron_options;
}

function sappers_squadron_ajax_callback($form, $form_state) {
    $city = $form['field_wkhist_city']['und']['#value'];

    $form['field_squadron']['und']['#options'] = sappers_squadron_squadrons($city);

    return $form['field_squadron'];
}

function sappers_squadron_squadrons($city) {
    $nodes = array();

    $select = db_query("SELECT node.title AS node_title, node.nid AS nid FROM  {node} node INNER JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid WHERE (( (node.status = '1') AND (node.type IN  ('squadron')) AND (taxonomy_index.tid = $city) )) ORDER BY node_title ASC");

    $nodes[]="";

    foreach ($select as $node) {
            $nodes[$node->nid] = $node->node_title;
    }

    return $nodes;
}

?>

```
> 11 votes

# Answer
put the line of code i.e
`$nodes[''] = '- None -';` after

```
 $nodes = array();

```

in ur `sappers_squadron_squadrons function` and that will solve your error

`form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));`
> 2 votes

# Answer
The root cause of "An illegal choice has been detected. Please contact the site administrator." is that the empty string with the value of 0 added by `$nodes[]="";` is invalid for the field\_squadron field.

See Advance PHP Programming and Development, but keep in mind that the DANGEROUS\_SKIP\_CHECK and validated flags are deprecated in D7.

After I removed that line, the error was gone.
> 1 votes

# Answer
Use the Reference field option limit module

> This module allows reference fields of several types to have their widgets' available options limited by the values of other fields in the current entity.
> 0 votes

---
Tags: 7, ajax, forms
---


# Question
Title: Due to Clean Url issue, the site is not working
I have downloaded Drupal 8 from official site.But during installation it shows following error:

but i continue installation, and it installed properly. The problem is that except home page whenever i click on any link it shows "Page Not Found".

I have enabled mod\_rewrite for apache . Also i uncomment and edit "RewriteBase/d8" in.htaccess file.

I tried all whatever i found on drupal.org but nothing work for me.I desperate to work in d8 but helpless to continue. Million of Thanks in advance.

# Answer
I enabled mod\_rewrite for Apache, and restarted Apache. Then I simply commented out the `RewriteBase /` part of the .htaccess file on line 110. Apart from this, I didn't change anything in Apache configuration files. It works for me.
> 0 votes

# Answer
I was having the same problem, I opened the `/etc/apache2/apache2.conf` file and located this portion of the file

```
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

```

And found that AllowOverride is set to None. Go ahead and replace it with All.

Restart your apache service when done. Similar question is asked here
> 1 votes

---
Tags: 8, uri
---


title: Long text increase maxlength

text:
# Question
Title: Long text increase maxlength
I have added a textarea and i want to store more that 1024 characters in it. Long text is the field type that i have chosen but an error comes up saying :
**Keywords cannot be longer than 1024 characters but is currently "xx" characters long.**
I tried using **hook\_form\_alter** to increase the maxlength but it does not work. Also tried the **hook\_form\_field\_ui\_field\_edit\_form\_alter** to change the length from 255 to 555 but no success.
Is there any other workaround for this ?

# Answer
> 0 votes
Use Field maxlength alter module

> * Creating an update hook that alters the field tables
> * Installing this module and simply edit the max\_length in the admin interface
> * Installing this module and run the Drush command to modify the max\_length

---
Tags: forms
---


# Question
Title: Autoselect parent taxonomy if child is selected
How can I have the parent taxonomy be automatically selected when one of its children gets selected? It would be a convenience if the parent is selected automatically in the backend for every child selected.

Right now, if I select a child and not the parent, then search or browse for the parent term, child terms under that parent are not brought back. This doesn't seem right.

# Answer
similar question here: Check parent term when checking subterm

but if you need check all child when parent checked, you need some changes in JavaScript file
> 1 votes

# Answer
You could use the Hierarchical Term Reference Autocomplete module and can accomplish the first half of the task.

For detail of how to use this module, go through the README.txt of the module.
> 1 votes

# Answer
In Drupal 7 I recommend using Term Reference Tree. It creates a hierarchical tree of taxonomy terms and allows you to toggle settings such as:

* Allow user to select only one term / allow multiple terms.
* Allow user to select only lowest-level terms / allow selection of parent terms.
* Record only the term lowest selection(s) / record all parent terms of selection(s).

This module is similar to Taxonomy Tree Select module of Drupal 6.
> 1 votes

# Answer
I needed this to only copy the root term over to another node. The rules module only have the parent value but how to drill down? This is what I did with Drupal 7.

```
/**
 * Implements hook_rules_action_info().
 */
function my_custom_rules_action_info() {
  return array(
    'my_custom_get_root_term' => array(
      'label' => t('Get root term'),
      'parameter' => array(
        'tid' => array(
          'type' => 'taxonomy_term',
          'label' => t('Term'),
        ),
      ),
      'provides' => array(
        'rootterm' => array(
          'type' => 'taxonomy_term',
          'label' => t('Root term'),
        )
      ),
      'group' => t('My custom rules'),
      'base' => 'my_custom_rules_action_get_root_term',
    ),
  );
}

/**
 * Find the root term for the given $term.
 *
 * @param $term
 */
function my_custom_rules_action_get_root_term($term) {
  $results = drupal_static(__FUNCTION__, array());
  if (!is_object($term)) {
    $term = taxonomy_term_load($term);
  }
  if (empty($term)) {
    return;
  }

  // Build hash [$child] = $parent
  if (!isset($result[$term->tid])) {
    $tree = taxonomy_get_tree($term->vid);
    foreach ($tree as $tree_term) {
      // HUH: parents array always has one element on our vocabulary sets
      // No parent == 0
      $result = array_shift($tree_term->parents);
      echo $result . PHP_EOL;
      $results[$tree_term->tid] = $result;
    }
  }
  // follow the parent refs until $parent == 0
  $tid = $term->tid;
  while ($results[$tid] != 0) {
    $tid = $results[$tid];
  }
  return array('rootterm' => taxonomy_term_load($tid));
}

```
> 0 votes

# Answer
Easiest way to do that is to use rules module.
> -1 votes

---
Tags: taxonomy-terms
---


# Question
Title: What is the proper way to handle drupal_get_destination and drupal_goto?
I am considering the following approach in my controller (the method which corresponds to a given route).

```
$destination = \Drupal::destination()->getAsArray();
if (isset($destination['destination'])) {
  return new RedirectResponse(Url::fromUri($destination['destination']));
}
else {
  return $this->redirect('acquia_connector.settings');
}

```

Should I use different code to handle both route based and URL based redirects?

# Answer
> 0 votes
Drupal automatically uses destination, you don't have to do anything. If a destination argument is given, it will override default. So you can simplify your code to a simple, hardcoded $this-\>redirect(...).

The only exception is when you have links that you want to respect destination too (e.g. a cancel link on a confirm form), then you have to do it yourself. But the default confirm form already does that too AFAIK.

---
Tags: 8, redirection
---


# Question
Title: How to create paragraphs item programmatically?
How to create **paragraphs** item programmatically?

In Drupal 7 I am using the following code.

```
    $node = node_load($nid);
    $paragraph = new ParagraphsItemEntity(array('field_name' => 'field_name', 'bundle' => 'para_bundlename'));
    $paragraph->is_new = TRUE;
    $paragraph->field_ptest1['und'][0]['value'] = 'Foo';
    $paragraph->setHostEntity('node', $node);
    $paragraph->save();
    node_save($node);

```

But its not working ?

# Answer
> 0 votes
This is the code used in various places to create an entity in Drupal 7

```
$node = node_load(...);

$paragraph = new ParagraphsItemEntity(array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save();

```

Field collection module using the following method instead

```
$node = node_load(...);
$entity = entity_create('paragraphs_item', array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$entity->setHostEntity('node', $node);
$entity->save();

```

Both should work fine. You code looks good to me just remove the last line.

---
Tags: 7, entities
---


# Question
Title: drupal multisite and symbolic links with various subdomains
i create two subdomains **dev.example.com** and **dev1.example.com** in cpnael admin and i create a drupal installation in public\_html/dev/sites/ and i create two folders dev and dev1 inside of sites and your own database and the sites.php your settings are

```
<?php
$sites['dev.example.com'] = 'dev';
$sites['dev1.example.com'] = 'dev1';
?>

```

i create symbolink links in this way

> ls -s ~/public\_html/dev ~/public\_html/dev1

working good **dev.example.com** but no **dev1.example.com**

but in this way **dev1.example.com/dev** and working the other installation, how to make this work enter to **dev1.example.com** instead **dev1.example.com/dev**?

thanks

# Answer
> 0 votes
I am not sure what the symbolic links are for. Normally, you would add another web server virtual host for dev1.example.com pointing to the same Drupal root directory as dev.example.com.

---
Tags: 7, multi-sites, subsites
---


title: Min/Max Facet slider not working

text:
# Question
Title: Min/Max Facet slider not working
I am working on Search API. I am using Search API module, Facet API, Search API ranges, Pretty Paths modules to add facet filters.

All the filters working fine like select list, checkbox but Min/Max slider not working. When I am moving the slider, it gives 0 results to me.

How can I solve this problem ?

# Answer
> 0 votes
I got the answer. Pretty paths module creates the problem for this. I disables the Pretty Path module and flush the cache.

Now Min/Max slider working fine.

---
Tags: 7, search
---


# Question
Title: How to automatically create nodes from a bulk file upload
I've got a hundred or so files (mixed types: pdf, ppt, doc, etc). I want to be able to upload these to my server, and then point my D7 site to the directory on the server that contains all of these files so that the site automatically creates a node for each file, with a single, different file attached to each node. Is there a module that will do this for me?

# Answer
Using Bulk File Nodes you can create unlimited number of nodes at once .

> Bulk File Nodes allows a user to upload or import many files at once, and have many individual nodes created, one for each file . Where this module significantly differentiates from other modules like Bulk Media Upload is that after uploading/importing the file(s), the user is given the opportunity to edit all of the fields for each node in a single form.

This module creates a node for each file and you can edit the fields of each node after uploading.

---

# Solution 1

You are right, Bulk File Nodes works only with images. since you need to create nodes programmatically and assign the files to the nodes you can use the following code to create a node without a file field

```
$uid = SOME_USER_UID
$values = array(
        'type' => 'THE_CONTENT_TYPE',
        'uid' => $uid,
        'status' => 0,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'en'
);
$entity = entity_create ('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('THE_TITLE');

$ewrapper->save();

```

But from Attaching image files to nodes programmatically in Drupal 7 you can use the following code to attach the file to the above node

```
$filepath = drupal_realpath('misc/druplicon.png');
 // Create managed File object and associate with Image field.
 $file = (object) array(
'uid' => 1,
'uri' => $filepath,
'filemime' => file_get_mimetype($filepath),
'status' => 1,
  );

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$ewrapper ->field_file[LANGUAGE_NONE][0] = (array)$file;

```

This code should be above `$ewrapper->save();` line.

# Solution 2

You can also create the nodes without file fields as described above. and for each node with `$node` variable Programmatically Attach Files to Node.

```
// We have complete file path.
$file_path = '/whatever/path/to/file/sample.pdf';

$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location.
$destination = 'public://PDFs/';

// Make sure destination directory exists before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_pdf[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_pdf[$node->language][0]['display'] = 1;
$node->field_pdf[$node->language][0]['description'] = 'Our special PDF';

// Save node to make the attachment effective.
node_save($node);

```
> 2 votes

---
Tags: 7, files
---


# Question
Title: How to fetch customer shipping information from rule component?
I created a rule for that sends each product creator an email on the "Completing the checkout" event. The rule, component, and action all work, but I can't find the Customer Shipping Information tokens.

Can you provide insight or ideas on how I might get a token that would reveal the shipping information for my email? Below is my rule component and screenshots.

```
{ "rules_send_email_to_vendor" : {
"LABEL" : "Send email to vendor",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "component_rules_fetch_product_author" : { "line_id" : [ "list-item" ] } }
      ]
    }
  }
]
}
}

```

And below my rules screenshoot

# Answer
A couple of things, you actually have two rules:

1. The first is the event rule that loops through the products
2. The second is the component rule that fires off each email

> Interesting side note, given your setup, you will likely be sending an email per product and not per product creator.

To get the shipping address in rules when you have access to an order entity, you simply need to add a condition "Entity has field" and check that the "line-id:order" has the customer's shipping profile field (by default this condition looks like this):

Here's an animated gif displaying the process:
> 2 votes

---
Tags: commerce
---


title: Adding fees at each payment

text:
# Question
Title: Adding fees at each payment
I am using Commerce Fees module, as I want to add 5% as fees at the time of purchase.

I have added a fees type, and created a rule for this.

**My Problem** is that I whenever I go to checkout page where I have added some products such that my total order price is 1000, so I should be getting service tax of 50, but I am getting it to be 52.63 instead.

I am attaching my rules export, please help.

```
 { "rules_5_service_fees" : {
 "LABEL" : "5% Service Fees",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules", "commerce_fees" ],
 "ON" : { "commerce_fees_order" : [] },
 "DO" : [
   { "data_calc" : {
       "USING" : {
         "input_1" : [ "commerce-order:commerce-order-total:amount-decimal" ],
         "op" : "*",
         "input_2" : "5"
       },
       "PROVIDE" : { "result" : { "tax" : "Calculated Tax" } }
     }
   },
   { "commerce_fees_apply" : {
       "entity" : [ "commerce-order" ],
       "fee" : "service_fees",
       "amount" : [ "tax" ],
       "currency_code" : "USD",
       "include_tax" : "0"
     }
   }
 ]
 }
 }

```

# Answer
> 0 votes
Not as much of an answer as it is a recommendation. You should be doing this at the price calculation (per product) level, not order level. Not doing this can mean you're taking into account the taxes, shipping, other coupons/discounts, etc.

---
Tags: commerce, rules
---


# Question
Title: How do I allow user to select table column they want in Drupal View?
I am trying to create a Human Resources Portal for my organisation. I have to create a table via View to show all the list of staff of the organisation which is about 500 employees. My major problem is that not all the column is needed at every situation, sometimes they need to create a table with only few columns at a time, so I need to expose the users (HR Dept) the columns so they can decide which one they need at a time. I have tried MediaTable module but that does not allow the user to hide columns themselves. I need like a checkbox of columns to be selected. Thank you

# Answer
> 2 votes
Give a look at Views Dynamic Fields module. I have used it in the past to create selectable table columns to display for views.

> The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
>
> **Features**
>
> * Users can dynamically choose the fields to view in their rendered view instance
> * Default fields to show when no filtering is applied, can be configured
> * Possible to always keep certain fields to display to the user
> * An exclusion mode to allow reverse selection of fields when there are too many
> * Great for creating and exporting reports from the view
> * Works great with Fields Embed Views module

---
Tags: views
---


title: How to remember exposed filter choices?

text:
# Question
Title: How to remember exposed filter choices?
We're hoping there's already a module that will do this...

We are creating a page that will contain three view blocks. Each view will have a different exposed filter (all based on taxonomies.) The views are completely independent of one another; they're just going to display on the same page.

What we're looking to do is allow a user to set the filters on each view, and then have Drupal remember those filters. This will be available to authenticated users only, and we're hoping that the filter values can be remembered from session to session.

Example: View 1 will have a Retailer filter, so the user can choose to view all content about Target. View 2 will have a Manufacturer filter, so the user can choose content about General Mills. And so on for as many views as we choose to display on the page.

I know we could do this to a certain extent with javascript and cookies, but as I said, we're hoping it's already been done, as we're under a deadline. Does anyone know of a module that does this? I've tried searching drupal.org for user customization and exposed filters, but the results are overwhelming, and not entirely relevant.

# Answer
> 10 votes
There is an option in views for this. Go and edit the exposed filter, In the edit form there will be option called

**Remember** Remember the last setting the user gave this filter.

However I dunno, how to restrict this functionality only to authenticated user.

# Answer
> 2 votes
i made a simple Module that store User-Pager settings in $\_SESSION. It's very easy written just a couple of code lines. So it can be modified to store every user Settings in it. Please check it out:

http://drupal.org/node/1482424#comment-6709534

# Answer
> 1 votes
If you take a look to the code of content administration (admin/content/content) you will see that they use the $\_SESSION to store the information.

But as Mathankumer say, I think that Views should give it to you.

# Answer
> 1 votes
You can use Views Global Filter if you want to remember the filter value permanently.

---
Tags: 6, views
---


title: custom fivestar icons

text:
# Question
Title: custom fivestar icons
I am having an issue loading my custom icons for the Fivestar module; Here are the steps I am taking, I am hoping someone can point out what I am missing.

first I hook into the fivestar widget to add in my new theme.

```
function my_module_fivestar_widgets() {
  $module_path = drupal_get_path('module', 'my_module');
  $widgets = array(
    $module_path . '/images/bonestars/bonestar.css' => 'bone_stars',
  );

   return $widgets;
}

```

This `bonestar.css` is pretty much a complete copy of the basic theme. Inside the css I link to my images instead of basic, so everything so far seems safe.

Next I go to the views configuration and click under *Fields*, **Field: Rating**. I click the *SHOWSTAR DISPLAY OPTIONS* to select which star I want to use. I see my custom stars visually:

I select it and save it and apply to all.

So then I go to my view to check if the new star theme has been loaded, but it now loads basic. So I clear the cache as well, nothing.

I am obviously loading the images or something, but it doesn't translate to my view. What am I missing? I also test this on views, blocks, etc it never loads it on the actual site. Only in the settings as seen above.

# Answer
There are generally 2 themes used in Drupal:

* Main theme
* Administrative theme

On the view configuration page, the administrative theme and its css will be loaded. On the output page of the view (if it is not an administrative page as well) the main theme and its css will be loaded.

That means, you have to update your css in both administrative and main theme.
> 0 votes

# Answer
When I added my custom fivestar, I saw a similar issue, you do not have your CSS listed but check to see if in the css you copied, check to see if all instances of the **.fivestar-** class has your custom star name after the hyphen. i.e. **.fivestar-bone\_stars** Also of note, I answered this on another person's post here is a really nice tutorial on adding custom stars using file\_scan\_directory so that all you have to do is add a new folder and update the css and the hook will automatically pick it up.

Custom fivestar widget does not display custom icons
> 0 votes

---
Tags: 7, views, rating
---


# Question
Title: Where are admin/config/user-interface/archive setting stored
Where are these settings stored at. On the disk? In a database table?

# Answer
Generally, configurations in administrative pages are saved into `variable` table.

The path `admin/config/user-interface/archive` is not a Drupal core path. It must have been provided by a module. If you want to get a definitive answer, you should provide more information.
> 2 votes

---
Tags: 7
---


# Question
Title: AJAX select returns 'illegal choice detected'
Create a settings form for a module in Drupal 8 - when a user selects a View from a list, the drop down under it should populate with the displays in that view.

While the form updates the option list for the user, it also throws an error message on the screen "Illegal choice has been detected".

Here is the code (it doesn't paste very well):

http://cgit.drupalcode.org/tvi/tree/src/Form/SettingsForm.php?h=8.x-1.x

getViewDisplays is the ajax callback that is populating the options.

Some people who have posted about this around the internet say to set #validated on the select field to TRUE, though, that doesn't necessarily feel right. I still want to validate the submission to do some checks.

# Answer
> 6 votes
You can't populate the choices in the ajax handler. The ajax handler is purely for returning the re-rendered form. If you want to do more advanced stuff you can use ajax response but that's it.

What you need to do is to use form state storage to store the selected view name and submit handler that will set this value(ie copy the value form submitted values into storage) and rebuild the form.

In the form you have to check if the view is in the storage and if not set the default one and use it and if it is use that one. Load the displays in the form based on this view.

This is a portion of one of my forms:

```
<?php

/**
 * Defines an e-mail settings form.
 */
class EmailSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $system_config = $this->config('system.mail');
    $plugin_id = $system_config->get('interface.default');
    $definitions = $this->mail->getDefinitions();

    if ($form_state->has('mail_plugin_id')) {
      $plugin_id = $form_state->get('mail_plugin_id');
    } else {
      $form_state->set('mail_plugin_id', $plugin_id);
    }

    // Make sure the plugin exists.
    $plugin_id = $this->mail->hasDefinition($plugin_id) ? $plugin_id : 'php_mail';

    $ajax = [
      'wrapper' => 'email-settings-form-ajax-wrapper',
      'callback' => '::ajaxRebuildForm'
    ];

    $form['#prefix'] = '<div id="' . $ajax['wrapper'] . '">';
    $form['#suffix'] = '</div>';

    $form['email_plugin'] = [
      '#type' => 'select',
      '#title' => $this->t('E-mail provider'),
      '#default_value' => $plugin_id,
      '#required' => TRUE,
      '#ajax' => $ajax + ['trigger_as' => ['name' => 'email_plugin_submit']],
      '#options' => array_map(function($definition) {
        return $definition['label'];
      }, $definitions)
    ];

    $form['email_plugin_submit'] = [
      '#type' => 'submit',
      '#name' => 'email_plugin_submit',
      '#value' => $this->t('Submit'),
      '#submit' => ['::changePluginSubmit'],
      '#limit_validation_errors' => [],
      '#ajax' => $ajax,
      '#attributes' => [
        'class' => ['js-hide']
      ]
    ];

    return $form;
  }

  /**
   * Submit handler that will change the mail plugin.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function changePluginSubmit(array &$form, FormStateInterface $form_state) {
    $plugin_id = $form_state->getValue('email_plugin');
    $form_state->set('mail_plugin_id', $plugin_id);
    $form_state->setRebuild();

    // Set the e-mail plugin.
    $this->configFactory()->getEditable('system.mail')
      ->set('interface.default', $plugin_id)
      ->save();
  }

  /**
   * Ajax submit handler that will return the whole form structure.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function ajaxRebuildForm(array &$form, FormStateInterface $form_state) {
    return $form;
  }
}

```

It's not a perfect example since there are other things going on that I have removed for simplicity but you should get the logic.

---
Tags: forms, 8
---


# Question
Title: How to change all iterations of a string to another word?
I noticed that most of my Russian clients afraid "Таксономия" ("taxonomy") word, because the word sounds like something very complex and incomprehensible for them:)

I want to change all iterations of "Таксономия" to another word, for example to "Классификация", because this word is familiar to everyone in Russia.

So how can I change one word to another in ALL iterations of the word in translate system ON EXISTING site. In other words, how can I bulk update translation by some algorithm instead of edit each string manually?

# Answer
> 1 votes
I found the following fast, easy and safe way to replace strings in translation.

1) export translation to .po file

2) open .po in text editor and autoreplace all iterations of the string.

3) import the .po file with replacing option

# Answer
> 4 votes
**Method 1:** Edit settings.php file

*Pros*

* Quick method for small number of strings.
* Less accessible in cases where you want to retain some control even after granting administrator access.

*Cons*

* English only.
* No admin pages, requires access to files on server (FTP / SFTP / SSH).
* Difficult to delegate changes to non-developers.

*Procedure*

1. Edit settings.php for the site in question.

* You'll need to either download the file, edit it, and re-upload it, or edit it in place on the server. Of course, make a backup.
    * Either way, you'll probably need to temporarily change the permissions of the file and its containing folder to to give you "write access". Be sure to take note of the permissions and change them back to what they were afterwards.
    * The default settings file is in drupal\_root\_folder/sites/default/settings.php
2. Look for this code at the bottom

```
# $conf['locale_custom_strings_en'][''] = array(
#   'Old string 1'      => 'New string 1',
#   'Old string 2'      => 'New string 2',
# );

```
3. Remove the comment marks ('#') and add string replacement assignments:

**Method 2:** String Overrides module

*Pros*

* Admin page for managing string replacements.
* Uses access permissions. Easier to delegate management of replacements.

*Cons*

* Yet another module to install, update, and administer.
* Possible performance hit and more difficulty to deploy (stores replacements in the database).
* Uses access permissions. Harder to restrict changes when you have to give administrator access to others.

*Procedure*

1. Install and enable the module.
2. Follow the instructions / documentation for adding string replacements.

**Method 3:** hook\_boot()

*Procedure*

1. Implement the hook\_boot()
2. Use the same array as in the settings.php.

```
/**
  * Implements hook_boot().
  */
 function mymodule_boot() {
   global $conf;
   $conf['locale_custom_strings_en'][''] = array(
     'Old string 1'      => 'New string 1',
     'Old string 2'      => 'New string 2',
   );
 }

```

**Method 4:** Replace all the strings in the database

*Procedure*

1. Dump the database to a text file.

```
mysqldump -u user -p databasename > ./db.sql

```
2. Run a sed command to find/replace target string

```
sed -i 's/oldString/newString/g' ./db.sql

```
3. Reload the database back into MySQL.

```
mysql -u user -p databasename < ./db.sql

```

*Note: All commands are bash commands on Linux, but you can replace them with another method.*

**References:**

---
Tags: i18n-l10n
---


# Question
Title: how to obtain fivestar field value in rules?
I'm trying to a grab a value of a fivestar field within rules and having no luck.

Basically I'm getting users to fill a feedback form and if the fivestar field value is less than 3 Stars then I want the rule to fire but no luck.

Can someone help me figure out to what's going wrong.

Thanks

# Answer
> 2 votes
I'm not sure about forms, since you didn't mention how you set those up on your website, but I can help you with the case where the Rule is called after saving a new comment with a Fivestar field, say it's called *Stars*. Follow the guidelines underneath for your Rule:

**Events:** After saving a new comment.

**Conditions:**

* Check whether the comment has a field *Stars* with *Entity has field*.
* Check whether the field *Stars* is not empty with *NOT Data value is empty*.
* Run this custom code: `return $comment->field_stars['und'][0]['rating']<=60;`.

Adapt these steps to your needs. Be sure to compare the rating with a score out of 100, since Fivestar works internally with percentages.

---
Tags: 7, rules, rating
---


# Question
Title: How do I add a password field during registration?
i am using Drupal 8. I want to set the password field and confirm password field during registration. On admin/configuration this option is not available. Is there a setting to achieve this?

# Answer
Yes. Disabling email confirmation. Which you probably don't want.

Drupal doesn't *really* have mail confirmation. It just doesn't tell the user his password, and then he gets a password recovery link and can provide a password after that.

I've built a custom module for this that allowed it for a project, you basically need to add a field to users, prevent login if that is not set, set it on the first login through password recovery. Change the user registration submission to send a confirmation mail anyway. And care about some special cases, like admin created users. Not trivial.

There are contrib modules for this, for example https://www.drupal.org/project/user\_registrationpassword. there's no official release yet, but maybe someone started porting it.
> 3 votes

---
Tags: 8, users
---


# Question
Title: The results within the page results do not lead to the nodes
I do not know how to treat *this problem* with Drupal. I hope you can help me.

Suppose this. We have a glossary (Views), which shows the items of the content type called "Glossary".

I created a search engine Views, following these instructions.

Now, I open my website and try to find one of the words of my glossary site.

Result: Well, the results page returns the title of one of the nodes of content type "Glossary", good! If I click on that word, then word node (which belongs to the glossary) is displayed.

But I do not want the node is displayed. I want that word is displayed within the glossary. Glossary nodes should not be viewed independently.

Is it possible that the word shown in the results page glossary is leading the glossary, and not their respective node?

Thanks in advance.

# Answer
Yes, you can change the link settings from within the field settings on the view (or, if you are rendering nodes, you will have to change it in the display settings or template files if you are showing teasers using default templates).

Once you've edited your view, you might consider using the Rabbit Hole module to further deal with unwanted Node views.
> 3 votes

---
Tags: nodes, views
---


# Question
Title: How can I enable JavaScript form validation for AJAX submit buttons?
Drupal 8 comes with client-side JavaScript form validation; however, for a submit button with #ajax, it is disabled. How can I enable it?

# Answer
> 5 votes
I had the same question this morning. Here's how I got it to work.

Add an invisible button and specify the `#ajax` on that.

```
$form['actions'] = array(
  '#type' => 'actions',
  'submit' =>array(
    '#type' => 'submit',
    '#value' => 'Submit',
  ),
  'validation-hack' => array(
    '#type' => 'button',
    '#value' => 'validated',
    '#attributes' => array('style' => 'display:none'),
    '#ajax' => array(
      'callback' => array($this, 'doSomething'),
      'event' => 'click',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'Example...',
      ),
    ),
  ),
);

```

Then add a `submit` handler on the form that stops the form submission and then calls `click` on the hidden button.

```
  (function($, Drupal) {
    Drupal.behaviors.example = {
      attach: function(context, settings) {
        $(context).find('#example-form-id').submit(function(evt) {
          evt.preventDefault();
          evt.stopPropagation();
          $('#edit-validation-hack').click();
        });
      }
    }
  })(jQuery, Drupal);

```

Hope this helps you, or anybody else that may stumble across this.

---
Tags: ajax, 8, forms
---


# Question
Title: Integer user form field with min 11 digits and max 11 digits
I need an integer form field with has a validation of **min 11 digits** and **max 11 digits.** In other words; the user has to fill in an 11 digit code.

How do i make this field and validation?

**Update:**

I managed the field by setting a min of `10000000000` and max of `99999999999`. But now i get this validation message:

> RIZIV number: the value may be no greater than 99999999999.

How do i change this validation/error message to something like:

> Fill in your right 11 digits RIZIV number.

# Answer
> 0 votes
Go to `admin/config/people/accounts/fields` add an integer field and set the limitations and by hook\_user\_update you can check the validation after saving the user profile.

---
Tags: 7, users, entities
---


title: Sorting Views by current week

text:
# Question
Title: Sorting Views by current week
The Date module with Views has functionality to filter dates with a granularity by Day, Months, Year, etc. but not for weeks. So to do this with a Contextual Filter and PHP code to retrieve the current week, I tried this:

This had an output that suggested the current week was the fifth of the year which would be in February as shown here:

Yet the output is correct without any filter as shown here:

With other PHP code to filter the View by days and months, it worked great. Yet this week filter doesn't seem to know the current week of the year. How can I either have the Date module filter with a granularity of weeks, or input the correct PHP code to have the list filter by the current week?

# Answer
I was able to find a solution by using two separate filters.

The **first filter** will be a relative for the current day. It should have an operator that is greater than or equal to today.

The **second filter** will be a relative day as well. It will have an operator that is less than +7 days.

This will allow you to filter views by the current day plus seven days.
> 2 votes

# Answer
Try this:

same steps as Views Contextual Filter by current day

except for relative date: put **week**
> 1 votes

---
Tags: 7, views, datetime
---


# Question
Title: Create a commerce product and add it to cart using Services
I am using **commerce\_services** module and **poster** as addon in firefox for my services. I want to create a commerce product and add it to cart using Services. I don't know what are the parameters and url to be provided. Please help...

Here is the poster.

# Answer
> 0 votes
Here's a link to the Commerce service's README.txt which includes a bit more detail on what kind of abilities it brings out of the box.

> The following grid indicates what callbacks have been defined so far out of the current target set of resources:

```
Resource         | Index | Retrieve | Create | Update | Delete
-----------------|-------|----------|--------|--------|--------
product-displays |   Y   |    Y     |   -    |   -    |   -
products         |   N   |    N     |   -    |   -    |   -
carts            |   N   |    -     |   -    |   -    |   -
orders           |   N   |    N     |   N    |   N    |   N

```

> The additional relationships and targeted actions are slated for development:
>
> product-displays: products products: add to cart carts: empty, convert orders: payments

So then the question is: Can you do what you want with commerce\_services?

**Can you create a product?** *Not according to the README*

**Can you add a product to a cart?** *Not according to the README*

---
Tags: commerce, services
---


title: ssl with boost and securepages module

text:
# Question
Title: ssl with boost and securepages module
I have this doubt. I have a website in drupal 7 currently live (Kickstart2) and use as cache management boost I have to buy a ssl certificate on my domain and with this certificate I would like to cover only the path checkout/\* and user/\*

I would like to proceed in this steps:

1. buy ssl certificate for the main domain
2. install the module securepages
3. configure the module with the path checkout / * and user / *

by this configuration I expect something like that: http://www.example.com/mypage but https://www.example.com/checkout only /checkout will be in https. Is it right?

This is just as reasoning and how to configure the module? Is it the right way?

Last question: I read that boost module does not work well with ssl, that it means that my checkout/\* pages will not be under cache, but the rest of the pages? Rest of the path like /about or /news are all done under cache? You can confirm this to me?

Ty guys

# Answer
> 1 votes
1. Should I use securepages?

**No.** The best practice these days is to just go with https for the whole site.

2. How do I go about caching my https content?

On a normal site, the https wouldn't matter, you can cache static content regardless of how encrypted it travels. BUT. The caching questions are legitimate because it is an eCommerce site and with that (by default), even anonymous users will have a session. Most default caching systems do not work with per-user sessions, unless you use something like authcache.

---
Tags: commerce, caching, ssl
---


# Question
Title: How to add Wishlist button field in views in drupal 7?
I am working on commerce site. In my site I have 3 views & each view have display 3 products. If user can first visit the product then user get the wishlist button but I want to show "add to cart" or "wishlist" or "buy" button with all the products so user can directly purchase, no need to visit.

I already created **Relation : "Content: Referenced products"** & add **Field : "Commerce Product: Add to Cart form"**. But no button show below product. Please help to solve. Thanks

# Answer
> 1 votes
Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display\_suite or panels to get more advanced control over what your products look like when rendered.

Sidenote, there's a great video I created that shows you how to use `hook_form_alter` to move the wishlist button around.

---
Tags: views, commerce
---


# Question
Title: Subtotal calculates from original product price, disregards applied per product discounts
This seems like a known issue but I actually didn't find a solution for this anywhere.

In commerce, if I apply a discount/pricing rule to a certain product, add it to cart, and go to checkout, table would say eg

```
Product - 120$ (discounted from original 200$)
Subtotal - 200$

```

The subtotal is taken from the original product price and doesn't include the applied discount. It would be a lesser problem if that was just display issue. But the tax is then actually calculated from the subtotal, making the order total wrong

Is there a solution for that?

# Answer
Since this question is now almost 2 years old, I assume this "discount" that they were dealing with was an older version of commerce\_discount. The newest version doesn't have any kind of subtotaling problems because it affectively utilizes the price calculation system for discounting.
> 0 votes

---
Tags: commerce
---


# Question
Title: Drupal Commerce: Allow anonymous users to choose password
I'd like to allow anonymous users to make purchases on my store, however I don't want them to have to login and then change their password as their first port of call. Is there anyway I can collect a password from the customer during checkout, like it is possible to in Ubercart 3 and with LoginToboggan?

# Answer
> 1 votes
You should look into modules that handle this use case. See below for examples:

https://www.drupal.org/project/commerce\_checkout\_complete\_registration

https://www.drupal.org/project/commerce\_checkout\_redirect

https://www.drupal.org/project/commerce\_login\_step

https://www.drupal.org/project/commerce\_extra

---
Tags: 7, commerce, users
---


title: Discount for each additional Item

text:
# Question
Title: Discount for each additional Item
I'm trying to set up a discount in Drupal Commerce for each additional product ordered. The first product is full price and all subsequent products should be discounted $20. I can have every product discounted, but have not been able to have the first product at full price. For example, if I have 3 of the products in the cart the discount is $60 (all three products discounted) and not $40 (only the second and third product should be discounted).

# Answer
You could potentially add a "data comparison" condition to your existing discount rule that would effectively do this:

current-user:order:line-items:0:commerce\_product:id != product:id

Which would say "only continue if the first line item's product id isn't the same as this product id" but would totally fail if you had some other line item added to your cart before your first product. If that is the case, then you would need to create a custom rules condition.
> 0 votes

---
Tags: commerce
---


# Question
Title: Permission Conflict - Commerce Order - Please give me a guidance
Today I a faced a confusing problem in my project.

let me introduce my project briefly.

I am creating a shop with drupal 7 and commerce module.

In my site 2 kinds of people exist. some people are seller and the others are customer. I have created a role called "SELLER" for seller users.

as you know each member has a specific page in his client area called "orders". in this page a member is able to see his orders (it is history of user orders)

and in drupal 7 permission, it is defined that each person is able to see his/her orders only. there is no permission to see the other people's orders. (ONLY ADMINISTRATORS CAN SEE ALL ORDERS)

but in my project, I want to give permission to the sellers to see the other people' orders that contains at least a product that the current seller has introduced.

let me give you an example. Imagine that we have a seller user in our site. his id is "seller\_1" seller\_1 is selling product\_1, product\_2 and product\_3 in site.

now a new user we called him "customer\_1" wants to but product\_1 . he make an order and complete it. imagine that order number is "100".

now an order is saved in database and "customer\_1" is able to see this order (order number 100) in orders page.

but in my plan the user "seller\_1" must be able to see the order number 100 in a specific page that is created via a view.

=============================================

I tried to run this scenario but I have not found a solution yet.

in permission page, I gave "ability to see all orders" permission to seller roles. this modification solved my problem but it really breaks the security of site. because if we grant ability to see all orders to "SELLER" roles, the seller people are able to see all orders in the site even though there is no related product in the orders.

Now, do you have any suggestion for me?

Thanks a lot for your helps.

# Answer
You would need to produce a custom permission using hook\_permission that grants permission for sellers to see orders of their customers.
> 1 votes

---
Tags: views, users, commerce
---


# Question
Title: Selecting a product attribute from a select list won't update other attribute fields
I'm working on a store created with Drupal Commerce where I have first created a product variation, then I created a corresponding product display type and finally I created different products, e.g. mattresses.

Now I find myself stuck with this problem: I have mattresses of different size and I have a product attribute (within the product variation) accounting for the different sizes - I have the option "Enable this field to function as an attribute field on Add to Cart forms" already checked.

When I select a size from the select list, the product price changes and displays accordingly but other product attributes, i.e. the sku, displaying on the same page, does not update.

Now, if I move on to the cart summary I can find the right sku, it looks like the price updates without the need for a page reload, while other custom attribute fields don't (you can see all of this live at http://www.dormiplus.it/cms/?q=it/materassi/stella, where "codice" is equivalent to sku).

How can I have the right sku displaying correctly whenever I select a different mattress size?

# Answer
1. Why don't you have the clean urls enabled?
2. I think for the ajax to function, we might require or at least assume clean urls. That may be all the problem is.
3. The reason your injected fields aren't changing is because of a javascript error, and it is often not related to Drupal Commerce at all, could be a theme issue.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Entity Reference field in custom line item missing multiple field values
I added an entity reference field to a line item within commerce.

Target is user, entity selection is done through a custom view. The view populates the values of a date field within the actual user entity. The preview works as desired, the field has 3 values and those 3 get shown in the views preview.

However looking at the add to cart form it always shows just the last value of this multiple value field. Why are not shown all 3 values in the add to cart form?

# Answer
Line-item entity reference fields being displayed as views is most likely not supported, or not very well supported, because it's a very edge-case situation. Nothing appears to be in the issue queue regarding this limitation, so you might make a feature request and see where it goes.
> 0 votes

---
Tags: entities, commerce
---


# Question
Title: limiting shipping method if a specific product is selected
I am trying to limit a number of shipping methods (from 5 to 3) if a specific product is chosen and inserted into cart. What is the best method to do it (I am using drupal commerce)

# Answer
> 0 votes
You are looking for how to add a condition to each of your shipping services for a specific product or two? Here's a quick animated gif that shows you the gist of what you want:

---

---

1. Locate your shipping services
2. Click "edit component" to control which service needs to be hidden based on a particular product
3. Add a condition called "Order contains a particular product"
4. You would need to check the "Negate" checkbox before saving to "show all the things unless this product is on the order." Which sounds like what you are attempting.

Good luck!

---
Tags: commerce
---


# Question
Title: Drupal 7 + Commerce + Addressfield remove specific <div> from form markup
i use drupal + commerce + adressfield and i am cleaning up the checkout-page form markup (at least i try).

i am familiar with the theme functions of form.inc and have removed some divs aleady using this functions but one of the divs i dont know were it is defined.

dpm(); says it resides in `$element['#children']` but `['#children']` is the whole markup including the div i want to remove.

to be clear: i want to remove the red marked outer div only!

# Answer
The user's answer in the comment is wrong. We never want to hack a module. But we can use hook\_form\_alter() to modify the #suffix and #prefix.
> 0 votes

---
Tags: forms, commerce, theming
---


# Question
Title: A Product Page with dynamic variants without using Commerce
I have a page that is product page for an offline product. This product will never be sold through the website, so the Commerce module would be serious overkill I think. There are some features of the the product pages I've seen possible in Commerce that I need though. Like product colors.

For what I'm working on, the product model has different builds, **(see the wireframe image)** and each build has different color options. I need to be able to toggle back and for between color options for a build, and build options for the model.

I would like the model to be all one content type. There are common elements in the model that should stay the same no matter what the build, but items that are build specific that should update when a build is clicked. I'm still trying to figure out the best way to structure the content type fields and such too.

I'm sure someone has had a similar need and I'm looking for tips in the right direction for the content type and the display. Since everything is part of the same content type, I figured I'd use a specific layout and use Panels to stitch it together, especially since I have related content to the model below the product.

Here are my direct questions: How would I go about segmenting the different build levels in the same content type?

What would be the best way to pull all this back into a display and have the right areas work to allow the large image of the product be able to be switched when the color links are actioned and then have all the right parts change when a different build is selected?

# Answer
As the user eluded, display suite or perhaps panels would be the go-to way to dealing with customized multi-column content type displays. Often on commerce sites, the quick tabs module is used to display tabbed product information.
> 0 votes

---
Tags: nodes, commerce, panels, theming
---


# Question
Title: commerce kickstart - how to edit a view ? the link is missing
I am really clueless why the edit link of the view is gone in Drupal Commerce, even Drupal 6 used it before.

Where is the edit link?

# Answer
It is available if you enable the "Contextual Links" module.
> 0 votes

---
Tags: views, commerce
---


# Question
Title: Have to hook into a function from a module
I am using the LinkedIn Integration module and have created a custom module to add some functionality.

Please see the linkedin.inc file at line 17 - function linkedin\_access\_token($account)

When a user links their LinkedIn account, I want to add to the db\_write\_record to also write to a custom field in my database for a timestamp.

Not sure what hook to use since it is a function.

# Answer
> 1 votes
Just making a quickly research (I don't have time at this moment to test the code) inside the Linkedin Integration module I can tell you that I found a hook named `linkedin_external_login`

See the code in the linkedin\_auth/linkedin\_auth.module file in the line 124

```
/*
 * Implementation of hook_linkedin_external_login
 */

function linkedin_auth_linkedin_external_login($uid) {
  $name = db_query("SELECT authname FROM {authmap} WHERE uid = :uid AND module = :module", array(':uid' => $uid, ':module' => 'linkedin'))->fetchField();
  user_external_login_register($name, 'linkedin');
  drupal_goto();
}

```

Just implement your own `hook_linkedin_external_login()`

---
Tags: 7, hooks
---


# Question
Title: Views relationship not been added by code
Im trying to make a abandoned cart notification module, trying to relate my notification table with the commerde\_order table by its order\_id in views. Right now i have this in my hook\_views\_data

```
function commerce_abandoned_cart_notification_views_data(){
    $data = array();

    $data['commerce_abandoned_cart_notification']['table']['group']  = t('Commerce abandoned cart notification');

    $data['commerce_abandoned_cart_notification']['table']['join'] = array(
        'commerce_order' => array(
            'left_field' => 'order_id',
            'field' => 'order_id',
        ),
    );

    $data['commerce_abandoned_cart_notification']['table']['base'] = array(
        'field' => 'id',
        'title' => t('Commerce abandoned cart notification'),
        'help' => t('Commerce abandoned cart notification'),
    );

    $data['commerce_abandoned_cart_notification']['id'] = array(
        'title' => t('Notification ID', array(), array('context' => 'A Commerce abandoned cart notification internal ID')),
        'help' => t('The unique internal identifier of the notification.'),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    $data['commerce_abandoned_cart_notification']['order_id'] = array(
        'title' => t('Order ID', array(), array('context' => 'A Commerce order ID')),
        'help' => t('The unique internal identifier of the order.'),
        'relationship' => array(
            'base' => 'commerce_order',
            'field' => 'order_id',
            'handler' => 'views_handler_relationship',
            'label' => t('Referencing order'),
        ),
        'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_string',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
    );

    return $data;
}

```

The problem is that when creating a view i do not see my relationship to commerce orders or viceversa, (the hook works because i can create a view of type commerce\_abandoned\_cart\_notification and add some of its fields). I know there is a commerce\_abandoned\_cart\_notification or commerce\_notification module but they seem incomplete and/or abadoned

Should i use hook\_views\_data\_alter to alter commerce\_order relatations and add one to my custom table?

# Answer
Have you considered using the module Commerce Notification?
> 0 votes

---
Tags: commerce, views
---


title: Show old price with line-through

text:
# Question
Title: Show old price with line-through
I have Drupal 7, without Drupal Commerce modules installed, because we are nor e-commerce place. For some items, we need to show up two prices (old\_price and new\_price). Only for items for new\_price filled I need to show up old\_price line-trough or with an X on top. I suppose that I need to put some code in someplace, but where?

I have been looking for a module, but all modules are for commerce. I do not want to install commerce and all the pile of commerce modules just to add this feature.

# Answer
First, create two fields-"Old price" and "new price". Second, use css `text-decoration:line-through;` on the old price field.

Edit:

Based on your comment and clarification, I would suggest using rules and rules bonus pack to look for the "new price field", then have it add a body class to the node.

Your rule will look something like

* Event #1: "when content is created"
* Event #2: "when content is updated"
* Condition #1: "entity has field", then select your "new price" field
* Condition #2: "Data value is empty" and enable "negate"
* Action: "Add body class"

Then in your css add the strikethough based on the extra body class.

This is essentially how the Commerce price savings formatter module works, but without the overhead of using commerce.
> 1 votes

# Answer
Or you could use the module that does this formatting for you.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: Seller and Buyers Own Comments (Commerce Communicae)
I would like to have a way for my seller/author (author of node) and my buyer/user (not author of node) to communicate.

First, I have looked at the comments. If I allowed buyers to only start one comment and seller only able to reply to that buyer's one thread.. I envision buyer adding comment and seller only being able to reply to that comment. the seller would also see comments from other buyers; one thread per buyer so the conversations are grouped by buyer; for the seller to see. The buyer would see only their initial starting comment and any replies from the seller.

If used a view to contextually filter for same exact node and contextually filter for logged users authored nodes. basically showing the same node if logged user is seller. then I just use view mode to display the comments only. this results in the seller/author seeing entire comments.. in this case id only have to limit buyers/users to making one comment thread and the seller/author view would be 'finished'

How do I limit buyers/users from posting only one initial tread that buyer and seller reply back and forth. so from sellers view, they see buyers only once in comment list and the conversation there.

For the buyer I haven't been able to use view block to make correct relationships to get the buyers initial comment thread as well as the authors replies to it..

1. Should I use two views and better filters and relationships, (or even 1 view?)
2. Should I make new content types or entities instead of using comments? (id hope to leverage the comment form, and email alerts and rest of comment stuff instead of making new framework
3. Should I consider other modules or organic groups? (again comments is so close id hate to reinvent the wheel.
4. Should I consider livechat module and have it make a separate chat channel per item, per buyer/seller?

**Edited** It seems to me that if I can keep user making only 1 comment, if I can target the start of the thread I can then say grab only the buyers comment starting tread.

**Added** So tried entity construction kit and was further than comments is already from my goal. used entity reference field so in node edit you saw a message text field; didnt want that.

Also tried some modules for buyers to only start one comment thread. onecomment, one\_comment\_only... did not have what I was looking for.

# Answer
> 0 votes
Have you tried commerce\_message? In Kickstart 2, we created an order commenting system, where buyers and sellers could leave messages for each other and the system could also leave notes about the history.

---
Tags: views, commerce, comments
---


# Question
Title: Why my query string generates page not found for my view?
In Drupal 7 I'm using a view export to download information for my orders.

If i go to the default url `/admin/commerce/orders` then the page downloads correctly.

However, I also have some filters so I can download only the orders I need, this passes a query string to the view which causes a 404 error (page not found).

In example:

> /admin/export/orders?status\[0\]=invoiced&event=All&school=&uid=&held=All&attach=admin\_page

I can't find out why this is causing a 404 error.

I have another view with the same configuration and it works fine. It is a number of query or something?

# Answer
Are you using views\_data\_export? The most likely reason you are getting a 404 (are you sure it's not a 401?) is that your path starts with "/admin" and the menu system may be protecting it because its not sure which view you are loading.

Also, by default, Commerce rewrites all order and product SQL statements to enforce the permissions system. You can turn off the SQL rewriting if you know what you are doing (this is a security risk).
> 0 votes

---
Tags: 7, commerce, views
---


# Question
Title: Profile2 Registration Path loose registration field after translate URL alias
I use Profile2 and Profile2 Registration Path module. This is the original `Registration Path`, set in the configuration.

I tried to translate the `Registration Path` at `Administration » Configuration » Search and metadata » URL aliases`.

But when i visit for example the Belgium dutch version, i loose my extra added Profile field at my Registration form (RIZIV number)?

# Answer
Profile2 Registration Path module does not support multilingual URL aliases. Profile2 fields are added to reg form based on the alias that you set up on profile2 edit form. That is why your profile2 fields are not displayed on dutch version of reg form. Your best choice is to remove translated alias and set your original regpath alias to something that sounds good in both languages. Or you can improve the module by adding multilingual alias support (though it may require some reworking in module's logic).
> 0 votes

---
Tags: 7, users, i18n-l10n
---


# Question
Title: Programmatically creating users attach profiles to correct uid on localhost but uid 1 on production
While programmatically importing thousands of users from an old site, I'm facing this very strange behaviour. The code snippet below correctly attach commerce customer profiles to the created users on localhost site, but attach them to `uid 1` on production site !

*localhost is a strict copy of remote site : git clone for code and Backup and Migrate DB copy* The users are imported uploading and parsing a csv file in a custom form, connected as admin

```
$new_user = array(
  'name' => $new_name,
  'pass' => $pwd,
  'mail' => $email,
  'init' => $email,
  'status' => 1,
);

$account = new stdClass;
$account->roles = array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  9 => 'client',
);

if ($saved_user = user_save($account, $new_user)) {
  dpm($saved_user, $new_name.'/'.$saved_user->uid );
  //VERY STRANGE HERE (ON PROD SITE ONLY) see screen capture below
  //the dpm title prints $saved_user->uid as a new uid
  //but "inside" dpm $saved_user->uid is 1 !
}

//create user commerce profile
$profile = commerce_customer_profile_new('billing', $saved_user->uid);
$profile_wrapper = entity_metadata_wrapper('commerce_customer_profile', $profile);
//... add profile values ...
$profile_wrapper->save();

```

**Localhost : expected uid** when `dpm($saved_user, $new_name.'/'.$saved_user->uid );`

**Production site : uid 1 instead.** The user is created with the new uid though, but uid 1 is passed then to commerce customer profile

# Answer
> 0 votes
Sounds like somewhere in the first few lines of code your $account variable is getting switched to the user 1 or perhaps the currently logged in user. Perhaps trying to change the "$account" variable name to something definitely unique to see if that fixes the problem.

---
Tags: commerce, users
---


# Question
Title: Get all databases name present in Postgres Server in Drupal 7 Form API
I was currently developing a module and I want to display the names of all the databases present in my Postgres server through a query. I want also to query and list the names of schemas, tables, field and field type of each databases. How can I do that? I want to do this because I was making an interface about database connections and configuration. Is that possible?

# Answer
> 3 votes
One solution can be configurate the external database as a second database in settings.php.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'postgres',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

```

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute `db_set_active('external');`

When you want to switch back to the default database you execute `db_set_active();`

Example code to switch to and query the external database:

```
db_set_active('external');
$result = db_query('SELECT something FROM {sometable}');
while ($row = db_fetch_array($result)) {
  drupal_set_message($row['something']);
}

db_set_active();

```

***And here are the queries that I have used for a similar project.***

Getting the Databases:

```
SELECT datname
FROM pg_database
WHERE datallowconn = true AND NOT datname = 'postgres' AND NOT datname = 'template1'
ORDER BY datname

```

Getting the Schemas:

```
SELECT schema_name
FROM information_schema.schemata
WHERE catalog_name = 'DATABASE_NAME' AND schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema'
ORDER BY schema_name

```

Getting the Tables:

```
SELECT table_name
FROM information_schema.tables
WHERE table_catalog = 'DATABASE_NAME' AND table_schema NOT LIKE 'pg_%' AND table_schema <> 'information_schema' and table_type = 'BASE TABLE'

```

Getting Fields and Field types

```
SELECT ordinal_position, column_name,
CASE
WHEN character_maximum_length > 0 THEN concat(data_type, ' (',  character_maximum_length, ')')
ELSE data_type
END
AS data_type, is_nullable, column_default
FROM information_schema.columns
WHERE
table_schema = 'SCHEMA' and table_name = 'TABLE_NAME'

```

**Reference**

---
Tags: 7, forms, database
---


# Question
Title: How to count the number of unique views of a node?
Is there any possible way to find the number of views of a node.

For example:

I have created a node called "Sample".

**If i viewed it once then the count should be increased as 1 view and when i view the same node again it should not get increased.**

Is there any module to do that..

Else what's the best way to do it ?

# Answer
> 4 votes
It depends how much traffic you site has and how big your server is. If you need to create a view count like this, it will require that you disable page cache making your site slower and demanding more resources from your server, or run expensive queries on every node view.

You could do this with Drupal, but there isn't a module that provides this functionality for you. The statistics module will count all views of the node. To implement this you would need to use either `hook_node_view` or `hook_boot` and write to a database the nid of the node being used and a token for the user. If you don't want to count anonymous users, you can use the uid, else you would have to use a combination of uid and session id to try not to count the same anonymous users twice.

A better way if you have a lot of traffic is to use an external tool like Google Analytics and then draw data from there.

Both solutions will require custom code though.

# Answer
> 2 votes
Enable **statistics** module in your site and then go to configuration of statistics module which is at

--\> admin/config/system/statistics.

--\> CONTENT VIEWING COUNTER SETTINGS check "Count content views".

Then go to any node like node/1 or node/2, at bottom see the number of reads like "1 read" / "50 reads" you can also find the number of **node views in any View** go to -\> add fields and search --\> " **Content statistics: Total views**" This will bring node views to your content.

# Answer
> 1 votes
There indeed indeed appears to be contrib module that provides *unique* page visits for an entity. I haven't used it yet but just came across it when search for this https://www.drupal.org/project/piwik\_stats.

# Answer
> 0 votes
For Drupal 6 you can use "Statistics Advanced" module that allows to track only unique visitors.

For Drupal 7 this module has unstable version http://drupal.org/node/816040

# Answer
> 0 votes
Statistics module has a short API for doing this job

```
$nodevisit=statistics_get($node->nid);
print $nodevisit['totalcount'];
print $nodevisit['daycount'];

```

---
Tags: nodes
---


# Question
Title: How to obtain a list of the submodules of a module using Drush?
I want obtain trough drush a list of the availables submodules that comes inside a module.

So far this is what I have achieved:

```
drush pmi views_*

```

I obtain a detailed info for all the modules and themes starting with views in his name. (views\_ui, views\_bulk\_operation, etc)

```
drush pml views | grep views_

```

In GNU/Linux systems I obtain a list of availables modules and themes starting with views\_ in his name (views\_ui, views\_bulk\_operation, etc)

But I can't obtain only the submodules of a module.

**Edit:** I'm using Drush 5.10.

# Answer
> 2 votes
A submodule is a convention rather than a 1st class citizen in Drupal. There are only Modules, Themes and Profiles in Drupal in Drupal 7, and perhaps you could list Configuration in Drupal 8.

A submodule in Drupal 7 at least is simply a convention that a Drupal 7 may contain within it additional module(s). Because a module in Drupal 7 is merely a folder with a given machine\_name and an info file declaring that folder as a module to drupal.

The only thing I could think of attempting for your inquiry is to scan with the `drush pmi` outputs `path` value or even easier use a custom command with PHP and SQL to scan the drupal `system` tables `path` entry for nested values and outputting the name of modules that share nested directory paths. Such a tool could be written as a drush script or command of course. If these details aren't enough to clue you in on it's implementation, if my schedule clears up I may reply with an implementation.

**Note:**

Scanning the directory paths could produce errorenous results. There's nothing stopping you from placing modules within other modules. Much in a similar way many people make custom: contrib, custom and features folder in their modules folder. Of course this would lead to confusing output.

# Answer
> 4 votes
This information is available via the `pm-projectinfo` command:

```
$ drush pm-projectinfo views
 Name         :  Views (views)
 Version      :  7.x-3.13
 Extensions   :  views
                 views_test
                 views_ui

```

This command is available in Drush 8, and was first introduced in this PR. It is also available in Drush Extras for older versions of Drush.

---
Tags: 7, drush
---


# Question
Title: How do assign a role to user after add to cart in ubercart in drupal 7?
I am using ubercart for my site.. I need to assign a role to user after shopping with price base.. If user does $300 shopping then role 10%-role . if user does $400 shopping then 20%-role etc.. And remember these role next shopping.

# Answer
> 0 votes
Try to do this using Rules.

1. Add a new rule on event **complete checkout**.
2. Give your required conditions.
3. Add **Assign role to user** as action.

For your scenario you can do it using multiple rules.

Hope this will help you.

---
Tags: ubercart
---


title: Change the input format in drupal 8

text:
# Question
Title: Change the input format in drupal 8
I would like to know how to change the input format (automatically or by sql ) for all articles in my website, because I migrated from D6 to D8 and I face a nasty bug that requires to edit all my nodes (more than 2000) manually and set either filtered HTML or FULL HTML format to all nodes.

# Answer
> 0 votes
In node click the (+) and you will see more tables. For example: node\__body

All you gotta do now is export this table as a CSV. Open the file on Microsof Excel. Then CTRL+F click on the replace tab, and replace filter\_html with full\_html. Save and import back to database, check mark replace data option. Then in Drupal clear the cache.

# Answer
> 1 votes
Thanks to No Sssweat. His answer works. But I prefer to use sql so here it is.

Using Phpmyadmin navigate to node\__body table (or just search it) then in SQL tab, write this:

```
UPDATE `node__body` SET `body_format`='full_html' WHERE `body_format`='full_html1';

```

Please notice the following:

* in my case, I use different body format in my website so it is not good to change all body\_format to full\_html.
* after the migration I got full\_html1, but you may get different body\_format.

After execution the SQL command, Clear **Drupal cache**

---
Tags: migrations
---


# Question
Title: What do the js-text-full and text-full in the StringTextAreaWidget class do?
I am planning to create a field type to use as *hidden captcha*: a field that is hidden to users using a browser with enabled CSS, used to verify if the user registration is not done by a human being. I though to derive its widget from the `StringTextAreaWidget` class, but I noticed that `StringTextareaWidget::formElement()` uses two CSS classes: js-text-full and text-full.

What do those CSS classes do?

I would like the widget to be very similar to the textarea used to enter a long string, except that a CSS class I add would make it invisible. I would not want that the existing CSS classes would interfere in some way.

Alternatively, is there another class I should use? I see there is a `TextareaWidget` class, but it seems for text with an input format associated, while I would need just plain text, without any input format associated.

# Answer
These are classes that Drupal sets for its own css and js. For javascript it is always with the prefix "js". At first sight this seems to be redundant. The reason is, if someone wants to override the css class, it doesn't effect the js behavior and vice versa.

If you want to address the field through your own css, you can always target the field name "edit-mytextfield". If you use a class with the name of a text format, there is a chance, that you target other fields you don't want.
> 2 votes

# Answer
I'm assuming that full means that the text are widget uses the full text format.

According to the drupal 8 standard classes that are used by JavaScript to select elements should start with the js prefix. That way the themers will know not to remove them.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to properly compare values of two identical entities?
I have a custom entity that is not revisionable and I need to store any differences made by the user - and only differences, so if nothing has changed there should be no entry.

I am doing this in preSave method because the original entity has the same format as current entity(ie. some fields do some value processing and therefore the original entity does not match the current entity exactly in postSave method).

The issue I am facing is that I cannot properly compare values($entity-\>toArray()) because the data is not consistent. For example in the original entity a field's value can be 123.8 but in the current entity it can be 123.8999999... If I type cast it to string I end up with something like '123.8' vs '123.80' so the values won't match. Or 1 can be '1' and so on. Also with arrays I think keys get misordered sometimes(either that or the same issue but in the whole array).

I have tried to use the DiffArray::diffAssocRecursive() and Differ::diff() but neither is working reliably.

One thing that comes to mind is doing something like `Differ::diff($entity->view('somemodewithallfield'), $entity->original->view('somemodewithallfield'))` but that won't cover fields that are hidden or invisible in UI and also diff would be "ugly" and too big.

So I am wonder what would be the correct solution in this case? I would like to avoid going through each value and doing some insane comparisons and data transformations(string/int/float).

I remember that there was a story on d.org to not save any field data if the data hasn't changed but I haven't looked into that yet and I'm not sure at what state that is at the moment.

# Answer
> 1 votes
Assuming you have two entities `$a` and `$b`.

You can convert them to arrays and compare the two arrays.

```
// if the position matters
$is_equal = ($a->toArray() === $b->toArray())

// if the position doesn't matter
$is_equal = ($a->toArray() == $b->toArray())

```

Edit: I thought the OP was about discovering if two entities have identical data. After reading the question again it seems that OP wants a way to mark what is the difference in data.

---
Tags: 8, entities
---