# Question
Title: How can I add a textbox in Site Information configuration
I'm altering the following form, **admin/config/system/site-information**.

I need a textbox in the site details section, below the email address textfield. The name of the textbox should be `site_organisation`. This textbox needs to save to variable when the save configuration button is clicked. Its saved value should be displayed when the page is reloaded.

How can I do this? Is there a module that can do this?

# Answer
You need to add your own module if you're looking to alter this form. You'll need 2 things:

1. An alter form hook function to add the text field.
2. A submission handler to process the data.

Something like this...

```
function mymodule_form_system_site_information_settings_alter(&$form, $form_state, $form_id) {
  $form['site_information']['mymodule_site_organisation'] = array(
    '#type' => 'textfield',
    '#title' => t('Site Organization'),
    '#default_value' => variable_get('mymodule_site_organisation', ''),
  );
  $form['#submit'][] = 'mymodule_handler';
}
function mymodule_handler($form, &$form_state) {
  variable_set('mymodule_site_organisation', $form_state['values']['mymodule_site_organisation']);
}

```

Once implemented, you can reference your custom value by using `variable_get('mymodule_site_organisation', '')` anywhere you need it.
> 4 votes

# Answer
Consider editing your question to explain "why" you would want to alter that form, add that field "site\_information", etc. The way the question is phrased right now, I have the impression that you're making it way too complicated to address something that is rather easy to do with some standard Drupal features.

**If** you only want to "display the 'site organisation' when the page is reloaded" (or whatever other info you'd want to enter in such textbox) **Then** it may be sufficient to create a new block, position it in the right spot (region) of the theme you're using (optionally with some extra CSS / theming stuff to make it pixel perfect). And with the content of the block equal to what you mean with "the value entered in this textbox". That would also avoid you'd have to enable yet some other module in your site (cfr. the "which module to use for that).

Or is there some other reason why you really want this to be done via such variable as you asked about?

PS: I just saw Shawn's answer also, which is obviously a great answer (I think) if you really want/need to go that route (for reasons however that right now I cannot find in your question). To actually decide about which of these 2 answers to go for, it might depend also on:

1. preferences or skills of either the **person in charge of building the site**, like a Drupal developer, a site builder, someone new to Drupal, etc, or
2. the actual **customer that the site is for**, who would have to choose between a custom module and some rather basic Drupal admin feature that requires less skills to keep up to date.
> 1 votes

# Answer
```
if ($form_id == 'system_site_information_settings') {
   // echo '<pre>'; print_r($form); echo '</pre>'; exit();
   $form['site_information']['site_organisation'] = array(
     '#title' => t('Site Organisation'),
     '#description' => t('Site Organisation'),
     '#type' => 'textfield',
     '#default_value' => !empty(variable_get('site_organisation')) ? variable_get('site_organisation') : '',
   );
 }

```
> 0 votes

---
Tags: hooks, 7
---


title: Unique Classes on lists items

text:
# Question
Title: Unique Classes on lists items
I'm very new to Drupal 8 theming and I'm trying to replicate a random website to practice.

I have a problem recreating this part though:

I have a block with the latest news articles and a block with most popular.

**I wonder if I could put unique classes on each item in the list (of latest news)**, that way I can make the widths different and make the floats work.

Is there anyway to do this? If I'm doing this wrong and there's a better way, feel free to tell me!

# Answer
In order to replicate the desired behavior you can create several Views blocks and use the pager `Display a specified number of items` option. Then for each block change the amount and offset:

If you would do this with 3 different blocks and use offset/amounts of 0/1, 1/2 and 3/4 you should be able to stack them and have the desired result.

If you really really want to change the class per row, have a look at the great example Dynamically adding a CSS class to a view row with template.php where you can use a views preprocessor to set the right class per row.
> 1 votes

---
Tags: views, theming, 8
---


# Question
Title: How do I completely overwrite an array in JSON serialized data field
I am storing an array as a JSON encoded serialized data field in Drupal 7 using the Serialized Field module.

If I have an array of 20 elements and try to overwrite it with an array of 10 elements, I would expect to only have 10 elements in the field. But instead I am getting the 10 elements (keys 0-9) from my new array AND THEN the higher keyed elements from the old array (10-19).

Is there a way to empty out the old previously stored array values before writing the new array values?

I have tried the following but nothing completely overwrites the field:

`$node->field_test[LANGUAGE_NONE][0]['value'] = "";`

`$node->field_test[LANGUAGE_NONE][0]['value'] = NULL;`

`$node->field_test[LANGUAGE_NONE][0]['value'] = array();`

`$node->field_test[LANGUAGE_NONE][0]['value'] = array(NULL);`

`$node->field_test = array(NULL);`

`$node->field_test = NULL;`

# Answer
A colleague suggested a solution that worked.

The Field Settings has a group of settings called "Serialization Options" which includes a checkbox option for "Namespace the data". In my initial configuration that box was checked. I unchecked the box and saved the field settings and my problem was solved.

Final solution: Uncheck "Namespace the data" in the Field Settings.
> 0 votes

---
Tags: nodes, entities, database
---


title: Convert hook_menu in drupal 8

text:
# Question
Title: Convert hook_menu in drupal 8
I have a hook\_menu as follows :

```
/**
 * Implementation of hook_menu().
 */
function conditional_fields_menu() {
  $items = array();

  foreach (node_get_types() as $type) {
    $content_type = content_types($type->type);

    $items['admin/content/node-type/' . $content_type['url_str'] . '/conditional'] = array(
      'title' => 'Conditional fields',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('_conditional_fields_admin', $content_type['type']),
      'access arguments' => array('administer conditional fields'),
      'type' => MENU_LOCAL_TASK,
      'weight' => 5
      );
  }

  return $items;
}

```

How can i convert this to **`conditional_fields.routing.yml`** in d8 ?

what i tried :

# Drupal 8 conditional\_fields.routing.yml snippet

```
conditional_fields.admin:
  path: 'admin/content/node-type/{this is unknown}/conditional'
  defaults:
    _form: '_conditional_fields_admin'
    _title: 'Conditional fields'
  requirements:
    _permission: 'administer conditional fields'

```

# Answer
The routing system uses pattern matching. You can define a parameter in the path that will be used as a variable.

If we look at this snippet of node.routing.yml:

```
node.add:
  path: '/node/add/{node_type}'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE
    parameters:
      node_type:
        with_config_overrides: TRUE

```

You can see the `{node_type}` in the path. This variable will contain the node type as specified in the path. You can use that as part of the requirement as you can see above, and it will also be available to your functions. `\Drupal\node\Controller\NodeController::add` receives the `node_type` variable as well:

```
public function add(NodeTypeInterface $node_type) {
  $node = $this->entityManager()->getStorage('node')->create(array(
    'type' => $node_type->id(),
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

```

Read Parameters in routes for more information.

And for forms:

```
example.user_form
  path: 'example/form/{user}'
  defaults:
    _form: '\Drupal\example\Form\ExampleForm'
  requirements:
    _permission: 'access content'

```

You can use the `buildForm` function and place the additional parameters after `$form` and `$form_state`.

```
namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Session\AccountInterface;

class BasicForm extends FormBase {

 public function buildForm(array $form, FormStateInterface $form_state, AccountInterface $user = NULL) {
    // Do something with $user in the form
  }
}

```
> 3 votes

---
Tags: 8, hooks
---


# Question
Title: Adding a wrapper to contain tables using grouping field in views / display suite
I'm using a table to display fields data in views 3. Within this i've got a field selected to group these items which produces a heading and then a table for each group. All good up to this point. The issue i'm trying to solve is a way to manipulate all these tables - so i'd like to add a container, with an id to style accordingly. I'm able to access the wrapper for the whole via https://api.drupal.org/api/views/theme%21views-view.tpl.php/7 and the template for the table which in my instance is views-bootstrap-table-plugin-style.tpl.php (which allows me to markup for each table) What i'm looking is where the loop occurs for the grouped field so i can put a wrapper round the loop. Any suggestions?

EDIT: here is a grab of my view https://www.dropbox.com/s/a2mb85m1lo2oxr4/views-display.png The region i am trying to wrap is below the exposed filters form. I am using Display Suite \> Views Displays to layout the view with exposed filters and views content in the left column and the map as an attachment in the right column.

EDIT: removing the view having its template defined via DS Views has given a result with markup with a .view-content wrapper around the tables (which is good) but isn't entirely helpful as i still need to split the view into two columns (which is why i was using DS).

https://www.dropbox.com/s/7aukgjkkux2xycs/views-display-no-ds.png

Whilst creating a custom template to do this by modifying an existing DS template and making a region specifically for my grouped table seems the quickest way to solve this, it certainly seems a bit messy as this will need to be done for every time i set to use grouped fields.

# Answer
> 1 votes
You can add classed to your regions within Display suite:

Add CSS classes to regions Now that you have defined regions you can define custom CSS classes for them.

* Go to Administration \> Structure \> Display Suite \> CSS Classes (admin/structure/ds/classes)
* Enter custom class names in the fields "CSS classes for regions” (one per line). You can provide a human friendly class name by using a pipe ("|”), e.g.,: `class_name_1
class_name_2|Class two
extravagant|Extravagant
subtle_emphasis|Subtle emphasis`
* Click "Save”
* Go to Administration \> Structure \> Display Suite (admin/structure/ds/layout) and choose "manage display” for the desired entity.
* Choose the tab "Custom classes” to assign the classes to the regions
* Click the tab "Extra classes for regions”. Assign the defined classes to the regions.
* Click "Save”
* You can check the source code of your web page to see the new classes and start styling them in your CSS.

From Manage displays.

You can use above steps to add a class to your Display Suite region. Depending on how Views renders the View, explore the DOM to see if you need to select additional classes.

---
Tags: views, theming
---


title: paypal no shipping address on file

text:
# Question
Title: paypal no shipping address on file
**Problem statement:** When users pay for an order at paypal, in almost 50% cases(for both verified and unverified paypal users) the transaction slip(for business account) does show shipping address(confirmed address), but for other 50% users it is saying **"We have no shipping address on file"** even if users enter shipping details on paypal review page.

Using Paypal Express Checkout payment Method.

Currently we are passing NOSHIPPING=1

What should be the parameter for NOSHIPPING ? What could be the problem ? Please help.

# Answer
try not passing that parameter at all

Here is an excerpt from the PayPal's Express Checkout Integration guide about Shipping address:

> **Suppressing the Buyer's Shipping Address**
>
> You can suppress the display of the buyer's shipping address on the PayPal pages. You might want to do this in these cases:
>
> 1. You are selling a product or service that does not require shipping.
> 2. You prefer to handle addresses completely on your own and do not want to let buyers choose from their PayPal address book.
>
> `To suppress` the display of the buyer's shipping address, `set the NOSHIPPING parameter to 1` in the call to SetExpressCheckout. No shipping address displays on Express Checkout pages.

Hope this helps.
> 1 votes

---
Tags: 7, commerce, payment-gateways
---


# Question
Title: How to bulk create many sites using one platform in Aegir
I a plan to use Aegir (part of a BOA server) to host many sales sites, one site for one product.

I would like to know how to bulk-create 1000 sites using an existing platform in Aegir.

This apparently is not included in the Aegir handbook

If it may be more efficient, the other approach would be to clone 1000 sites from one existing site in Aegir.

I suppose that this can be accomplished either way using Drush, but how? It should use a list of domain names.

# Answer
> 1 votes
I've used software-as-a-service modules before to test this. This is what I use because I worked on/with these modules a lot so it's the most efficient route for me, but I don't think it would take anyone more than an hour to set up.

(This is a clone-based approach.)

Go to your hostmaster site and download the important modules:

```
drush dl hosting_variables hosting_saas
git clone --branch no-specifics https://github.com/PraxisLabs/hosting_restapi.git

```

Enable the modules, and set the site nid and platform nid in Hosting -\> SaaS. (You can find the nid of a site or platform in the URL of their "edit" tab.)

Test the site creation with this bash command:

```
curl --data "url=test1.example.com&invoice=1" http://yourhostmasterurl/hosting/api/site

```

If this works, from there you can easily create 1000 sites with a simple bash script:

```
for ((i=2;i<=1000;i++));
do
   curl --data "url=test$i.example.com&invoice=$i" http://yourhostmasterurl/hosting/api/site
done

```

This would queue up clone creation for test2.example to test1000.example.com

Here's an article I wrote on using Aegir SaaS in production.

Alternatively, you can set up Hosting Services and use the REST API to queue up site creation tasks. I think this could take a few hours if you've never used it before.

# Answer
> 0 votes
Yes Drush is your friend here.

Examples from the import handbook and context import should be helpful.

There once was a feeds integration to create sites based uppon cvs or rss. But it has not been updated for Aegir 3.x.

Updates to the docs pages are always welcome ;)

---
Tags: drush, aegir
---


# Question
Title: In views, how to create link to field visible through relationship connection?
I don’t want to link to the original piece of content (which is a join table) but to the content type which is referenced in the join table.

Using: Views, Entity Reference, Entity Tokens, Token.

I have these content types:
\- Person (firstname, lastname, etc.)
\- Story (field\_story\_title, orig copyright, description, etc.) Note: \[content:title\] is automatically generated and not used.
And this content type which functions as a join table
\- PersonStory (field\_personstory\_person\_id, field\_personstory\_ story\_id, relationship \[e.g. author\].)

The view has Content: Type (= PersonStory)
Relationships have been created
\- Story from field\_personstory\_story\_id
\- Person from field\_personstory\_person\_id

The view successfully finds Story Title (field\_story\_title) and Person Name (using \[Global: custom text\] in concatenation of field\_person\_lastname, field\_person\_firstname, etc).

I created a link:
\- Added field \[content:path\] above Story Title on the field list. Checked "Exclude from Display" and expanded "Rewrite results" and only checked "Use absolute link" for this field.
\- Added field field\_story\_title, expanded "Rewrite results" and checked "Output this field as Link" with the Link path: \[path\] .

The view *looks* just fine with the field\_story\_title appearing as a link.

**However, clicking the link goes to the record in PersonStory instead of the record in Story**. @skorzh suggested that I investigate replacement pattens in the Rewrite results, but I don't see any tokens which connect to the fields in **Relationships** in the View.

I’ve tried many different patterns and tokens and nothing has worked in details of \[field\_story\_title\]. I don't know what the replacement pattern should look like. Is it possible to join replacement patterns? How do I determine what the url should be?

My latest attempt is
\[site:url:join:/\]/\[content-type:name\]/\[node:field-story-title:name\] but it's not working, naturally.

Thanks.
(Entire post has been updated to reflect my current (lack of) progress)

# Answer
> 1 votes
You need to have the path field set to use the story relationship. http://cl.ly/372U1S1b2s3V

# Answer
> 0 votes
> 1. Place content:path before the field X. Check "Exclude from Display". Expand "Rewrite results" and only check "Use absolute link" for this field.

Did you set properly relationship in this field?

> 2. Field X - Rewrite results - Output this field as Link - Link path: \[path\] . Do NOT check "Use absolute path" here again.

You can try to write path by entity id token, without additional path field, so in Link path set something like Link path: `node/[node_id]` (see available tokens within Rewrite results)

---
Tags: 7, views, entities, tokens
---


# Question
Title: Drupal Commerce product in-cart status info in Views
How can I use information in Views about whether a particular product is in this user's cart? Particularly, how many times into a Views row for that product?

For example, on a view listing available products, I'd like to be able to stylistically differentiate the rows representing products the customer has already added to their cart, and/or show a field, empty by default, stating how many of that item are already in the user's cart.

I've looked at existing Commerce modules such as Commerce Views Display and Commerce Add to Cart Extras, but can't see anything directly relevant. I'm not sure how to proceed with creating something to do this short of writing a custom Views query which also loads the Commerce cart for each row, which I'd rather not do since I'm not sure how I could make it reasonably efficient.

Does anything exist to support this, or if not, is there a simpler/more integrated, less "reinventing the wheel" approach using the Views and/or Commerce API?

---

An ideal result would be a Views Field for commerce products outputting a simple number representing how many times a product with this product ID is in the cart. Turning that into all the above use-cases is easy (e.g. rewrite as a class `product-in-cart-N` then apply default styles to `.product-in-cart-0`, simply display the field with a label, etc etc).

# Answer
> 2 votes
I am not aware of any modules, that will provide the functionality that you described out of the box, but the snippets below will probably get you moving in the right direction.

---

You'd write a function that gets all product IDs that are in the cart.

```
/**
 * Return the product_id values for all products in the cart
 *
 * @return
 *  An array of product ids
 */
function CUSTOMMODULE_get_products_in_cart() {
  $cart_product_ids = &drupal_static(__FUNCTION__);

  if (!isset($cart_product_ids)) {
    global $user;
    $cart_product_ids = array();
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
                if ($line_item_wrapper->type->value() == 'product') {
                    $product_wrapper = $line_item_wrapper->commerce_product;
                    $cart_product_ids[] = $product_wrapper->product_id->value();
                }
      }
    }
        $unique_cart_product_ids = array_unique($cart_product_ids);
  }

  return $cart_product_ids;
}

```

---

For adding a class to the views row according to the quantity in the cart you'd implement **`hook_views_pre_render()`** and implement your logic there

```
/**
 * Implements hook_views_pre_render().
 */
function CUSTOMMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
        // get product_ids in cart
        $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
        if (in_array($product->product_id, $cart_product_ids)) {
            // check how many times product_id is in the present in the array
            // do other stuff - apply class, etc.
        }
  }
}

```

---

Also, you'd probably want to change the "Add to Cart" button text to something custom if the product is already in the cart

```
function CUSTOMMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
    if (in_array($product->product_id, $unique_cart_product_ids)) {
        // Product is already in cart
        // Change "Add to Cart" button text
        $form['submit']['#value'] = t('Add one more'); // your custom text and maybe a quantity of that product that is already in cart...
    }
}

```

---

I think using `hook_views_pre_render()` is the right way to go about this, but if there is more efficient or easier way I'd like for others to pitch in with ideas.

Hope this helps.

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


# Question
Title: RSS item elements not being not being read by XML Reader
I am new to stackexchange and don't know if i am asking this correctly but plz help me.

I am using Drupal Views to display RSS for my site. I am using the '**Views RSS: Core Elements**' module to map the RSS fields with the custom fields added by me in the views. All works well. But a requirement forces me to add custom item elements in the RSS display. I am implementing the **hook\_views\_rss\_item\_elements()** to add custom item elements. When i view the RSS page i get the see the custom items but when i try to read the RSS using a RSS reader, the items are not being read. What am i doing wrong, or am i missing something?

Here is my code to add custom items to the '**SHOW ITEM ELEMENTS : CORE**' for RSS display:

```
function Mymodule_views_rss_item_elements() {
  $elements['blogs_title_image'] = array (
    'title' => t('Blogs Title Image'),
    'description' => t('Blogs Title Image'),
  );
  $elements['blogs_additional_tags'] = array (
    'title' => t('Blogs Additional Tags'),
    'description' => t('Blogs Additional Tags'),
  );
  $elements['blogs_short_desc'] = array (
    'title' => t('Blogs Short Description'),
    'description' => t('Blogs Short Description'),
  );

  return $elements;
}

```

# Answer
After some research i did manage to find my way out: I implemented hook\_views\_rss\_namespaces to add a custom namespace and the custom items under the namespace:

```
function Mymodule_views_rss_namespaces() {
  $namespaces['blogs'] = array(
  'prefix' => 'xmlns',
  'uri' => 'http://base.google.com/ns/1.0',
);
return $namespaces;
}

```

Note: Use the same 'prefix' and 'uri' as given in the above code or else namespace uri error will arise.
> 3 votes

---
Tags: views, feeds
---


title: Customize admin toolbar

text:
# Question
Title: Customize admin toolbar
Is it possible to make admin toolbar partially visible to newly created users in Drupal 8? For example, the user would be able to observe the Reports, but not be able to add new modules, so the 'Extend' entry is not visible to him?

# Answer
> 1 votes
Yes, as Neo mentioned, the toolbar utilizes menu permissions so it only displays items available to the user. So if the user has permissions for *Use the administration toolbar* & *View site reports* (or whatever permission needed for a sub-item in the admin menu), they will see only the report menu items.

---
Tags: 8, toolbar
---


# Question
Title: How to debug or explore an unknown object or array too big for Drupal's debug()?
I'm trying to see what variables I have available in a $vars object in a Views hook. Unfortunately, like many Drupal object, this one is huge and attempting to output it using the Drupal `debug()` function (with or without the 3rd boolean argument) causes the server to crash with an out of memory error.

Note that this is after increasing the memory limit quite high, the memory limit isn't the problem here (*UPDATE: I later discovered the array output was over 370 megabytes!*).

What's the least intensive (fewest contrib modules, patches, custom code, 3rd party libraries etc) way to explore the contents of a Drupal object like this that's too big for Drupal's `debug()`?

# Answer
## Devel

Devel module provides `dd()` command which is very useful for dumping very large object. Just run `dd($vars)` in the middle of code, it'll dump any object to the temporary file in your Drupal temp folder (`temporary://drupal_debug.txt`).

---

### XDebug

Use XDebug PHP extension, so `var_dump()` will be replaced by `xdebug_var_dump()` so your big dump won't consist circular dependencies and would be limited only by specific depth.

---

Alternatively use TVarDumper, array\_slice, serialize or json\_encode, so check below for further details:
> 6 votes

# Answer
Here's a very quick and reliable way to explore any object or array (here named `$vars`) one layer at a time:

```
  debug( array_keys((array)$vars), 'vars: '.  gettype($vars), false);

```

`array_keys()` gives only the names of the keys, giving you enough info to see where you need to go in the tree, regardless of what those keys contain.

Since you might not know if this variable is an array or an object, casting it as an array with `(array)` makes `array_keys()` work on either. You'll need to know which it is for the syntax for the next step, so that's ouput in the Drupal `debug()` title string with `gettype()`.

---

Then you can simply choose a likely-looking from the output and walk up the tree. For example on seeing that $vars is an array which contains a relevant-looking key `field`:

```
  debug( array_keys((array)$vars['field']), 'field: '.  gettype($vars['field']), false);

```

Then on learning that `$vars['field']` was an object containing a relevant-looking property `items`:

```
  debug( array_keys((array)$vars['field']->items), 'items: '.  gettype($vars['field']->items), false);

```

...and so on.
> 1 votes

---
Tags: 7, debugging
---


# Question
Title: Manage display of geofield with wkt input widget
I am stuck on something that seemed very simple and need your help. I have an input form where there is a geofield input field of type WKT. So the user gives the WKT of a point. When the node is viewed I would like the WKT that the user previously gave to be displayed on a map. On the manage display tab all the other options seem to work (WKT, KML, description etc), except from the map option like leaflet, openlayers and geofield maps. There is empty space where the map was supposed to be. Can anyone help me on this?

# Answer
> 1 votes
Some suggestions:

* make sure that you edit the right format when you filled in the wkt.
* check for any errors in the installation of the map.

I had the same problems in the beginning with mapping too. I had an error in the installation of my leaflet map. In the end I solved it with a new installation and I geocoded the geofield from my address field.

# Answer
> 0 votes
Problem solved, I suppose it was a bug. The content type had two maps with location. When the first was empty then the second didn't show up and caused the empty space. When I removed the first map everything worked fine. But now I am stuck to this if anyone could help... Hide grey leaflet map if empty

---
Tags: location
---


# Question
Title: Seemingly random <h3> being added into views node header for content type
I've got what seem to be random empty `<h3>`s appearing whilst displaying a custom content type as a teaser in a pretty standard blocks display through Views. Now this is only a problem because it's adding dimension and padding, which can be aleviated but I'd actually rather like to get to the bottom of why it is happening.

```
<article class="node-3099 node node-feature node-teaser contextual-links-region
        node-by-viewer clearfix" typeof="sioc:Item foaf:Document"
        about="/feature/simplifying-copyright-through-digital-technology">
    <header>
        <h3></h3>
        <h1 class="node__title node-title">

        ...

```

We've created a subtheme of Zen and only have the following files overriden:

* block.tpl.php
* node.tpl.php
* node--news\_story.tpl.php
* node--product.tpl.php
* page.tpl.php
* views-view--page.tpl.php
* views-view-unformatted.tpl.php

I've cleared the views cache, cleared all caches, not got "compress JS/CSS" etc. selected, rescanned the template files but it makes no difference.

I've not added any custom classes to the views display settings, I've not done anything funky in the custom content types either, not the default/teaser displays. Nearly everything is as it is by default. And we're not using grouping, which I've read can be a problem.

In our custom "news\_story" template (and the product one too) we'd carried over something in the header from an old build. This was displaying an empty h3 but commenting it out fixed it completely. And it was not in the rendered HTML at all. Unlike the other blocks, like the Features section.

```
  <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished || !$page || $title): ?>
    <header>

        <?php //DONT DO THIS WITH THE H3: it injects it even if the field_news_category is ignored?>

      <!-- <h3><?php
        // Only one of these will be shown (Domain Fields...)
        //print render($content['field_subtype']);
        print render($content['field_news_category']);
      ?></h3>-->
      <?php
        //hide($content['field_subtype']);
       //hide($content['field_field_news_category']);
      ?>
      <?php print render($title_prefix); ?>

```

However, we've not overriden the other custom content types and I can't find anything in any of the other templates that has any h3 or anything. I've looked through Zen and there's nothing there. I've looked through the Views module and in the Theme folder there was a h3 in "unformatted" so I overwrote that and commented out the `<h3>` ...

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <!-- <h3><?php print $title; ?></h3> -->
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

And since we're using the "unformatted" format I can only presume that's all that's needed. I also tried commented out the `<h3>` in the views-view-unformatted.tpl.php file in the Views module's Theme directory. And clearing Views caches with Drush. But somehow there's still a h3 getting in there...

# Answer
> 1 votes
`<h3>` in the `views-view-unformatted.tpl.php` is outputted only if you use Grouping setting in your view. So commenting that out is a bad idea.

Looking at your markup I can say with confidence that h3 is produced by either one of the following templates:

* node.tpl.php
* node--news\_story.tpl.php
* node--product.tpl.php

Good point was made by rhuffstedtler, about checking which template is producing the markup.

find settings.php file and uncomment the line (usually last line) that says:

**`$conf['theme_debug'] = TRUE;`**.

Then refresh your page and check the source HTML code. You'll figure out from there which template you should be modifying.

---
Tags: views, nodes, blocks, theming
---


# Question
Title: How to alter command being run by drush_invoke?
When you run `drush features-revert-all` command, it can be altered using `hook_drush_command_alter` (`&$command`).

However during run it's invoking another command by:

```
drush_invoke('features-revert', $features_to_revert);

```

It seems I can still use `drush_hook_pre_COMMAND` and `drush_hook_post_COMMAND` to perform some additional checks.

However I'd like to alter the list of arguments (features) being passed into `features-revert` which are not available as part of the main command.

Is there any Drush hook which I can use to achieve that?

# Answer
Drush calls command hooks via the function \_drush\_invoke\_hooks, which unfortunately does not provide any facility to alter the arguments list from a pre or validate hook. We are looking to provide a more flexible mechanism that would allow this in Drush 9. Currently, only the command alter hook can change the parameters to a command. Ideally, Drush commands should invoke other Drush commands via `drush_invoke_process`; this will also go through the command alter hook. If a command uses drush\_invoke, though, you are stuck, as `drush_invoke` bypasses the alter hook.
> 1 votes

---
Tags: hooks, drush
---


# Question
Title: Get a multiple value listing of related node IDs using Relation module and Views node ID field
**The situation**

The awesome Relation module uses so called *endpoints* in a dummy field to show related entities to a given entity.

Sadly there is (still) no way to (really) decide what field values of the *related Entities* exactly *these endpoints* are which we want to show. You are only able to decide between "endpoints" or "endpoints and fields", which both result mostly in the same: a list of the linked titles of the related entities, more or less cluttering, depending on your additional relation fields.

**The question**

Is there something I miss to achieve this? I would like to prevent using performance hogs Views field view for such small task like a list of related node IDs per row in a Views table of listed nodes. Is there any work around or advice somebody can give? Thanks in advance.

**Maybe related issues I found on DSX here:**

# Answer
> 1 votes
A work around which could come in mind to an experienced Drupal site builder is to use Views module to get more flexibility in showing other fields of related entities listed instead of titles, by using the Views relationship advanced settings in connection with an existing field of related items like node ID.

Sadly the multiple value field handler of Views only appears on the Relation endpoint field itself, added directly in your Views view, but not in the node ID field by using the proper Views relationship to the relation \<-\> for this purpose.

The expected behavior is, that you are able to activate and modify multiple values of the related node ID field now in the node ID field settings like you did in the endpoints field before. But sadly that's not the case. You will always get the first related node ID or many duplicate records depending on how much related items you have with each related node ID per Views view row.

---
Tags: 7, views, entities
---


title: Which files should I version?

text:
# Question
Title: Which files should I version?
After reading the following posts, I'm still not sure on how to set up a Drupal 8 site with Git.

Apparently, the contributed/ custom modules and themes folders have moved from /sites/all/modules and /sites/all/themes to /modules and /themes, in Drupal 8. When I copy the modules to /sites/all/modules Drupal 8 does recognize them, but when I add modules via UI, they get downloaded to /modules.

Which folders should be committed in a Git repository? Is it generally bad practice to go for sites/all?

Formerly, we had this file and git structure.

```
/
↳ www.example.com
  ↳ sites
    ↳ all -> /repo/repo.git/all
↳ repo
  ↳ repo.git
    ↳ all

```

Now, I imagine it's more complex.

```
/
↳ www.example.com
  ↳ modules -> /repo/repo.git/modules
  ↳ themes -> /repo/repo.git/themes
↳ repo
  ↳ repo.git
    ↳ modules
    ↳ themes

```

What about sites/default/files/conf\*?

I understand that this folder is being used for the configuration files.
Is it right that my local developmente environment and the staging/ production environments have their own folder? Is the usage of configuration files necessary when we only tend to have one *real*, always up-to-date main database (production/live)?
Should the configuration be tracked and deployed with Git? Why?

# Answer
> 4 votes
Drupal comes with an example .gitignore file, just rename "example.gitignore" to .gitignore and you have a pretty good starting point. It also comes with a lot of explanations.

Many of your questions go way beyond just answering that should be added to get, there are also some different opinions.

* Yes, put your modules in /modules and so on, it's a lot easier to work with.
* Whether or not to commit /vendor depends on your deployment process. if you deploy your git repository directly and have no intermediate deployment process, you probably still want to commit the vendor directory. There are various alternatives, starting from just building an archive yourself and deployment that, to automating that with scripts/build tools to using solutions like platform.sh that run composer install automatically for you. If you use any of those, you likely want to ignore vendor as the example .gitignore file does by default.
* It's also common practice to have a settings.local.php and add settings.php to git, see instructions in settings.php at the end.
* I don't understand your repo.git and repo folder examples. It's not more complex than in Drupal 7, just different folders.
* Yes, you probably want to move your config folder out of files (you need to update the path in settings.php) and commit it. You shouldn't only have one environment, and config allows you to make changes on one site, export it and import it on production. There are many questions here and documentations about this available.

---
Tags: 8, installation, version-control
---


# Question
Title: Force to download a module on a remote site
How can I force to download a Drupal 8 module on a remote Drupal 7 site?

I tried the following commands, but they let me choose Drupal 7 versions.

* `drush @remote.dev dl --default-major=8 composer`

> There are no stable releases for project composer. Choose one of the available releases for composer:
> \[0\] : Cancel
> \[1\] : 7.x-1.x-dev - 2013-Sep-30 - Development, Recommended
* `drush @remote.dev dl composer-8`

> There are no stable releases for project composer.
> Choose one of the available releases for composer:
> \[0\] : Cancel
> \[1\] : 7.x-1.x-dev - 2013-Sep-30 - Development, Recommended

How does Drush detect the version of the remote site?
Maybe I can edit that and restore it after the download, or I can override some Drush parameters to forcefully show all releases.

# Answer
I was going to suggest --default-major. Since that does not seem to work, I can only recommend to download the module outside of a Drupal site and then move it into place.

`drush dl composer-7 --destination=/tmp && drush rsync @self:/tmp/composer @remote-dev:sites/all/modules`
> 1 votes

# Answer
Try the following command:

```
drush @remote.dev exec drush @none dl composer --default-major=8

```

which will execute `drush` (either `exec` or `ssh`) on remote using `@none` environment, which will force Drush to not try to recognise the major version of Drupal which you're running in the current folder. Without using `@none`, this is expected behavior.
> 0 votes

---
Tags: drush, composer
---


# Question
Title: Taxonomy term reference field from custom database table
I am trying to create a taxonomy term reference field or the equivalent in a View that uses the uuid of a field in a custom table. This field can contain multiple uuids.

My first approach after having issues with the `views_handler_field_taxonomy` ( because the table does not contain the `vid` and `tid` fields ) was using joins and another table that contained all the necessary taxonomy fields. Although I got it to work the multiple joins caused the results to become pretty ugly ( lots of duplicates ). I may have to use this approach and clean up the results with custom code but I would definitely prefer not to.

So the question. Is there any straightforward way I'm missing to get my custom database field of comma separated uuids treated like a taxonomy term reference field by Views? I have tried a variety of different relationship handlers as well as field handlers in my `hook_views_data` but no luck. I have found very limited documentation and only the simplest tutorials for custom views field and relationship handlers. Any links to good ones and/or good sample code would be greatly appreciated.

I would also be completely fine with a way to treat a custom entity property as a taxonomy term reference field.

# Answer
> 0 votes
The easiest solution would be to use some sort of system to synchronize those terms from whatever data set you have to real taxonomy terms.

It would probably function similarly to Node Auto Term.

---
Tags: 7, database, entities, views
---


title: Redirect page without exit

text:
# Question
Title: Redirect page without exit
I have checkout function which uses `drupal_goto` to redirect to the confirmation page after validating all info. I want to redirect to the confirmation page before all validation. Then in the background I need it to complete all validation and email me any errors.

Problem is, `drupal_goto` calls `drupal_exit` so all further code stops running. I can implement my own `goto` function without the `exit` but then it won't redirect until all validation is completed. I need validation to run in the background after the redirect.

# Answer
> 0 votes
During checkout, you'll need to create a transaction because the order needs to be paid before it is actually completed. If you're needing to do other processing, you might consider looking at the architecture of Commerce License, where a license can have a post-checkout set of processes.

The short version of it looks like this:

1. You create the license or the "queue item" that needs to process.
2. Redirect to the completion page.
3. Have an AJAX watcher that looks for the completion of whatever needs to be done (could be handled by queues or some external system that updates state on the site).
4. Use JavaScript to take action.

---
Tags: 7, redirection
---


# Question
Title: Page redirect in rule after VBO new custom operation is is not redirecting
I need to page redirect after the VBO operation.

The page redirects is inside a rule component that I have created for a new operation in VBO. This is the my new operation in my VBO:

I have marked force redirect. And it doesn't work too. I tested installing rules debug, to see if rules was executed, and it shows as executed, but it doesn't redirect to cart. What could I check on this issue?

The debug is showing, skipping page redirect during the batching process, see it please.

How could I add a rule for page redirect, just after the batch process of my VBO operation? This could works.

Note: Not very relevant but

## Here is the export of the rule:

{ "rules\_vbo\_add\_to\_cart" :

```
"LABEL" : "A\u00f1adir las fotos seleccionadas al carrito",
"PLUGIN" : "action set",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_cart", "rules" ],
"ACCESS_EXPOSED" : "1",
"USES VARIABLES" : { "commerce_product" : { "label" : "Commerce product", "type" : "commerce_product" } },
"ACTION SET" : [
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : [ "commerce-product:sku" ],
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  },
  { "redirect" : { "url" : "\/cart" } }
]

```

}

## }

# Answer
> 0 votes
There could be a possibility that some other redirect rule is overriding you **page redirect to cart** Rule. So please check if in case any other rule is getting triggered or not. If yes, then set priority of **page redirect to cart** rule's **high**.

1. For checking if any other rule is overriding the "Page redirect to Cart" rule we can actually use `watchdog('Backtrack message','<pre>'.print_r(debug_backtrack(),true).'</pre>');` It will give show everything what all code running at the time the rule triggers.
2. You are absolutely correct sir, just need to set the weight of **Page Redirect to Cart** rule lower than other rule. It will set the priority higher.

# Answer
> 0 votes
I have found a solution on how to do a custom page redirect, after an VBO Operation.

Here there is a patch to add a custom redirect field in the options https://www.drupal.org/node/2307381

I have applied the patch #6

in ./profiles/commerce\_kickstart/modules/contrib/views\_bulk\_operations

using the command

patch \< 2307381\_6.patch

It asked me for file to patch, and I had to indicate:

file to patch: ./views/views\_bulk\_operations\_handler\_field\_operations.inc

then patch done!.

Results is awesome and redirect specified is working perfectly!! so I am happy!

Thanks for all your help!!

---
Tags: 7, commerce
---


title: How to prefill address field forms?

text:
# Question
Title: How to prefill address field forms?
I've been using the Prepopulate module for a while, and it works really well. It can't prefill an addressfield type field, though.

How can I achieve this?

# Answer
Add something like this to your hook\_form\_alter() or hook\_form\_FORM\_ID\_alter():

```
  $form['field_address'][LANGUAGE_NONE][0]['#address']['country'] = 'US';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = 'Livermore';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = 'CA';
  $form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = '94551';

```
> 8 votes

# Answer
Just as addition to MotoTribe's answer. I had to prefill some fields of the registration form and used the YOUR\_THEME\_hook\_form\_FORM\_ID\_alter() function in my template.php.

The fields are custom and the way to go for me was to set a default value:

```
$form['field_custom_field_name'][LANGUAGE_NONE][0]['value']['#default_value']

```

Maybe this helps someone out.
> 2 votes

# Answer
D7 solution by custom module. This is to prepopulate current user address\_field when creating a new node. Add user address\_field field, name it user\_address, then make a custom module with the following code, replace CAPTIAL LETTERS as needed.

function YOURMUDULE\_form\_alter(&$form, &$form\_state, $form\_id) {

/\* Check to see if the form alter function is actually running */ /* dsm($form); \**/

```
/* Only do this for a new, not-yet updated entityform -NB might need a 'return' here */
if (!isset($form['#entity']->is_new)) {

    //Ensure, we're updating field info on the correct entity type
    if ($form_id == 'CONTENTYPE_node_form') {

       if (!isset($form['#entity']->is_new)) {

        /* function load user data from field_user_address */
          global $user;
          $current_user = user_load($user->uid);
          $current_user_country = $current_user->field_user_address[LANGUAGE_NONE][0]['country'];
          $current_user_estate = $current_user->field_user_address[LANGUAGE_NONE][0]['administrative_area'];
          $current_user_city = $current_user->field_user_address[LANGUAGE_NONE][0]['locality'];
          $current_user_locality = $current_user->field_user_address[LANGUAGE_NONE][0]['dependent_locality'];

          /*  dsm(user_load($user->uid));     */

          $form['field_CONTENTYPE_FIELD'][LANGUAGE_NONE][0]['#address']['country'] = $current_user_country;
          $form['field_CONTENTYPE_FIELD'][LANGUAGE_NONE][0]['#address']['administrative_area'] = $current_user_estate;
          $form['field_CONTENTYPE_FIELD'][LANGUAGE_NONE][0]['#address']['locality'] = $current_user_city;
          $form['field_CONTENTYPE_FIELD'][LANGUAGE_NONE][0]['#address']['dependent_locality'] = $current_user_locality;

          }
      }

  }
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: New VBO bulk operation button not get translated
VBO button not translated issue.

I have created a new VBO bulk operation using rules component.

This is the button:

In Rules I have written the translation for this rule, in the translate tab of the rule.

But the button in the view doesn't display translated. :(

Too I tried to override a label in the view for this button, and translate this label with the translate view option, translating this field.

But the button doesn't translate too.

How could I translate my button?

# Answer
> 0 votes
Sharing a link below:-

http://www.drupalcontrib.org/api/drupal/contributions!views\_bulk\_operations!views\_bulk\_operations.api.php/function/hook\_views\_bulk\_operations\_form\_alter/7

Here a function `function hook_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
}` We can use this function and here we can actually do custom code for this particular action and set the label accordingly.

Would be able to answer more appropriately if you share some more details with your question that what you basically did.

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


# Question
Title: How to dynamically Prepopulate / Prefill addressfields
I have an single entityform of type 'letter generator' this contains two addressfields:

* 'To' addressfield
* 'From' addressfield

I would like to prepopulate / prefill these addresses with content from elsewhere on my site.

1. 'From' addressfield populated from the 'User addressfield' attached to my 'user' entity type.
2. 'To' addressfield populated from the 'School addressfield' attached to my 'School info' 'node' entity type (also the parent node for the letter generator)

I am new to php and programming so this is my first attempt at a custom module. So far I have the following php that attempts to address point (1.)

```
function letter_address_form_alter(&$form, &$form_state, $form_id) {

// Check to see if the form alter function is actually running
dsm($form);

    // Only do this for a new, not-yet updated entityform -NB might need a 'return' here
    if (!isset($form['#entity']->is_new)) {

        //Ensure, we're updating field info on the correct entity type
        if ($form_id == 'letter_generator_entityform_edit_form') {

            // load user information
            global $user;
            $current_user = user_load($user->uid);

            //Populate the entityform addressfield with values from the user addressfield
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['thoroughfare']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['premise']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['locality'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['locality']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['administrative_area']['value'];
            $form['field_user_address'][LANGUAGE_NONE][0]['#address']['postal_code'] =
                $current_user->field_user_address[LANGUAGE_NONE][0]['#address']['postal_code']['value'];

        }
    }

}

```

... Ok I got this working:

```
global $user;
$user_fields = user_load($user->uid);
//useful ...
dsm($user_fields);
$userthoroughfare = $user_fields->field_user_address['und']['0']['thoroughfare'];
$userpremise = $user_fields->field_user_address['und']['0']['premise'];
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $userthoroughfare;
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['premise'] = $userpremise;

```

> NB adding \['value'\] to the line:

```
$form['field_user_address'][LANGUAGE_NONE][0]['#address']['administrative_area']['value'] = $useradministrativearea;

```

> will select the state for you...

# Answer
I cant find any reference of hook\_form\_entityform\_alter if it is available you will want to take out the hook part and replace this with you module name.

I have re written the code using hook\_form\_alter. You will need to replace $address1 etc with your own code.

```
function letter_addresses_form_alter(&$form, &$form_state, $form_id) {

// Ensure, we're updating field info on the correct entity type
//This needs to be more specific incase more entity forms are created
if ($form_id == 'yourformname_entityform_edit_form') {

// Only do this for a new, not-yet updated entityform -NB might need a 'return' here
if (!isset($form['#entity']->is_new)) {
//Populate the entityform addressfield with values from the user addressfield
$address1 = "address1";
$address2 = "address2";
$county = "county";
$postcode = "postcode";
$form['field_address'][LANGUAGE_NONE][0]['#address']['thoroughfare'] = $address1;
$form['field_address'][LANGUAGE_NONE][0]['#address']['premise'] = $address2;
$form['field_address'][LANGUAGE_NONE][0]['#address']['locality'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['administrative_area'] = $county;
$form['field_address'][LANGUAGE_NONE][0]['#address']['postal_code'] = $postcode;
  }
}

```
> 1 votes

# Answer
You can use the default value to set it - see here for an example: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#default\_value

```
<?php

         $form['body'] = array(

          '#type' => 'textarea',
          '#title' => t('Body'),
          '#default_value' => $node->body,  //$user->addressField or $node->school_address
          '#required' => TRUE,
         );

  ?>

```
> 0 votes

# Answer
This may be a duplicate of this question and I posted there a working solution for one node field, should be very easy to add the second field.
> 0 votes

---
Tags: entities
---


# Question
Title: Attach a Webform to user registration form
Is there any way to do this in Drupal 7?

I want new users send some documents via Webform on registration.

The reason is that I don't want to save these documents as an user profile field.

# Answer
> 1 votes
It sounds like you want the Webform Registration module. It lets any webform create users upon submission. It also lets you customize the registration process by selecting which webform elements are associated with the newly created user's name, password, & email.

---
Tags: 7, users, webforms
---


# Question
Title: How to calculate margins based on JSON and ONIX (XML) input and calculate points based on them?
In a Drupal Commerce distribution based on Drupal 7 we sell books. First I want to calculate a margin price based on several given data. The JSON is imported or can be manually added. The ONIX (in fact XML) data is already imported in an earlier stage. In the ONIX data the tags Price, Weight and Publisher are available as variable. When an order is placed I need a rule that combines these data, makes a calculation and present the result after ordercompletion in the dashboard of the admin as a view.

After this I want to calculate how many points the buyer gets based on the order price per item in the order in relation with the previously calculated margin. The point that is earned is an equivalent to a maximum percentage of the price of a book AND cannot be more then the maximum % of the calculated margin.

Is there any way or technique in Drupal to do this?

# Answer
> 0 votes
# Calculations

You should definitely have a look at the (fairly new) Math Field module, to use it for:

* calculating the margin price.
* the calculations after order completion.

Some more details about this module (from its project page), which also details **when** the calculations actually happen:

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Known issues**

As this is a fairly new D7 module, there are still a few (known) issues with it, as mentioned also on its project page:

**Bonus**: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...

# Dashboard

Depending on your actual requirements/expectations, you might be able to implement your dashboard with only the Views module, possibly complemented one of more add on modules for it. E.g... if you'd also want some sort of charts to be created, a module such as charts could be a good fit.

As an alternative (or possible complement?) you might also want to consider the Forena module (discosure: I'm a co-maintainer), e.g. because it comes with charting out of the box, and it would even allow you to integrate some of your data stored in XML (your ONIX data) without importing them.

# Buyer points

These points could be implemented using the Userpoints module (that's obvious). And by using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of granting the appropriate number of userpoints. So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of **Goals** and related **Tasks**. For a basic introduction about Goals, have a look at:

**Bonus**: even though your question doesn't seem to include that (yet) as requirements, it would be straight forward to implement some special reward(s) for your ***frequent buyers***. Here is what it would take:

1. **Goal** = "New customer", with only 1 **Task** = "Buy 1 product" (say with machine name = `buy_product`).
2. **Goal** = "Silver customer", with **Task** = "Buy 10 products, on 10 different days, in a timeframe of 3 months".
3. **Goal** = "Gold customer", with **Task** = "Buy 100 products, on 25 different days, in a timeframe of 12 months".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = `buy_product`) to keep track of the progress of any user to become a new/silver/gold customer (check the video for a similar sample).

---
Tags: 7, commerce
---


# Question
Title: Adding a drop down field to user registration
We are using Drupal 8 for one of our new project and we need to add a country dropdown to the user registration form. I see that we can add a select box through Manage fields section, but how do I make it configurable?

I mean I want to show the values in the select box from a configurable list.

# Answer
> 0 votes
It sounds like you've found where you can add user fields (under **Administration \>\> Configuration \>\> People \>\> Account settings**). Once you've clicked the **\+ Add Field** button, you can select *List (text)*, add your Label, and click the **Save and Continue** button to configure the options you can add to your country select list.

Here is where you add your list of items. The **Allowed values list** text field is where you can add your selectable items. You can add each country you want, once per line. Once finished, you can click the **Save field settings** to continue to the final configuration page.

Customize the remaining settings and click the **Save setting** button to finish adding the country select box for your user account.

---
Tags: entities, 8
---


title: Filter in view with some dynamic value

text:
# Question
Title: Filter in view with some dynamic value
I have a content type, have a integer value field suppose field name is "field\_xyz" and I have also variable from variable tables (variable\_set('xyz')) which have some dynamic value

Now I want to create a view in which I need to add a filter and showing all node having field\_xyz's value greater than equal to variable\_get('xyz') value. I can do this using views\_php module but I want to do it with manual configuration (No PHP code). Is there anyway ?

# Answer
I won't recommend `views_php` module. This will hamper performance of the site.

You can use `hook_views_query_alter(&$view, &$query)` for this. What you have to do is - add `field_xyz` filter inside view, and override it in `hook_views_query_alter(&$view, &$query)`.
> 1 votes

# Answer
You can do it with 2 extra modules installed: Variable and Views arguments in filters

You need to install the sub-module of Variable called **Variable views**

> Provides views integration for variable, included a default variable argument.

Via it you can add a default value to the contextual filter as a Variable.

As you want to do a `value greater than equal to` comparison you will need the **Views arguments in filters** module:

> Using the "Views arguments in filters" module, you can use placeholders when configuring filters, like so:
>
> * Node: Title CONTAINS %1
> * Node: Post date \>= %2
> 0 votes

---
Tags: 7, views
---


# Question
Title: Invalid datetime format for a field never submitted?
I'm working my the edit page for my mobile app which is fetching data from a Drupal site. I'm fetching data, I'm editing it, and submitting it. However, when submitting back, I'm getting `Internal Server Error : An error occurred (22007): SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2009' for column 'field_yapim_yili_value' at row 1` but I'm not even fetching that field. It's a field collection, if that matters. In fact, I even grep'd my codebase for that field, it doesn't even exist. I checked the content type, it's not required. Any ideas how I can debug this?

UPDATE: Below is what I have in Chrome development tools network tab

```
node[type]:oyuncu
node[title]:Ergün YOLSUZ
node[language]:und
node[field_tc_kimlik_no][und][0][value]:1737769758
node[field_sgk_durumu][und][value]:devam_ediyor
node[field_kategorisi][und][0]:oyuncu
node[field_kategorisi][und][1]:yardimci_oyuncu
node[field_telefon][und][0][value]:05352107332
node[field_telefon_2][und][0][value]:02122111048
node[field_adres][und][0][value]:Mecidiyeköy mah Şehit Ertuğrul Kabataş Cad.
node[field_yasadigi_sehir][und][value]:34
node[field_e_posta][und][0][value]:ergun@magicleaves.com
node[field_cinsiyet][und][value]:bay
node[field_gogus][und][value]:75
node[field_bel][und][value]:96
node[field_kalca][und][value]:116
node[field_dogum_tarihi][und][0][value][date]:1 Nis 2016
node[field_boy][und][value]:170
node[field_kilo][und][value]:75
node[field_goz_rengi][und][value]:kkahve
node[field_ten_rengi][und][value]:esmer
node[field_ayak_no][und][value]:46
node[field_egitim_duzeyi][und][value]:Lisans
node[field_oyunculuk_egitimleri][und][0][value]:-
node[field_diller][und][0][value]:Almanca, İngilizce, Türkçe
node[field_beceriler][und][0][value]:Bateri, gitar, piyano, okçuluk, kılıç sanatları, dans, bilgisayar,
node[field_kisisel][und][0][value]:Çok acayip adamım ben. Cidden bak.
node[field_videolar][und][0][video_url]:
node[field_videolar][und][0][description]:
node[field_okudum_anladim][und][value]:0

```

# Answer
It may be possible your `field_yapim_yili_value` field has a default value and that default value is invalid for datetime format.
> 0 votes

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


# Question
Title: How to display external data using custom form in a Drupal page?
I have created a form custom module for get data from an external url.

`$requestType = drupal_http_request('http://www.example.in/php/example/getSampleType.php',$options);
$loomType =drupal_json_decode($requestType->data);`

This is my Form

Using this result I have created checkboxes and select a value from checkbox then submit the data.

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

$form_state['rebuild'] = TRUE;
$url='http://www.example.in/php/example/exampleSort.php';
//$data1 = http_build_query($form_state['values']['check'], '', '&');

$checked = array();
foreach($form_state['values']['check'] as $key => $val) {
array_push($checked, $val);
  }
$mychecked=checking($checked);

$checkedType = array();
foreach($form_state['values']['checktype'] as $key => $val) {
array_push($checkedType, $val);
  }
$loomType=checking($checkedType);

$datas=array("sampleMachine"=>$mychecked, "sampleType"=> $loomType);
$data =json_encode($datas);
$option = array(
            'method' => 'POST',
            'data' => $data,
            'headers' => array('Content-Type' => 'application/json'),
    );
//$headers = array('Content-Type' => 'application/json');

$response =drupal_http_request($url,$option);

echo "<pre>";
print_r($response);
echo "</pre>";

```

}

I got some result. Now I want to display those results in my drupal page. How can I do that..I am using Drupal 7.

I want to display this in Drupal page in specific format

# Answer
> 1 votes
Not sure why you want to create a custom module for this, since ... there is a module that can "**\*display JSON results in a Drupal page**" ... i.e. the Views JSON Query module. Some details from its project page:

> JSON Query is a Views 3 plugin that adds native JSON query generation. It allows you to parse JSON using Views' graphical query builder. It works much like Views XML Backend but with JSON.

And a screenprint from that same page:

For more details, read about it in the article about "Show external JSON data in Drupal Views".

PS: Similar solution if your input format is XML (instead of JSON), using Views XML Backend.

---
Tags: 7, forms
---


title: hook_load vs. hook_node_load?

text:
# Question
Title: hook_load vs. hook_node_load?
Can someone explain clearly the difference between `hook_load` and `hook_node_load`? `hook_load` says it is a "node-type-specific hook". What does that mean? `hook_node_load` actually has a types parameter.

# Answer
> 3 votes
This paragraph in `hook_node_load()` docs page explains it in details:

> This hook is invoked during node loading, which is handled by entity\_load(), via classes NodeController and DrupalDefaultEntityController. After the node information is read from the database or the entity cache, hook\_load() is invoked on the node's content type module, then field\_attach\_load\_revision() or field\_attach\_load() is called, then hook\_entity\_load() is invoked on all implementing modules, and finally hook\_node\_load() is invoked on all implementing modules.

Here's the breakdown, from first to last call:

1. `entity_load()`
2. `hook_load()`
3. `field_attach_load_revision()` or `field_attach_load()`
4. `hook_entity_load()`
5. `hook_node_load()`

What this means to you is that using a different hook you will be able to modify values earlier or later. This matters if you're overriding value from another module for example. Otherwise, I think it's safe to use either.

# Answer
> 2 votes
Looking at the code of `NodeController::attachLoad()`, and a note in the documentation for `hook_node_load()`, I would say that `hook_load()` is only invoked for the modules implementing a content type. In fact, the note in `hook_node_load()` documentation says the following. (Emphasis is mine.)

> **`hook_load()` is invoked on the node's content type module**, then `field_attach_load_revision()` or `field_attach_load()` is called, then `hook_entity_load()` is invoked on all implementing modules, and finally `hook_node_load()` is invoked on all implementing modules.

Plus, the only code dealing with `hook_load()` implementations is the following one.

```
  // Call object type specific callbacks on each typed array of nodes.
  foreach ($typed_nodes as $node_type => $nodes_of_type) {
    if (node_hook($node_type, 'load')) {
      $function = node_type_get_base($node_type) . '_load';
      $function($nodes_of_type);
    }
  }

```

`node_type_get_base()` returns the node type base, which the function documentation describes as follows:

> The base indicates which module implements this node type and is used to execute node-type-specific hooks.

It seems that in the Drupal 7 documentation, the term *node-type-specific* replaced what in the Drupal 6 documentation was described as *used by node modules*. See Drupal 6 `hook_load()`, Drupal 7 `hook_validate()`, and Drupal 6 `hook_validate()`.

To be sure that is the only code invoking `hook_load()`, see `DrupalDefaultEntityController::attachLoad()`, called from `NodeController::attachLoad()`, since `DrupalDefaultEntityController` is the parent class of `NodeController`; apart from field-related hooks, its code only invokes `hook_entity_load()` and `hook_TYPE_load()` which, for node entities, is `hook_node_load()`.

```
  // Attach fields.
  if ($this->entityInfo['fieldable']) {
    if ($revision_id) {
      field_attach_load_revision($this->entityType, $queried_entities);
    }
    else {
      field_attach_load($this->entityType, $queried_entities);
    }
  }

  // Call hook_entity_load().
  foreach (module_implements('entity_load') as $module) {
    $function = $module . '_entity_load';
    $function($queried_entities, $this->entityType);
  }
  // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  // always the queried entities, followed by additional arguments set in
  // $this->hookLoadArguments.
  $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  foreach (module_implements($this->entityInfo['load hook']) as $module) {
    call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  }

```

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


# Question
Title: Remove the image style from node--type.tpl.php
Is there a way from a node--'type'.tpl.php template to remove the image style of an image field?

# Answer
I found it, in field.tpl.php.

```
$items[n]['#display_settings']['colorbox_node_style'] = "";

```
> 0 votes

---
Tags: 7, theming, nodes, media
---


# Question
Title: clearing cache to call hooks in .module file
I have created a **token** in `.module` file. that gives **current node title**.

But every-time I change the title of node, I have to rebuilt cache *so that* **updated title** get reflected in my token.

Of-course *clearing cache* again and again on every page refresh is *not a good idea*.

**Any other way to call `hook_token_info` and `hook_tokens` automatically on every page load?**

PS: I also installed "**token**" module and this module is using `hook_module_implements_alter(&$implementations, $hook)`.

@edit:

```
function hook_token_info() {
    $info = array();
    $info['tokens']['etf']['node-title'] = array(
    'name' => t('Node Title'),
    'description' => t("Provides current node title."),
    'type' => 'etf',
    );
    return $info;
}

function hook_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();

  $url_options = array('absolute' => TRUE);
  if(isset($options['langcode'])) {
      $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
      $langcode = $options['langcode'];
  }
  else {
      $langcode = NULL;
  }
  $request = \Drupal::request();
  $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
  $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  if ($type == 'etf') {

    foreach ($tokens as $name => $original) {
      switch ($name) {
              case 'node-title':
              $replacements[$original] = $title;
//              drupal_flush_all_caches();
//              sleep(2);
              break;
       }
    }

  }
  return $replacements;
}

```

*All code is written in .module file*

# Answer
### Short

This is wrong use of tokens, it can never work.

### Long

So what you are doing is incorrect usage of tokens. The idea with tokens, is that you have some data object, like a Node, a User etc and based on that you can output something from that object, like the label, uri etc.

Tokens aren't designed to load data from somewhere and display it. For Drupal 8 with all the new caches, it's even more tricky, but even for Drupal 7 this would not work. The reason is that the result of token replacement is cached, since the idea with tokens is that it will always be the same (as long as the data objects which are used for to make the tokens do not change.

To achieve this feature, you would need to load the current node and make it available in the texts where you want to use it as a token, and for Drupal 8 you would also need to add cache context of the url. If I knew what you are using this for, I might be able to give a more precise advise on what the best way would be to achieve this.
> 3 votes

# Answer
The node title already has a token, you can see this, if you install the token module: https://www.drupal.org/project/token

This is only an alpha version, but it is OK to use it.

Go to the help page of the module and you will see that the node title is already there:

```
[node:title]

```

You can use this token only in a node context. If you use it outside of this, for example in a block, you have to add a cache context in this block:

```
$build['#cache']['contexts'][] = 'url.path';

```

And a cache tag to invalidate the block if the node is changed:

```
$build['#cache']['tags'][] = 'node:N';

```

or if any node is changed:

```
$build['#cache']['tags'][] = 'node_list';

```
> 1 votes

---
Tags: 8, caching, tokens
---


title: Feeds import dynamic author change

text:
# Question
Title: Feeds import dynamic author change
I use Feeds so that logged users can upload data. I need to keep track of which user uploads what.

In Feeds importer 'Settings' you define the author, but in my case it should not be static but defined dynamically by the system.

How can I dynamically change that? thanks

# Answer
You will need to make sure that users import content by creating a node. You can then map the author of that node to the author of the feed items that get created.

1. Make sure your importer is attached to a content type. Users can then import content by creating a node of that type. If you use the standalone import form, you cannot track which user uploaded what.
2. Map "Feed node: User ID (parent:uid)" to "User ID (uid)". This will make sure that the author of all nodes that get created will be the same as the author that is set on the feed node.  If you are using the CSV parser, manually enter `parent:uid` instead as source.
> 0 votes

---
Tags: feeds
---


# Question
Title: Replacement for drupal_add_http_header()
I have a custom module which are basically APIs, hence require headers like content-type to be added to the responses. I was using `drupal_add_http_header()` in Drupal 7, but it seems to be deprecated in 8. Is there any replacement?

I did read about it on the Drupal website talking about Symfony object Response, but I am unable to use that either.

# Answer
If you want to modify the headers of a response, you need to use an EventSubscriber. Symphony doesn't have a hook system, but instead uses an event/emitter system. Since it's Symphony driving the request/response cycle, you basically needs to integrate with Symphony to do this.

You could take a look at `\Drupal\Core\EventSubscriber\FinishResponseSubscriber` to see how this is done, the gist of it is this:

```
/**
 * Add custom headers.
 */
class HeaderResponseSubscriber implements EventSubscriberInterface {
  public function onRespond(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Some-Header', 'some value');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }
}

```

Note in the above code all use statements have been excluded, also you need to register your class as a event\_subscriber service, this is done in your module's `module_name.services.yml` file like this:

```
services:
  name_of_service:
    class: Drupal\Full\Namespaced\Path\To\Class
    tags:
      - { name: event_subscriber }

```

You can add arguments (other services) that your class will depend on in the services file like normally.
> 10 votes

---
Tags: 8
---


# Question
Title: Sorting logic with anonymous function does not work
This question is related to my previous question about how to change the sort order in a view. Since this is a new question I thought I better post a new one.

My new problem is that I use `hook_views_pre_render()` as suggested, but I am having trouble getting the views sort order right. I use an anonymous function like this to change the views order:

```
/**
* Implementation of hook_views_pre_render. Sorts the nodes under "Givare"
 */
function mysite_views_pre_render(&$view) {
    if ($view->name === 'related_items' && $view->current_display === 'probes') {
        $node = node_load(arg(1));
        $sortorder = array();
        $groups = $node->field_lagg_till_givargrupp['und'];
        foreach($groups as $group){
            $group_nid = $group['nid'];
            $group_node = node_load($group_nid);
            $probe_nids = $group_node->field_koppla_givare['und'];
            foreach($probe_nids as $probe_nid){
                $sortorder[] = $probe_nid['nid'];
            }
        }

        usort($view->result, function ($a, $b) use ($sortorder) {
            $cmpa = array_search($a->nid, $sortorder);
            $cmpb = array_search($b->nid, $sortorder);
            dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb);
            if($cmpa === $cmpb) {
                return 0;
            }
            return ($cmpa < $cmpb) ? -1 : 1;
        });
    }
}

```

The variable `$sortorder` contains an array with nids in the wanted order. But the resulting `$views_result` does not follow that order (but it is altered, just in the wrong way). Can anyone see what I am doing wrong?

EDITED: added context – the view in question is a block display with a grid setting (there are several of these block displays in the same view and these block displays are used by Quick Tabs to render each block under a tab as related items.) In this particular block display I have tested to omit exposed filters, to deselect grouping by title etcetera to see if that would impact the sorting, but with no luck. I was surprised that this block needed sorting at all because I give the order explicitely with a contextual filter. See this question for the contextual filter: Sort criteria is ignored in Views

Also, as I added the row `dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb);` I can see that there are more than one **hundred** value pairs, but there are only 22 items to be rendered(!). The first few rows of that dsm() looks like this, where for example the nid 20726 is repeated several times:

> 20726 20693 7 12
>
> 21863 20726 5 7
>
> 20726 20695 7 4
>
> 20726 20697 7 0
>
> 20726 20699 7 15
>
> 20861 20726 21 7
>
> 20860 20726 20 7
>
> 20859 20726 19 7
>
> 20858 20726 23 7
>
> 20857 20726 22 7
>
> 20768 20726 2 7

# Answer
PROBLEM SOLVED. As J. Reynolds pointed out there were missing nid values in $view-\>result before the sorting was made.

There was also an issue with the nids because I had forgotten to set the field mapping (migrate d2d) to "do not create automatic URLs" for pathauto during a an earlier migration from D6 to D7 of the group nodes that contained the items in question. So the item nids were fetched from the wrong group entity. My mistake :-(.

But everything is sorted out now. Thanks for your input!
> 0 votes

---
Tags: 7, views
---


title: Sort criteria is ignored in Views

text:
# Question
Title: Sort criteria is ignored in Views
I have a view that shows related products by means of a contextual filter (PHP). If the returned nid values from the contextual filter is for example "**20697**, **20735**, **20768**, **20903**, **20695**, **21863**" I want the nodes to be rendered in that order.

But they don't, I have tried all kinds of settings with no luck. The order given is in fact the delta of a certain field, but when I try to use the delta version of that field as a sort criteria, it is simply ignored, even if I add a relationship under "**Advanced**".

Anyone who recognizes this behaviour?

EDITED: This is my contextual PHP filter. It fetches all the nid's entered in a certain node reference field as I explained above. And I want them to show in that same order, so that the admin user can sort the order by dragging the rows in the Node reference field:

```
$node = menu_get_object();
$value = null;
if(empty($node->field_lagg_till_givargrupp['und'][0]['nid'])){
    $node->field_lagg_till_givargrupp['und'][0]['nid'] = NULL;
    $value = FALSE;
         return $value;
} else {
        $limit = count($node->field_lagg_till_givargrupp['und']);
        for($i = 0; $limit > $i; ++$i){
            $group_nid = $node->field_lagg_till_givargrupp['und'][$i]['nid'];
            $group_node = node_load($group_nid);
            $limit2 = count($group_node->field_koppla_givare['und']);
            for($x = 0; $limit2 > $x; ++$x){
                $value .= $group_node->field_koppla_givare['und'][$x]['nid'].",";
            }
        }
        return rtrim($value, ",");
}

```

EDITED: this is the SQL query (I have added a few nids as an example);

```
SELECT node.nid AS nid, field_data_field_koppla_givare.delta AS field_data_field_koppla_givare_delta, field_data_field_koppla_givare.field_koppla_givare_nid AS field_data_field_koppla_givare_field_koppla_givare_nid, 'node' AS field_data_field_givargrupper_node_entity_type, 'node' AS field_data_field_huvudbild_givare_node_entity_type, 'node' AS field_data_field_tumnagel_givare_node_entity_type, 'node' AS field_data_field_underrubrik_givare_node_entity_type, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_artikelnr_produkt_node_entity_type, 'node' AS field_data_field_pris_givare_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_koppla_givare} field_data_field_koppla_givare ON node.nid = field_data_field_koppla_givare.entity_id AND (field_data_field_koppla_givare.entity_type = 'node' AND field_data_field_koppla_givare.deleted = '0')
WHERE (( (node.nid IN('20697', '20735', '20768', '20903', '20695') ) )AND(( (node.status = '1') )))
ORDER BY field_data_field_koppla_givare_field_koppla_givare_nid ASC

```

And this is the simple query without the delta field and without the *order by* criteria trying to sort in hook\_views\_pre\_render() instead (see this question about that Sorting logic with anonymous function does not work):

```
SELECT node.nid AS nid, 'node' AS field_data_field_givargrupper_node_entity_type, 'node' AS field_data_field_huvudbild_givare_node_entity_type, 'node' AS field_data_field_tumnagel_givare_node_entity_type, 'node' AS field_data_field_underrubrik_givare_node_entity_type, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_artikelnr_produkt_node_entity_type, 'node' AS field_data_field_pris_givare_node_entity_type
FROM
{node} node
WHERE (( (node.nid IN('20697', '20735', '20768', '20903', '20695') ) )AND(( (node.status = '1') )))

```

As you can see I am really stuck in all ways about this ...

# Answer
> 0 votes
You can use a custom sort in your module like

```
/**
* Implementation of hook_views_query_alter().
 */
function yourmodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_machine_name_view') {
        $query->add_orderby('node', 'created', 'DESC');
    }
  }
}

```

# Answer
> 0 votes
PROBLEM SOLVED. Just in case anyone would have the same problem... there was in fact nothing wrong with my contextual filter. With help (thanks J. Reynolds) I solved the sorting issue with hook\_views\_pre\_render(). See this question for the answer: Sorting logic with anonymous function does not work

---
Tags: 7, views
---


# Question
Title: How to bulk update entities using the Feeds module, without existing mappings to a "unique target"
Importing new entities with feeds using a published csv file is very handy. I use Google Sheets to publish a csv file and use Feeds to create new nodes, which then can be updated based on a unique target field.

However, I have a number of sites that need their content to be bulk-updated in a similar fashion, but these entities were not imported through Feeds, so no unique target / hash check is present to update them.

Is there a way to make drupal import a feed and check for existing entities using the title field, and modify/populate the corresponding fields?

# Answer
You could use a custom text field as unique target by using the "Unique values" validator of the Field validation module.

You could also implement `hook_feeds_processor_targets_alter()` in a custom module to add a "unique callback" to a target. In that callback you can implement your own logic for retrieving an existing entity.

See https://www.drupal.org/node/1307732#field\_as\_unique\_id\_7 for a list of steps for both solutions. See also feeds.api.php for more information about implementing "unique" callbacks.
> 1 votes

---
Tags: entities, feeds
---


# Question
Title: How to import nodes with custom fields using Feeds module and Feeds JSONPath Parser
I've got a content type called 2Wd-Tractor with this structure :

* Model (node title)
* Engine
* Transmission
* Operational
* Hydraulic System

Engine field is a custom field implemented using Field Api and it does have these subfields :

* Make
* Model
* Net Power
* PTO Power
* Aspiration
* Power Measured At
* and ...

After that to make this field visible in feeds mapping hook\_feeds\_processor\_targets\_alter was implemented.

Here is the code :

```
foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance)
{
    $info = field_info_field($name);
    unset($callback);

    if ($info['type']=='uceen2wdtractor')
    {
        //The callback for this field type goes here.
        $callback = 'TARGET_SETTER_FOR_en2wdtractor';
    }

    if (isset($callback))
    {
        $targets[$name] =array(
            'name'=>check_plain($instance['label']),
            'callback' => $callback,
            'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
        );
    }
}

```

Data is imported to Feeds using json files , An importer is provided with these settings :

---

finally this is my json file :

The Problem is no data is stored in Engine field . this is the dsm($node) in hook\_node\_presave :

# Answer
> 2 votes
There are 3 places where the problem could lie:

1. Data not being correctly parsed by feeds
2. Data not being correctly saved by feeds
3. Problem with the field definition itself

Number 3 is ruled out since fields save correctly via the UI.

**Troubleshooting Number 1.**

Add a `hook_feeds_after_parse` to your module and either step through with a debugger or dump the `$items` array to the `dblog`:

```
function mymodule_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
  if($source->id == 'ENTER YOUR SOURCE ID HERE') {
    watchdog('My Module', '<pre>' . print_r($result->items, TRUE) . '</pre>');
  }
}

```

Question: is there a value in the items array for your engine field?

If no: there is a problem in the JSON parser definitions and feeds is not extracting the data correctly.

If yes: if the information exists that you require, i.e. every sub field value exists then the problem is not with the feeds parsing.

**Troubleshooting Number 2**

This points to an issue with your implementation of `hook_feeds_processor_targets_alter`. Most likely, the data is not in the correct format for saving. Add some watchdog statements in this function to determine:

1. Is the callback being fired?
2. If the callback is being fired then there is an issue with your hook\_feeds\_set\_target implementation. It isn't providing the correct data format to allow the field to be saved. You could add a `dpm()` statement to `hook_node_update` and then save a node via the UI. This will show the correct format.

# Answer
> 1 votes
For troubleshooting data that is not correctly parsed, you can also use the Feeds Import Preview module. This module allows you to see what your source looks like after it has been parsed.

---
Tags: 7, feeds
---


# Question
Title: Where is the target ISBN in feeds module?
I'm using an ISBN module that create a simple textfield with "ISBN" as a type (this module makes validation of the books ISBN when inserted on the textfield when creating a book) It's a pretty cool module.

But now i want to populate my database with books from a CSV file, so in the header i've : "title, author,..,ISBN" i import this CSV file using feeds module, everything is imported except the ISBN. Even when i want to create a mapping for ISBN, i can't find field\_data\_field\_isbn in the targets list. I know that the ISBN module makes validation (or not) for isbns only if you "write it" manually using the textfield. But is there any way to get ISBN from CSV with feeds (it's not important if it's validated or not) ?

Thank you

# Answer
The ISBN Field module doesn't support Feeds yet. Every module that provides a field should write their own mapper to support Feeds, as Feeds isn't able to dynamically know how to populate a field.

In the ISBN Field issue queue there is a patch available which might solve your problem: https://www.drupal.org/node/1930538
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: How to add a class to the <a> link elements within a Multiple Values field in a View?
I have a Views field (in this case, taxonomy term references) with Multiple Values set to "Display all values in the same row", using the Link formatter and a seperator. I want to add a class to *each* "multiple values" `<a>` element *within* this one field. My output currently looks like this:

```
<div class="field-content">
  <a href="/some/path" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Some name</a>
  ,
  <a href="/another/path" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Another name</a>
</div>

```

I simply want to add classes to the multiple links within the field (and not the the wrapper), like this:

```
<div class="field-content">
  <a class="some-class" href="/some/path" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Some name</a>
  ,
  <a class="some-class" href="/another/path" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Another name</a>
</div>

```

While my fields are taxonomy term references ideally I'd like to know how to do this with any of the many fields that use the "Link" formatter.

Note that this field is included with other fields using a replacement pattern in a custom text field, which unfortunately seems to prevent field tpl.php options from working.

---

This seems like it should be simple, but I can't find a way even after trying all these things:

* Every combination of Views **Multiple Field Settings** (which contain no means to add a class) and **Style Settings** (which only affect the field *wrapper*, not each of the multiple items)
* Reading about twenty related questions on here, none of which combine all the elements in my question (CSS class, views, multiple value field), I couldn't find anything that actually works, and the only suggestions that sound like they might work were to use Display Suite, which is a great module but way too big an added overhead for something so minor as adding some classes to some links, or giving up, cheating and adding the class client-side in jQuery, or brute force with Views PHP. Most answers don't apply to Multiple Values fields (even when the asker specified such). This suggestion based on `hook_preprocess_field` looks perfect, but it doesn't get called from Views.
* Hacking through the objects available in `hook_preprocess_views_view_field()` and `hook_views_view_field__[view_name]__[view_style]__[field_name]()`. The former seems to treat multiple field items as a lump and not allow changes to each, the latter, when trying to do something like this, just wouldn't change anything at all
* Scouring Views and Drupal Core's `tpl.php` files, and Views' handler for links. No changes here seemed to make any difference.
* Checking the Views issue queue. I found a feature request and non-committed patch, adding the ability to set a class like this - but it only applies to multiple field items that are set to be a list item, not seperator-separated items.
* I've considered creating a custom Views field formatter, but that seems like a terrible solution given that I'd simply be duplicating the existing Link formatter then adding a class. I've looked for a way to hook in to an existing formatter but haven't found one.

# Answer
Just rewrite the lot with appropriate Replacement Patterns.

In Views:

**Rewrite Results:**

* Rewrite the output of this field : Tick
* Text : Add as appropriate, ie \[field\_link-title\]
* Output this field as a link : Tick
* Link path : Add as appropriate, ie \[field\_link-url\]
* Link class : Add as appropriate

Above assumes your multi-value field is Link.

If any other field you can just Rewrite with output as link, link path and link class.

THERE does not seem to be a way to write the other original attributes back into the link. They can be obtained from a Replacement Pattern, but there is no form input to add them back.
> 0 votes

---
Tags: 7, views, entities
---


title: Custom link to add product

text:
# Question
Title: Custom link to add product
As question states, i'm trying to make a custom menu ( hook\_menu() ) to call the same pages as how commerce does it originally (will link everything below)

The idea is to let Authenticated users add products (of all product types)
I have changed the permissions for creating product entities
and can acces, as Authenticated users, the add form via the the admin url

But i'd like to change that so they have a custom link and don't see the whole admin/commerce/products/add/bag

but only
/products/add/bag

i have tried to do this by adding a custom menu with the hook\_menu() but always get an 'You are not authorized to access this page.' message, even when i am connected as admin

Anyone any idea what i should change to be able to acces it outside de admin zone?

my hook\_menu():

```
function TTK_product_form_menu() {

  //non admin form
  if (function_exists('commerce_product_types')) {
    $commerce_product_bp = drupal_get_path('module', 'commerce_product').'/';

    foreach (commerce_product_types() as $type => $product_type) {

      $items['products/add/' . strtr($type, array('_' => '-'))] = array(
        'title' => 'Create !name',
        'title arguments' => array('!name' => $product_type['name']),
        'description' => $product_type['description'],
        'page callback' => $commerce_product_bp.'commerce_product_ui_product_form_wrapper',
        'page arguments' => array(commerce_product_new($type)),
        'access callback' => $commerce_product_bp.'commerce_product_access',
        'access arguments' => array('create', $type),
        'file' => $commerce_product_bp.'includes/commerce_product_ui.products.inc',
      );
    }
  }

  return $items;
}

```

# Answer
> 0 votes
problem was that i didn't knew very well how menu hook worked
solution is:

```
foreach (commerce_product_types() as $type => $product_type) {
  $items['sell/' . strtr($type, array('_' => '-'))] = array(
    'title' => 'Sell !name',
    'title arguments' => array('!name' => $product_type['name']),
    'page callback' => 'commerce_product_ui_product_form_wrapper',
    'page arguments' => array(commerce_product_new($type)),
    'access callback' => 'commerce_product_access',
    'access arguments' => array('create', commerce_product_new($type)),
    'file' => 'includes/commerce_product_ui.products.inc',
    'file path' => $commerce_product_bp,
  );
}

```

didn't have to apend the path to function names, thought those where called by path for some reason..

---
Tags: 7, commerce
---


title: Video Migration from MySQL

text:
# Question
Title: Video Migration from MySQL
I have a video link and the video is there in my FTP. I need to migrate videos from mysql to DRUPAL database. Video complete path is stored in mysql database at present. In this process I dont want to transfer videos from this FTP, instead I want to link somehow to the video-upload field of my content type. Is this achievable ? Is there a module to do this? I have used feeds module for migration but int that I can not migrate videos.

Content type: Sports Fields: Sports Type(Text) and Sports Video(Video upload)

I have a video link in my existing database. I want to migrate or somehow link the video to the Sports Video field.

# Answer
> 0 votes
If you want to keep the video stored somewhere else and you don't need to consider the video as a managed Drupal file, then you could just migrate the 'video url' to a text field or a custom field type.

Depending on how you would like to output the video to your visitors you could create your own field formatter. And use the stored 'video url' as a source for your video player.

---
Tags: migrations, 7, files
---


# Question
Title: drupal_add_js() does not add .js file from libraries folder
I have a page callback where I want to add a colorbox library by this code:

```
drupal_add_js('sites/all/libraries/colorbox/jquery.colorbox-min.js', 'file');

```

The file exists, path is right. But in html is this file not included. Why it does not work?

# Answer
That seems apply to your issue :

> This problem occurs because the path to library is often incorrectly set as
>
> ```
> libraries\colorbox\jquery.colorbox-min.js
>
> ```
>
> The solution should be to correct the path. You need to place the whole Colorbox plugin directory after unpacking it in sites/all/libraries This means the path should look like
>
> ```
> sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js
>
> ```

Source
> 1 votes

---
Tags: theming
---