# Question
Title: "Missing configuration for parameter commerce_order"
I'm trying to define a default rule in a small module based on Commerce Price Table and Commerce Rules Extra. The rule is to set price based on the quantity of produtcs that contains a partial sku in the current order and the price table of the line item.

I'm new to Rules... and commerce. I'm not sure if I set the default rule correctly to get the current order or if the error is in the definition of the action (or if it's to late at night for me to see it!).

The error I got : Error: Missing configuration for parameter commerce\_order.

Here is the current state of the code:

```
/**
* Based on Commerce Price Table and Commerce Rules Extra
*/

/**
 * Implements hook_default_rules_configuration().
 */
function commerce_price_table_sku_contains_default_rules_configuration() {
  $rules = array();

  // Add a reaction rule to update a shopping cart order's status to "Shopping
  // cart" when a product is added to or removed from the order.
  $rule = rules_reaction_rule();

  $rule->label = t('Override price with price table if sku contains');
  $rule->active = TRUE;

  $rule
    ->event('commerce_product_calculate_sell_price')
    ->condition('entity_has_field', array(
      'entity:select' => 'commerce-line-item',
      'field' => 'commerce_product',
    ))
    ->condition('entity_has_field', array(
      'entity:select' => 'commerce-line-item:commerce-product',
      'field' => 'field_price_table',
    ))
    ->action('commerce_price_table_sku_contains_set_price', array(
      'site:current-cart-order' => 'commerce_order', // Wrong? Error: Missing configuration for parameter commerce_order.
      'product_id' => '',
      'commerce_line_item:select' => 'commerce-line-item',
      'price_table:select' => 'commerce-line-item:commerce-product:field-price-table',
      'component_name' => 'base_price',
    ));

  $rule->weight = -9;

  $rules['commerce_price_table_sku_contains_override_price'] = $rule;

  return $rules;
}

/**
 * Implements hook_rules_action_info().
 */
function commerce_price_table_sku_contains_rules_action_info() {
  $actions = array();

  $actions['commerce_price_table_sku_contains_set_price'] = array(
    'label' => t('Set the unit price to a table based price'),
    'parameter' => array(
      'commerce_order' => array( // Wrong? Error: Missing configuration for parameter commerce_order.
        'type' => 'commerce_order',
        'label' => t('Order'),
        'description' => t('The order whose line items should be checked for the specified product. If the specified order does not exist, the quantity is 0.'),
      ),
      'product_id' => array(
        'type' => 'text',
        'label' => t('Product(s) SKU(s)'),
        'description' => t('The SKU of the product must contain this information. Each SKUs on a newline'),
      ),
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
      'price_table' => array(
        'label' => t('Price table'),
        'type' => 'list<commerce_price_table>',
      ),
      'component_name' => array(
        'type' => 'text',
        'label' => t('Price component type'),
        'description' => t('Price components track changes to prices made during the price calculation process, and they are carried over from the unit price to the total price of a line item. When an order total is calculated, it combines all the components of every line item on the order. When the unit price is altered by this action, the selected type of price component will be added to its data array and reflected in the order total display when it is formatted with components showing. Defaults to base price, which displays as the order Subtotal.'),
        'options list' => 'commerce_line_item_price_component_options_list',
        'default value' => 'base_price',
      ),
    ),
    'group' => t('Commerce price table sku contains'),
  );

  return $actions;
}

/**
 * Rules callback: executes the "Replace the price for a price table" action.
 */
function commerce_price_table_sku_contains_set_price($order, $sku, $line_item, $price_table, $component_name) {
  // If the line item contains a product...
  if (in_array($line_item->type, commerce_product_line_item_types())) {
    // Load its referenced product.
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $product = $line_item_wrapper->commerce_product->value();

    // Bail now if the unit price is unset.
    $unit_price = commerce_price_wrapper_value($line_item_wrapper, 'commerce_unit_price');

    if (empty($unit_price)) {
      return;
    }

    // Fetch the quantity of product that contains the partials skus in the order.
    $quantity = commerce_price_table_sku_contains_partial_sku($order, $sku);

    // Fetch the table based price for the current product quantity.
    $table_price = commerce_price_table_get_amount_qty($product, $quantity, $price_table);

    // If we got a valid table price...
    if (!empty($table_price)) {
      // If the currency is different from the current currency, convert it.
      if ($unit_price['currency_code'] != $table_price['currency_code']) {
        $line_item_wrapper->commerce_unit_price->amount = commerce_currency_convert($unit_price['amount'], $unit_price['currency_code'], $table_price['currency_code']);
        $line_item_wrapper->commerce_unit_price->currency_code = $table_price['currency_code'];

        // Convert the currency code of the price's components.
        if (!empty($unit_price['data']['components'])) {
          foreach ($unit_price['data']['components'] as $key => &$component) {
            $component['price']['amount'] = commerce_currency_convert($component['price']['amount'], $component['price']['currency_code'], $table_price['currency_code']);
            $component['price']['currency_code'] = $table_price['currency_code'];
          }

          $wrapper->commerce_unit_price->data = $unit_price['data'];
        }
      }

      // Calculate the difference between the current unit price amount and the
      // table price and create a price array representing the difference.
      $current_amount = $unit_price['amount'];
      $updated_amount = $table_price['amount'];

      $difference = array(
        'amount' => $updated_amount - $current_amount,
        'currency_code' => $table_price['currency_code'],
        'data' => array(),
      );

      // Set the amount of the unit price and add the difference as a component.
      $line_item_wrapper->commerce_unit_price->amount = $updated_amount;

      $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
        $line_item_wrapper->commerce_unit_price->value(),
        $component_name,
        $difference,
        TRUE
      );
    }
  }
}

/**
 * Checks to see if a particular products exists on an order
 * and calculates the total quantity, based on a sku fragment.
 */
function commerce_price_table_sku_contains_partial_sku($order, $skus) {
  // Initialize
  $total_quantity = 0;

  // Don't do anything without a valid order.
  if (!empty($order)) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    // Populate the array of the quantities of the products on the order.
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
        // Extract SKU and quantity from line item.
        $line_item_sku = $line_item_wrapper->commerce_product->sku->value();
        $quantity = $line_item_wrapper->quantity->value();

        // Does the SKU exist partially in the order SKU?
        // multiple skus on newlines
        $sku = strtok($skus, PHP_EOL);
        while ($sku !== false) {
            if (strpos($line_item_sku, $sku) !== FALSE) {
              // Update quantity.
              $total_quantity += $quantity;
            }
            $sku = strtok( PHP_EOL );
        }
      }
    }
  }

  return $total_quantity;
}

```

Thx!

# Answer
> 0 votes
The error was simple and in the \_default\_rules\_configuration().

It was just the array key name that was wrong... it was late last night.

The second modification is to use "commerce-line-item:order" insted of "site:current-cart-order".

Here is the code that works:

```
<?php
/**
 * Based on Commerce Price Table and Commerce Rules Extra
 */

/**
 * @file
 * Default rule configurations for Cart.
 */

/**
 * Implements hook_default_rules_configuration().
 */
function commerce_price_table_sku_contains_default_rules_configuration() {
    $rules = array();

    // Add a reaction rule to update a shopping cart order's status to "Shopping
    // cart" when a product is added to or removed from the order.
    $rule = rules_reaction_rule();

    $rule->label = t('Override price with price table if sku contains');
    $rule->active = TRUE;

    $rule
        ->event('commerce_product_calculate_sell_price')
        ->condition('entity_has_field', array(
            'entity:select' => 'commerce-line-item',
            'field' => 'commerce_product',
        ))
        ->condition('entity_has_field', array(
            'entity:select' => 'commerce-line-item:commerce-product',
            'field' => 'field_price_table',
        ))
        ->action('commerce_price_table_sku_contains_set_price', array(
            'order' => 'commerce-line-item:order',
            'product_id' => '',
            'commerce_line_item:select' => 'commerce-line-item',
            'price_table:select' => 'commerce-line-item:commerce-product:field-price-table',
            'component_name' => 'base_price',
        ));

    $rule->weight = -9;

    $rules['commerce_price_table_sku_contains_override_price'] = $rule;

    return $rules;
}

/**
 * Based on Commerce Price Table and Commerce Rules Extra
 */

/**
 * Implements hook_rules_action_info().
 */
function commerce_price_table_sku_contains_rules_action_info() {
    $actions = array();

    $actions['commerce_price_table_sku_contains_set_price'] = array(
        'label' => t('Set the unit price to a table based price'),
        'parameter' => array(
            'order' => array(
                'type' => 'commerce_order',
                'label' => t('Order'),
                'description' => t('The order whose line items should be checked for the specified product. If the specified order does not exist, the quantity is 0.'),
            ),
            'product_id' => array(
                'type' => 'text',
                'label' => t('Product(s) SKU(s)'),
                'description' => t('The SKU of the product must contain this information. Each SKUs on a newline'),
            ),
            'commerce_line_item' => array(
                'type' => 'commerce_line_item',
                'label' => t('Line item'),
            ),
            'price_table' => array(
                'label' => t('Price table'),
                'type' => 'list<commerce_price_table>',
            ),
            'component_name' => array(
                'type' => 'text',
                'label' => t('Price component type'),
                'description' => t('Price components track changes to prices made during the price calculation process, and they are carried over from the unit price to the total price of a line item. When an order total is calculated, it combines all the components of every line item on the order. When the unit price is altered by this action, the selected type of price component will be added to its data array and reflected in the order total display when it is formatted with components showing. Defaults to base price, which displays as the order Subtotal.'),
                'options list' => 'commerce_line_item_price_component_options_list',
                'default value' => 'base_price',
            ),
        ),
        'group' => t('Commerce price table sku contains'),
    );

    return $actions;
}

/**
 * Rules callback: executes the "Replace the price for a price table" action.
 */
function commerce_price_table_sku_contains_set_price($order, $sku, $line_item, $price_table, $component_name) {
    // If the line item contains a product...
    if (in_array($line_item->type, commerce_product_line_item_types())) {
        // Load its referenced product.
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
        $product = $line_item_wrapper->commerce_product->value();

        // Bail now if the unit price is unset.
        $unit_price = commerce_price_wrapper_value($line_item_wrapper, 'commerce_unit_price');

        if (empty($unit_price)) {
            return;
        }

        // Fetch the quantity of product that contains the partials skus in the order.
        $quantity = commerce_price_table_sku_contains_partial_sku($order, $sku);

        // Fetch the table based price for the current product quantity.
        $table_price = commerce_price_table_get_amount_qty($product, $quantity, $price_table);

        // If we got a valid table price...
        if (!empty($table_price)) {
            // If the currency is different from the current currency, convert it.
            if ($unit_price['currency_code'] != $table_price['currency_code']) {
                $line_item_wrapper->commerce_unit_price->amount = commerce_currency_convert($unit_price['amount'], $unit_price['currency_code'], $table_price['currency_code']);
                $line_item_wrapper->commerce_unit_price->currency_code = $table_price['currency_code'];

                // Convert the currency code of the price's components.
                if (!empty($unit_price['data']['components'])) {
                    foreach ($unit_price['data']['components'] as $key => &$component) {
                        $component['price']['amount'] = commerce_currency_convert($component['price']['amount'], $component['price']['currency_code'], $table_price['currency_code']);
                        $component['price']['currency_code'] = $table_price['currency_code'];
                    }

                    $wrapper->commerce_unit_price->data = $unit_price['data'];
                }
            }

            // Calculate the difference between the current unit price amount and the
            // table price and create a price array representing the difference.
            $current_amount = $unit_price['amount'];
            $updated_amount = $table_price['amount'];

            $difference = array(
                'amount' => $updated_amount - $current_amount,
                'currency_code' => $table_price['currency_code'],
                'data' => array(),
            );

            // Set the amount of the unit price and add the difference as a component.
            $line_item_wrapper->commerce_unit_price->amount = $updated_amount;

            $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
                $line_item_wrapper->commerce_unit_price->value(),
                $component_name,
                $difference,
                TRUE
            );
        }
    }
}

/**
 * Checks to see if a particular products exists on an order
 * and calculates the total quantity, based on a sku fragment.
 */
function commerce_price_table_sku_contains_partial_sku($order, $skus) {
    // Initialize
    $total_quantity = 0;

    // Don't do anything without a valid order.
    if (!empty($order)) {
        $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

        // Populate the array of the quantities of the products on the order.
        foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
            if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
                // Extract SKU and quantity from line item.
                $line_item_sku = $line_item_wrapper->commerce_product->sku->value();
                $quantity = $line_item_wrapper->quantity->value();

                // Does the SKU exist partially in the order SKU?
                // multiple skus on newlines
                $sku = strtok($skus, PHP_EOL);
                while ($sku !== false) {
                        if (strpos($line_item_sku, $sku) !== FALSE) {
                            // Update quantity.
                            $total_quantity += $quantity;
                        }
                        $sku = strtok( PHP_EOL );
                }
            }
        }
    }

    return $total_quantity;
}

```

Thx.

---
Tags: commerce, rules
---


# Question
Title: How to save the definition of an entity?
I am trying to figure out if there is a difference between saving an instance of an entity and saving the definition of an entity.

My use case is this: I wrote a small module that defines an entity, which I then used in other code on my site. All of this worked just fine, and I thought that once I had created some instances of my entity, and that those instances were stored in my database, I could then disable the little module that defined my entity. I thought, in other words, that defining an entity would be like defining a Content Type, and that once you had done so the new entity, like a new Content Type, would "stick around".

That, however, is not how things work. If I disable the little module that defines the new entity, that entity disappears from my system, and the code that uses that entity fails. Re-enabling the little entity-defining module returns everything to normal and the site works again.

I think I may have missed a step here \[entity\_save?\] but find nothing in the documentation that discusses saving the definition of a programatically defined entity.

Two more things. First, I have noticed that the "model" module, which provides a template for creating your own entities, exhibits the same behavior that my little module did: if I disable that module, the entities that I used it to define vanish from my system. I have also noticed that the Entity Construction Kit \[ECK\] creates, in addition to the base table, two additional tables, one of which, eck\_bundles, looks like it has entity properties. I have not been willing to disable the ECK, though, because the documentation says that Drupal needs it.

Another way of posing my question would be this: "Do you have to keep the code that defines your entity in your system, or is there some way of storing the entity definition for subsequent use?"

I am running Drupal 7.39

# Answer
> 0 votes
Yes, the module providing the entity type needs to be enabled for the entity to work correctly, and any module using that entity should include the defining module as a dependency. Drupal modules are generally not factories that produce configuration and can then go away (the major exception being modules generated with the Features module which can behave this way at times), they generally provide ongoing functionality that Drupal will expect to be available on demand.

In your case Drupal loads the class from that module under a variety of conditions (not the least of which is anytime you load an instance of that entity) and so needs to continue to be active as long as you use the entity. That module is also the place to define any special behaviors of the new type of entity you have defined (like changes to the save/load process, or other actions the entity may provide).

---
Tags: 7, entities
---


# Question
Title: How to include only an updated custom field in an email created using Rules?
I used the Rules module to create a rule with an event "After update existing content". This rule sends an email to the editing user when that user makes an edit to one of the multiple custom fields in a node. I would like to include only the custom field that he/she changed in that email.

# Answer
> 1 votes
# Part 1: Processing a single field

Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

```
{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-optionlist" ],
          "value" : [ "node:field-optionlist" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with a special field value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with a value (which is [node:field-optionlist]) you needed to be informed about ..."
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "After updating existing content".
* In my case I have a selection list field with machine name `field_optionlist`, and a few possible values.
* The Rules Condition checks if the "The selected value changed".
* If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Change the field name of `field_optionlist` to match the field name of your content type, and adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

# Part 2: Processing a multiple fields

## Option 1 - a SEPARATE rule for processing each field

If you have multiple fields, create a similar rule for each of them, so that it will send 1 single eMail for each field update.

## Option 2 - a SINGLE rule for processing all fields together

If you have like a dozen fields, using Option 1 implies .... a dozen rules (fairly straight forward rules, but a bit of a maintenance challenge). To consolidate them all in a single rule, you should consider (both of) these refinements:

* a **Rules Component** (which will replace the Rules Action as in the prior rule example), and which you'll be able to reuse within the Rules Action later on by assigning appropriate values to its variables (as further detailed below).
* the Conditional Rules module which will allow for conditions to be part of a Rules Action.

Read on for more details on this refinements.

### Rules Component

Create a Rules Component that will (simply) produce an eMail, using these ***Parameters***:

* User to be notified with machine name `user_to_notify`.
* Updated Field Label with machine name `updated_field_label`.
* Updated Field Value (old) with machine name `updated_field_value_old`.
* Updated Field Value (new) with machine name `updated_field_value_new`.

Here is an example (in Rules export format) of such Rules component (I trust the eMail subject, content, etc is clear from just reading the source ...):

```
{ "rules_email_field_updates" : {
    "LABEL" : "eMail field updates",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "user_to_notify" : { "label" : "User to be notified", "type" : "user" },
      "updated_field_label" : { "label" : "Updated Field Label", "type" : "text" },
      "updated_field_value_old" : { "label" : "Updated Field Value (old)", "type" : "text" },
      "updated_field_value_new" : { "label" : "Updated Field Value (new)", "type" : "text" }
    },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Notification about an updated field",
          "message" : "Please be aware that the field labeled \u0022[updated-field-label:value]\u0022 has been updated from \u0022[updated-field-value-old:value]\u0022 to \u0022[updated-field-value-new:value]\u0022.",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

### Conditional Rules

On top of the `field_optionlist` field from above, let's assume we add a 2nd field, i.e. a *free format text* field with machine name `field_free_format_text`. Assuming that you enabled the Conditional Rules module, you should be able to import the rules example below (in Rules export format) in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names):

```
{ "rules_notify_editing_user_of_selected_field_updates" : {
    "LABEL" : "Notify editing user of selected field updates",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Option List",
                  "updated_field_value_old" : [ "node-unchanged:field-optionlist" ],
                  "updated_field_value_new" : [ "node:field-optionlist" ]
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Free Format Text",
                  "updated_field_value_old" : [ "node-unchanged:field-free-format-text" ],
                  "updated_field_value_new" : [ "node:field-free-format-text" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```

If you're familiar with Rules, the above Rules example should be self explaining. If you're not, here are a few more details to explain the rule:

* **Rules Event**: After updating existing content.
* **Rules Conditions**: Check if we're processing content that has either of our 2 fields.
* **Rules Actions**:
    + If the value of `field_optionlist` changed, then invoke the *Rules Component*, with parameters related to this field.
    + If the value of `field_free_format_text` changed, then invoke the *Rules Component*, with parameters related to this field.

Voilà, happy (Conditional) Rules-ing!

---
Tags: entities, rules, emails
---


# Question
Title: How to change the default date format in Rules?
I've created a rule to send an html email which contains a date, printed using tokens as `[commerce-order:field_delivery_date]`. In email, the date looks like `2016-07-08 00:00:00 to 2016-08-02 00:00:00`. The date may or may not be an interval.

How can I alter the date format in Rules?

I know that I can use something like `[commerce-order:field-delivery-date:value:custom:j m] - [commerce-order:field-delivery-date:value2:custom:j m Y]` which outputs `08.07 - 02.08.2016`.

But, I don't always have an interval, I can only have the start date, which should be printed as `08.07.2016`.

# Answer
> 1 votes
Try to use what you have defined as the format for `short` / `medium` / `long` format in your Drupal date settings, using either of these tokens:

* `[commerce-order:field_delivery_date:value:short]`
* `[commerce-order:field_delivery_date:value:medium]`
* `[commerce-order:field_delivery_date:value:long]`

However, since your date seems to be a data range, you may have to enable the Entity API module and its "`Entity tokens`" sub-module to access the date values.

Also, be aware that `Entity tokens` replaces underscores (= "`_`") in the tokens names by dashes (= "`-`"), so in your case "`field_delivery_date`" becomes "`field-delivery-date`". And with that, this is how it should look like:

* `[commerce-order:field-delivery-date:value:short]`
* `[commerce-order:field-delivery-date:value:medium]`
* `[commerce-order:field-delivery-date:value:long]`

---
Tags: 7, rules, datetime, tokens
---


# Question
Title: When creating a new user with a order, how to email the new user login details
I am using Commerce Admin Order Advanced. It allows the following extras when creating an order in Drupal Commerce

* Search users by email or profile name before creating the order
* Select existing customer profiles before creating the order Validates
* Check a new customers email against existing customers to prevent duplicates
* Moves customer profiles to the top of the admin order form
* Provides copy address profile functionality on the admin order
interface (uses the same settings as the checkout pane for this
feature)

But it also will create a new user with an order, however there is no email sent to the new user with a one time link to login and set a password.

Does anyone know how this could be achieved?

# Answer
> 0 votes
I have achieved this using Rules

The Rule is as follows.

**Events** After updating an existing commerce order

**Conditions** Data value is empty - commerce-order:owner:last-login

**Actions** Send account e-mail

The reason why I have used this **Event** rather than 'After creating a new order' is to do with how this 'Commerce Admin Order Advanced' module works. You create the order before adding line items. And since I only need this email to be sent when a certain product type is created, this should suffice, hence I add the following **condition**

Order contains products of particular product types - Bespoke (an arbitrary product type)

But in order to prevent these emails being sent again should an admin update the order again, I have added the following extra **Condition**

Data comparison - commerce-order:created == commerce-order-unchanged:changed

---
Tags: commerce, rules
---


title: Output Custom Field in Drupal 8

text:
# Question
Title: Output Custom Field in Drupal 8
How can I output a custom field in Drupal 8 (Bootstrap theme)? Editing the field.html.twig file, if I have a custom field named field\_title I thought

```
{{content.field_title}}

```

Would display it, but it doesn't. I've also tried:

```
{{item.content['#field_title']}}

```

To no avail.

The only thing that's worked for me is:

```
{{items[0]}}

```

But that picks up the custom field by its index number, instead of its associative name in the array.

What am I doing wrong?

# Answer
{{ content.field\_title }}

This should work if you've got a field with that machine name. If you're trying to print the title, the current syntax is:

```
{{ label }}

```

An easier way to figure out if the variables that you are trying to use is actually usable is to download the Devel module and enable Kint. Then in your .html.twig template file, you can enter:

```
{{ kint(content.field_myCustomfield) }}

```

and you would get an array with all the available variables. If you don't want to install the devel module, you can just use: I would recommend Devel/kint, it makes everything prettier and easier

```
{{ dump() }}

```

You're only going to need to dig into the array if you're trying to do something really custom. Eg: I used the following code in one of my projects to dig down into a link field so that i can output the exact url into an A tag inorder to wrap an entire region in a link.

```
<a href="{{ content.field_card_custom_link[0]['#plain_text'] }}">

```

You can read more about outputting Variables in twig templates here: https://sqndr.github.io/d8-theming-guide/twig/twig-debug.html

and on drupal.org here: https://www.drupal.org/theme-guide/8
> 1 votes

# Answer
I found out my problem was I was editing the wrong template file. The file I needed to edit was:

```
/themes/bootstrap_subtheme/templates/node/node.html.twig

```

Once I added {{ content.field\_title }} there, it worked!
> 1 votes

---
Tags: entities, 8, theming
---


# Question
Title: How to add a confirm dialog to node add and edit forms?
**Note:** This has an accepted bounty, but no accepted answer because I still want to know how to add a node save confirm dialog using drupal code, not javascript. If you can write up a good answer on that I'll definitely accept it, and probably open and award you another bounty for your trouble.

Trying to implement part of the functionality mentioned in How can I add or remove links to nodes in a list depending on the values of some of the fields I would like to give users a warning, if the node they are submitting would end up being a stub.

I've been trying to implement this by following lots of examples related to confirm\_form, especially this one.

I'm think my issue must be that I'm starting from hook\_form\_alter, so in hook\_form\_alter it doesn't work very well to return an entirely different form (the confirm\_form). Realizing that hook\_form\_alter must be the wrong starting place though, doesn't help me know where I **should** start.

So here's what I need to be able to do:

When the user clicks 'Save' on a node edit form, I need to then evaluate whether the field values meet some criteria, and then provide the user a warning, that saving in the current state will have some effect on the way the node is displayed and give them an option to confirm or cancel.

Here is one of the many iterations of what I've tried:

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

    if (in_array(strstr($form_id, '_', TRUE), $GLOBALS['conf']['publication_types'])) { // only work on the publication forms
        if( !isset($form_state['storage']['submitted'] )) { // if the form hasn't previously been submitted
            $form['actions']['submit']['#submit'] = array('MYMODULE_node_form_submit');

            return $form;
        } else { // this is the confirmation step
            $form = _MYMODULE_build_confirm_form($form_state);
            return $form;
        }

    }
}

/**
 * invoke hook_node_validate
 */
function MYMODULE_node_validate($node, $form, &$form_state) {
    if (MYMODULE_is_stub($node)) {
        $form_state['storage']['stub'] = True;
        if ($form_state['triggering_element']['#value'] === 'Preview') {
//            dpm($form_state);
            drupal_set_message($message = 'If saved in this form, your publication will not have enough information to merit its own publication page.', $type = 'warning', $repeat = TRUE);
        }

    } else {
        $form_state['storage']['stub'] = False;
    }
}

function MYMODULE_node_form_submit($form, &$form_state) {

    if( !isset($form_state['storage']['submitted'] )) // this is the first time this has been submitted
    {
        // not confirmed yet.
//        $form_state['storage']['confirm'] = TRUE; // this will cause the form to be rebuilt, entering the confirm part of the form

        $form_state['storage']['submitted'] = TRUE;
        $form_state['rebuild'] = TRUE;
    }

    else // if we get here, confirm should have been clicked on the confirm form
    {
        node_form_submit($form, $form_state);

    }
}

function _MYMODULE_build_confirm_form(&$form_state) {
    $path = current_path();

    $form['processed'] = array(
        '#type' => 'hidden',
        '#value' => 'true'
    );
    return confirm_form($form, t('Do you really want to save a publication stub?'), $path, 'Confirm', 'Cancel');
}

```

This code doesn't work. When you click save gets through returning the form created by \_MYMODULE\_build\_confirm\_form, but in the processing afterwards, it seems clear that the system is expecting a node edit form and doesn't like what it is getting instead. The confirmation form is never displayed. I've tried using the node edit form as an input into confirm\_form and the actions of the node edit form show up instead of the confirm\_form buttons.

I'm at the end of my rope, how do I do this? I guess I need to override the menus so that I can run a callback function to determine which form should be displayed at node/%id%/edit before it gets to the stage of altering the form that has been specified? If so, how can I do that? I just need a solution that will use my existing MYMODULE\_is\_stub() feature to determine whether there needs to be a confirmation form, and then display the warning to the use and ask them to confirm or cancel. Please help!

# Answer
You can also add the Javascript inside a custom module, using your `hook_form_alter()` from the question as a base:

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

    if (in_array(strstr($form_id, '_', TRUE), $GLOBALS['conf']['publication_types'])) { // only work on the publication forms
        $form['#attached']['js'][] = drupal_get_path('module', 'MY_MODULE') . '/js/cool.js';
    }
}

```

In this version your cool.js file will go in the js folder in your module.

### cool.js

```
(function ($) {

    (function Forever(){ // we create a function called Forever

        $('html').ready(function(){

            $('.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders').hide();

            var characters = $('#edit-field-doc-abstract-und-0-value').val().length;
            var field1 = $('#edit-field-doc-website-und-0-url').val();
            var field2 = $('#edit-field-doc-pub-files-und-0-upload').val();

            if (characters < 300 || field1 == '' || field2 == '') {
                var submit_button = document.getElementById("edit-submit");
                try {
                    submit_button.type = 'newId';
                } catch(e) {

                }

                $('#edit-submit').attr("id","msg").css({"width": "34px"});
            } else {
                var fake_button = document.getElementById("msg");
                fake_button.type = 'submit';
                $('#msg').attr("id","edit-submit");
            }

        });

        setTimeout(Forever, 1);

    })();

})(jQuery);

(function ($) {

    $( document ).ready(function() {

        $("#msg").click(function(){

            var characters = $('#edit-field-doc-abstract-und-0-value').val().length;
            var field1 = $('#edit-field-doc-website-und-0-url').val();
            var field2 = $('#edit-field-doc-pub-files-und-0-upload').val();

            if (characters < 300) {
                var a = '<li>Abstract is less than 300 characters.</li>';
            }
            else { a = ''; }
            if (field1 == '') {
                var b = '<li>No website to go for more information.</li>';
            }
            else { b = ''; }
            if (field2 == '') {
                var c = '<li>No public files available for download.</li>';
            }
            else { c = ''; }

            div1 = $("<div class='blackbg'></div>").css({"background-color": "rgba(0, 0, 0, 0.5)", "width": "100%", "height": "100%", "position": "absolute", "z-index": "5", "left": "0"})
            div = $("<div class='msgbox'><b>In its current form, your publication doesn't contain enough information to merit its own publication page because:</b><br/>" + a + b + c + "<br/><br/><span class='yes'> Save </span><span class='no'> Edit </span></div>").css({"width": "350px", "height": "180px", "position": "fixed", "top": "0", "bottom": "0", "left": "0", "right": "0", "margin": "auto", "z-index": "10", "background-color": "#cfd2cc", "padding": "10px"});

            $("#page").prepend(div1).prepend(div);
            $('.yes').css({"background-color": "#89c640", "padding": "5px 10px 5px 10px", "font-weight": "bold", "cursor": "pointer"});
            $('.no').css({"background-color": "#d2cd4c", "padding": "5px 10px 5px 10px", "font-weight": "bold", "cursor": "pointer", "margin-left": "10px"});

            $(".yes").click(function(){
                var fake_button = document.getElementById("msg");
                fake_button.type = 'submit';
                $('#msg').attr("id","edit-submit");;
                $('#edit-submit')[0].click();

            });

            $(".no").click(function(){

                $('.blackbg').remove();
                $('.msgbox').remove();

            });

        });

    });

})(jQuery);

```

# Result

After clicking the `save` button you will get:

> **Caviat:** The character count of the abstract field will work only if you are **not** using CKEditor for the abstract field.
> 4 votes

# Answer
> When the user clicks 'Save' on a node edit form, I need to then evaluate whether the field values meet some criteria, and then provide the user a warning, that saving in the current state will have some effect on the way the node is displayed and give them an option to confirm or cancel.

You could get pretty close to what you're trying to do by simply (and only) using the Rules module. Some more details about this approach:

* Use Rules Event "***Before saving content***".
* Use as many Rules Conditions as needed, for any of your fields you want to validate.
* Use Rules Action "**Set a Drupal message\***" (of type "error") for any validations that fail.

However, be aware that using Rules Event "Before saving content", you do not prevent the node from being saved. So with a rule as described above, you only show an extra error message when saving the node. This is true for either creating new nodes, or for updating existing nodes. There are a few approaches to somehow get around that node being saved anyway, such as:

* **Delete** the node that just got created (or updated). Obviously this destroys all data entered before saving the node.
* **Unpublish** the node, which avoids that all data entered before saving the node are destroyed. And wait for something to happen afterwards to get the node published later on.

To continue with the approach to unpublish a node that fails a validation, have a look at this rule (in Rules export format):

```
{ "rules_field_validations_before_saving_nodes" : {
    "LABEL" : "Field validations before saving nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } },
      { "NOT data_is" : { "data" : [ "node:field-free-format-text" ], "value" : "ignore" } },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      }
    ],
    "DO" : [
      { "node_unpublish" : { "node" : [ "node" ] } },
      { "drupal_message" : {
          "message" : "The option list value = \u0022[node:field-optionlist]\u0022 is no longer allowed for nodes of content type \u0022[node:type]\u0022. Its status is automatically changed to \u003Cstrong\u003EUnpublished\u003C\/strong\u003E until an appropriate corrective action has been applied.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\r\nTo still use that value: (a) enter \u0022\u003Cstrong\u003Eignore\u003C\/strong\u003E\u0022 in the field \u0022Free Format Text\u0022 to overrule this validation, or use another allowed value for option list and (b) change the node status back to \u003Cstrong\u003EPublished\u003C\/strong\u003E again.",
          "type" : "error"
        }
      }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event is "After saving new content", but as a sample I've limited it to content type "article" only (omit or adapt that extra verification as needed).
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 3 possible values, like so:
    + A (=Advanced).
    + B (=Basic).
    + C (=Custom).
* As a sample, I decided to add these Rules Conditions (validations), in the order specified:
    + a validation to ensure that this rule only applies for nodes that have a field with machine name `field_optionlist`.
    + a validation about attempts to save a node where "The selected value" of `field_optionlist` equals `Custom`.
    + a validation to check if the text field with machine name `field_free_format_text` does **NOT** contain the exact value (case sensitive!) of `ignore`.
    + a validation to check that the user editing the node does **NOT** have a role with `rid` = 4 (change to whatever `rid` fits for your case), which could be like a content editor or so (so that users with special roles can still edit such nodes without being stuck by this rule).
* If all these Rules Conditions are satisfied, then the Rules Action will perform 2 actions:

+ mark the node as unpublished.
    + display a message which looks like so (feel free to change that to whatever you want):
> The option list value = "Custom" is no longer allowed for nodes of content type "article". Its status is automatically changed to Unpublished until an appropriate corrective action has been applied.
>
> To still use that value: (a) enter "ignore" in the field "Free Format Text" to overrule this validation, or use another allowed value for option list and (b) change the node status back to Published again.

If you want, you can use the Rules UI to import the above rule in your own site. But before doing so, make sure you have defined 2 similar fields (with machine names `field_optionlist` and `field_free_format_text`). As a variation, adapt the machine names to similar fields you already have (attention about `field-optionlist` versus `field_optionlist` though, same for the 2nd field, important!).

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

Voilà, the above solution depends on Rules, nothing but Rules. Read on if you're in for adding some additional modules (and further refine it all) ...

# Refinement

If you have a lot of validations to implement, you could simply add as many similar rules as you want/need, or you might want to add the Conditional Rules module to further enhance this approach. Using this extra module, you could consolidate multiple rules in a single one, which IMO makes these rules easier to maintain.

# Heading for the golden cradle

If you want to take this approach (using Rules) a step further, you should have a look at the Rules Forms Support module. Some details from its project page:

> Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.

Have a look at its Community Documentation to get started with it.
> 1 votes

# Answer
You can know which button has been clicked by the user with `$form_state['triggering_element']`

```
function MYMODULE_node_validate($node, $form, &$form_state) {
 if ($form_state['triggering_element']['#value'] === 'Preview') {
   if (MYMODULE_is_stub($node)) {
     dpm("This would be a stub");
   } else {
     dpm("This would not be a stub.");
   }
 }
}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Possible cause of the one time login link sent via e-mail to be broken?
edit: it appears to be a bug, reported here https://www.drupal.org/node/2329723

---

When I, as the Admin, add a new user and let Drupal notify him via mail, the one-time login link is broken:

```
http://www.exmaple.com///www.exmaple.com/user/reset/...

```

Any idea why Drupal would create such a link? There is no module which alters this mail or tokens.

# Answer
> 2 votes
There must be **something**, Drupal does not create broken links by default. Sadly, we can't debug your site for you. literally are not able to. See here \- URL is accessible as `[user:one-time-login-url]` token, so if nothing overrides default support for this token, it must be OK.

Inspect http://example.com/admin/config/people/account, Password recovery tab. By default it should look like this:

> \[user:name\],
>
> A request to reset the password for your account has been made at \[site:name\].
>
> You may now log in by clicking this link or copying and pasting it to your browser:
>
> \[user:one-time-login-url\]
>
> This link can only be used once to log in and will lead you to a page where you can set your password. It expires after one day and nothing will happen if it's not used.
>
> -- \[site:name\] team

If this token is alone in it's line, just like above, then you know something interferes with tokens. If it's not, then maybe some automatic HTML syntax correction kicked in, and messed up your layout? It is impossible to tell without actually debugging your site.

# Answer
> 2 votes
Its a long time since this question has been posed; but I faced the same problem yesterday, and searched for a solution on the net. There are a lot of technical details floating about, and the original poster has referenced the issue on the drupal.org site; though the remedies pertain to Drupal 6.

The solution for Drupal 7 is as follows:

goto administration \>\> configuration \>\> content authoring \>\> text formats

In 'text formats' there are editable options for 'full html', 'plain text', and 'filtered html'. Clicking on each, at the bottom, there's the sub-section 'Filter Settings' and over here you can change the 'Maximum link text length' from its default value of 72 char to anything you fancy 147, 255, 257, etc.

On my site, this resulted in a successful use of the one-time login link which was full and unbroken.

---
Tags: users, emails, navigation, tokens
---


title: What is the correct template filename?

text:
# Question
Title: What is the correct template filename?
I created a new content type using Drupal 8 with the machine name "reviews." I thought that by duplicating the original content type template file, node.html.twig, and renaming it node--reviews.html.twig, I would be able to override the original template.
However, any new change is not reflected when I open any of my review pages. I have already cleared the cache.

What is the correct way to override the default template file?

# Answer
node--reviews.html.twig is correct. In my current theme, I have node--staff.html.twig and node--video.html.twig; they work perfectly fine. It could be a cache issue or probably a spelling issue.
> 1 votes

---
Tags: 8
---


# Question
Title: How to pull twitter feed in content type?
I need to create content type(twitter content ) where i can pull twitter feeds so that i can use that content type for entity reference and print the twitter feeds.

Can any one please help or assist me how pull twitter feeds in custom content type?

# Answer
For this you have twitter block module in drupal 7 , but you want content type for this make node--twitterfeed.tpl.php template and put your api script like this

```
<a class="twitter-timeline" data-dnt="true" href="https://twitter.com/myapp" data-widget-id="123456789">Tweets by @InstaSnapShop</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

```

also check https://www.drupal.org/project/twitter\_block
> 0 votes

---
Tags: feeds, social-network
---


# Question
Title: Body field data not showing in View or Edit mode but exists in database
This is very similar to this question, except there the asker answered with a solution that is not relevant.

Scenario: made a copy of a D7 site in order to apply new theme. All content types etc seem to be fine except one. In that case the body data shows in db in field\_data\_body table but does not show in View or Edit mode. The node has not been saved since the issue was noticed. There is only one value of revision\_id for the node, and is same on both original and copy.

Body field is set to '1' but i believe that is correct, and is the same as on the site we duplicated.

The formats on original and live are both filtered\_html and again this is working for all other content types

There are not field based permission modules involved. Thoughts?

here is row from original:

```
entity_type    bundle  deleted entity_id   revision_id language    delta   body_value  body_summary    body_format
node    committee   0   534 2416    en  0   George ...  filtered_html
```

here is row from copy:

```
entity_type    bundle  deleted entity_id   revision_id language    delta   body_value  body_summary    body_format
node    committee   0   534 2416    en  0   George ...  filtered_html
```

# Answer
At this point, the issue seems to relate to language. Both live and dev have 'en' as the default language, but any new content on dev is being created as 'und', but as 'en' on live.

By way of a test, i copied the html from the db for one of the problem nodes, pasted it via Edit and saved, and the body then showed, but in the db it was flagged as being 'und'

BINGO - we had pulled a feature on to this site from another site. The other site had all fields set to 'not translatable' (field\_config table).

On this 'inherited' site, some of the fields eg Body had been set to translatable, even though there were no other languages on the site.

And yes, the feature overrode the 'translate' setting in the db (there is no where to see this in the UI).

Setting body to '1' in the db has restored body being displayed, and some sanity.
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: Points-based tasks: pledging and tracking
I am a member of a social organization and run its Drupal 7 website. We will be starting a campaign in a couple of weeks to challenge members to pledge to accomplish certain points-based tasks (not related to the website), and want to track the pledges, completions, and rolled-up sums.

1. There are roughly 100 tasks, with different point values and descriptions. Tasks are individual: more than one member can pledge to do a task.
2. A member would sign up on a per-user page to complete certain tasks. The sums of a member's pledged tasks and completed tasks should be displayed on the per-user page, and there should be a summary of all members' pledged and completed points and tasks available as well.
3. A member needs to be able to return to his/her page to update pledges and completions.

I believe I can do something for this with Webform, but it may be somewhat awkward. I'm not sure I can do the per-member sums and the rollups easily. User Points might help a bit, but it's not really oriented toward this. I could write a module as well, but I'm not sure I have time to do that. Suggestions for other modules or implementing this quickly are welcome.

# Answer
I ended up choosing to write my own module, after discovering that Views includes the capability to create a form based on a view. This is a feature of Views that is not that well known (at least by me). There's an excellent tutorial on how to use the feature: Programmatically Creating Forms with Views in Drupal 7. Input fields can be added to a view using this feature, and their values are submitted with the form.

Each task described in the original question can now be a node. To do the point totals I will embed the view in a page and add some code to compute the totals. Eventually I may Ajaxify the page.

A key feature here is storing per-user data associated with a node, which is not that common. My module uses its own db table to store this. The Flag module can also associate store per-user data per node, but it only stores a boolean and does not handle multi-valued Flags.

The module I'm working on is currently a sandbox project, Task Pledge.
> 0 votes

# Answer
There's a way to use Rules, Webform and Webform Rules together, by adding a number field with initial value 0 in your user fields. Every time user completes a task, validating a form submission, a value will be added to your field. That's the points field, which would be, in this case, unique. There is no sum in this case, but the field value will be automatically calculated by Rules.

Number field, your points field, should be available in your display, not in your user register form, with the right permissions.

That's what I'm thinking as a solution right now, if tasks are webforms. Not sure about awards or how to keep track of each completed task.

I hope that would get you started.
> 3 votes

# Answer
# Goals module

You may want to look at the Goals module (disclosure: I'm its maintainer) as a possible alternative. To start using it only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

Using the **Goals Extras** sub-module it integrates with the User Points module also: each goal can be configured (using the admin UI) to automatically grant an amount of user points to some user, after that user completed the goal.

Since the Goals module is entity based, it has out-of-the-box integrations with modules such as Views, Rules, Flag, etc.

# Requirements mapping

I can think of multiple ways to implement your requirements. For the sake of simplicity, here is one that IMO is the most straight forward implementation.

> 1) There are roughly 100 tasks, with different point values and descriptions. Tasks are individual: more than one member can pledge to do a task.

Create a content type, say **Task**, and add any custom fields you may need, eg for storing your point values and descriptions. For each of your "*roughly 100 tasks*" (referred to as ***Task-I*** below), create a node of type *Task*.

Use the Flag module to create these (non global) flags to be used for flagging nodes of type "*Task*":

* **Pledge**: to indicate a pledge by the flagging user, related to Task-I.
* **Complete**: to indicate the completion of Task-I by the flagging user.

Make sure to authorize all relevant users to use these flags (of course). That way, "*more than one member can pledge to do a task*" (as in your question).

Use the Goals module to configure 1 goal (referred to as ***Goal-I*** below) related to Task-I, which consists of only completing 1 thing (= a "task" as defined within the Goals module): flag the Task-I node. While configuring Goal-I, also indicate how many points (using the Userpoints module) should be granted automatically by Goals after a user completes Goal-I.

Use the Rules module to allow Goals to "*record the progress of the completion of the task related to Goal-I*". To do so, create a rule like so:

* Rules Event: A node is flagged (by flag "completed")
* Rules Condition: The node's `nid` corresponds to the `nid` of Task-I
* Rules Action: Mark the completion of the task related to Goal-I

A more advance way to use (configure) goals, is that there could be multiple tasks, and/or they might have to be repeated multiple times, and/or they might have to happen within a given timeframe, and/or they may require some amount of time to expire in between any 2 similar tasks, .... However, Goal-I was configured to only consist of 1 task. So after the above Rules Action is executed, Goals will automatically mark Goal-I as completed.

To avoid you'd have to create (roughly) 100 such rules (1 for each Goal-I), you could consolidated them all in a single rule, by transforming the Rules Action to performing an equivalent Rules Component (using node's `nid` as a parameter of the Rules Component), whereas you'd move the Rules Condition to that Rules Component also. Other alternative could be to use the Conditional Rules module

> 2) A member would sign up on a per-user page to complete certain tasks.

That's simply a standard user registration, where you want to ensure that such users have read access to all the Task-I nodes, and also that they are allowed to use both flags.

> The sums of a member's pledged tasks and completed tasks should be displayed on the per-user page,

Use the Views module to build the appropriate displays. Because of the modules mentioned above, they all integrate with Views very well (so creating such views should be straight forward).

> There should be a summary of all members' pledged and completed points and tasks available as well.

To create these summaries, use the Views module (also), and/or have a look at the views (block) that comes with Goals (title = "Your completed goals").

> 3) A member needs to be able to return to his/her page to update pledges and completions.

That's a matter of flagging and unflagging Task-I.

# More details

For more details about the Goals module, refer to my answer to "How to implement gamification in a Drupal site and award incentives?".
> 2 votes

---
Tags: 7, webforms, userpoints
---


title: Having problem with namespace

text:
# Question
Title: Having problem with namespace
I am writing a custom module, I am trying to use the `validateExtensions()` method defined from the Drupal core File module inside the FileItem.php file, in my own controller, using the following code.

```
use Drupal\file\Plugin\Field\FieldType\FileItem;

//Some other Use statement

class someclass extends FormBase {
  $instance = new FileItem();
  //Some Code
  '#element_validate' => array(array(get_class($instance), 'validateExtensions')),

```

It gives the following error:

> Recoverable fatal error: Argument 1 passed to Drupal\Core\Field\FieldItemBase::\__construct() must be an instance of Drupal\Core\TypedData\DataDefinitionInterface, none given

# Answer
> 1 votes
The answer is in the error message:

FieldItemBase has a constructor, and it waits a parameter (actually multiple), but it doesn't get any:

```
$instance = new FileItem();

```

Even though the constructor function can't be find in FileItem, in this case you have to investigate which parent has it. You will find out that "FieldItemBase" has it. I don't know why you want to use this like this, but things like Controllers, Plugins, Services were mean to be to get instantiated by Drupal.

---
Tags: 8
---


# Question
Title: Webform get all submission for a node by date
I am using webform\_get\_submissions to get all submissions, I have a requirements to get only one day back submissions.

Is there any way to get this results?

# Answer
It seems it's not possible directly. See webform\_get\_submissions date range filter issue.

From taht issue:

> We now have built-in range functionality in #1237660: Add date range or "last X submissions" to CSV/Excel download. That patch just uses the existing ability of webform\_get\_submissions() to filter by SIDs, which would probably work in your situation too as long as you can retrieve a list of SIDs by date.

So you have to build a query to retrieve a list of SID's bty date and then pass it to webform\_get\_submissions.
> 0 votes

---
Tags: webforms
---


# Question
Title: Content Filter based on Heirarchical Taxonomies
I have one taxonomy named "Project Parameters" with hierarchical select and another taxonomy names "Project Sub Parameters" with hierarchical select.

I Want to filter the content with those taxonomies like on selection of Project parameter display its sub parameters and click on sub parameters with ajax call i need content filter

I Had created view and with contextual filter i achieve that but that load the page. I want to do same functionality with ajax only, No page reload.

Is it Possible? Please Help Me.. I am stuck since last 2 days.

# Answer
Create views for

* Project parameters
* Project sub parameters with contexual filter of project parameter taxonomy id with filter criteria
* Content view with contexual filter of project sub parameters taxonomy id.

After Create these views you can call ajax api and pass those conexutal filter on ajax for particular view like,

```
$view = views_get_view('viewname'); //viewname is the view machine name
$view->set_display("block_1"); //block_1 is the view display name
$view->set_arguments($tid); //$tid is the argument to pass
$view->pre_execute();
$view->execute();
$content = $view->render();

```

I got the success by this way.

Hope this answer help somebody.
> 0 votes

---
Tags: ajax, nodes, views
---


# Question
Title: Drupal 8 - "Level up" link in taxonomy term view
this is my first question on Drupal Answers so... nice to meet you :)

On Drupal 8 site I've replaced default taxonomy term page for one of my vocabularies with composition of view and block. View shows a table with nodes tagged with taxonomy term from the URL. Block contains a view with taxonomy term's children. These two components together have a feeling of files explorer application (like Finder, Explorer or Nautilus). But one thing is missing - a link to the parent taxonomy term. Name it "level up" or sth. I've tried adding something to the footer of block's view but with no results. And didn't find anything on the internet. Do you know if there is any possibility of doing this?

PS: I know that there is breadcrumb on every page, but this is not what I'm looking for.

# Answer
> 2 votes
Personally I would just write a custom code:

* You will need to define a custom block
* And you will also need to get the parameter from the URL.
* You will need the "database" service (select) in your code, to query the parent term (if there is any).

---
Tags: views, 8, taxonomy-terms
---


# Question
Title: How do I pass the value of a PHP variable?
I have the following code in Drupal 6.

```
drupal_add_js(array(
  'take_control_fb' => array(
      //          'pubKey' => variable_get('take_control_public_key', ''),
      'dataUrl' => base_path() . 'admin/build/take_control/fb/getfiles',
      'appUrl' => take_control_app_url(),
      'appDir' => $appDir,
      'extPath' => $extpath,
      'zipMimes' => take_control_zip_mimes(),
      'dirSeparator' => DIRECTORY_SEPARATOR,
      'validationString' => $validationString,
      'validationToken' => drupal_get_token($validationString),
      'curUserId' => fileowner(file_directory_path()))), 'setting');

```

I need to convert this, since `drupal_add_js()` is removed from Drupal 8. I can't use this to pass PHP variables to modulename.js file. How can I pass the PHP variable to JavaScript code?

# Answer
In Drupal 8 `drupal_add_css()`, `drupal_add_js()` and `drupal_add_library()` have been removed, and we are supposed to use #attached.

```
$page['#attached']['library'][] = 'fluffiness/cuddly-slider';
$page['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

```

More details about how JavaScript can be added in Drupal 8 can be found in https://www.drupal.org/theme-guide/8/assets#configurable-javascript.
> 3 votes

# Answer
In your case, you simply use the following code.

```
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');

$form['#attached']['drupalSettings']['take_control_fb'] = [
  'dataUrl' => base_path() . 'admin/build/take_control/fb/getfiles',
  'appUrl' => take_control_app_url(),
  'appDir' => $appDir,
  'extPath' => $extpath,
  'zipMimes' => take_control_zip_mimes(),
  'dirSeparator' => DIRECTORY_SEPARATOR,
  'validationString' => $validationString,
  'validationToken' => \Drupal::csrfToken()->get(),
  'curUserId' => fileowner($stream_wrapper_manager->getViaScheme(file_default_scheme())->getDirectoryPath())
];

```

Notice that I also replaced `drupal_get_token()`, which has been replaced from a service, and `file_directory_path()`, which doesn't exist since Drupal 7.

I am assuming your code is used in a form builder; if you use it in another context, replace `$form` with the variable containing the render array.
> 0 votes

---
Tags: 8, javascript
---


# Question
Title: Displaying parse errors in module development on the browser
I am currently trying to learn Drupal Module development.

As one might guess, many errors get created in the process. But, all i can see is WSOD on the browser.

For the same errors, most of the Module development videos on youtube show display the errors on the browser itself in an easy to understand format with specific details on the parse error(attached image).  I have tried some solutions on configuring on index.php, but in vain. Also, I can see the errors on Drush, but that doesn't satiate

Could anyone please tell me on how i can have this in my environment?

I'm running Drupal 7 on Windows 8 using Bitnami WAMP Stack.

# Answer
> 0 votes
You have to enable error displaying in PHP. There are several ways to do it, but one of the most straightforward is to enable them in the settings.php of your project.

Just add those lines to the file:

```
error_reporting(E_ALL);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

Meaning:

1. Instruct PHP to notify all errors.
2. Instructs Drupal to show all errors (using a drupal\_set\_message).
3. Instruct PHP to display errors instead of show a blank page.
4. Instruct PHP to display errors even those in the startup phase.

Also, as Clive comments, if you enable XDebug error reporting is more verbose. The screenshot you show includes XDdebug error backtrace.

# Answer
> 0 votes
Just add below lines in your site's settings.php

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

More details you can find from Show all errors while developing

---
Tags: 7
---


title: Block Plugin Derivatives Discovery

text:
# Question
Title: Block Plugin Derivatives Discovery
I need some help with my code. I am creating blocks dynamically using the plugin derivatives. I store some form data in a database table, then I display it in each block separately, depending on it's derivative id. My issue is: while, I do obtain all the individual blocks on a full clear cache, in the "Place Block" section, it's not there when I submit the form, basically, I would like the form submit function to trigger the derivative creation and it's discovery. Any suggestions appreciated.

Here's my Plugin Derivative code:

```
<?php

namespace Drupal\simpleads\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class SimpleAdsBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $query = \Drupal::database()
            ->select('simpleads_blocks', 'sb')
            ->fields('sb');
        $results = $query->execute()->fetchAll();

    foreach ($results as $result) {
        $this->derivatives[$result->bid] = $base_plugin_definition;
        $this->derivatives[$result->bid]['admin_label'] = $result->name;
    }

    return $this->derivatives;
    }
}

```

# Answer
Copied from BlockContent::postSave():

```
// Invalidate the block cache to update custom block-based derivatives.
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();

```
> 6 votes

---
Tags: 8, plugins
---


# Question
Title: How to show the number of user points within the user who posted a comment?
I use the User Points module. Despite of my searches, I didn't find answer to this question:

> **In the user profile of a comment, how to show the number of user points?**

For example to show the number of points below the picture of the user who posted a comment.

Any suggestions?

# Answer
> 0 votes
User Points

> * Services integration: allowing retrieving and updating points on your site using web services.
> * Rules integration
> * Views integration
> * A block displaying the number of points a user has gained
> * A block displays the top users who earned points
> * A status message telling the user how many points were earned/lost and their total points
> * A detailed point total report for each individual user
> * A point total report for all users

Profile2

> * The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module
> by default.
> * Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated
> permissions for those.
> * Optionally, profile forms are shown during user account registration.
> * Similar to the deprecated core profile module, fields may be configured to be private - thus visible only to the profile owner and administrators.
> * By default the UI behaves similar to the deprecated core profile module, thus showing each profile type in each own tab below
> user//edit. Via the included "Profile pages" module profiles can
> be viewed and edited at their own page and get their own menu link,
> e.g. "My profile".
> * Thanks to the foundational entity API the module integrates well with Rules as well as Features - thus profile types and the associated fields can be exported into feature modules. Once the Entity tokens module (part of the Entity API) is turned on, there are also token replacements available.
> * You may use Views and/or the Search API to provide listings or searches for profiles

# Answer
> 0 votes
Your question is similar to what is done in the Answers module (which comes with the `Answers Userpoints` sub-module that integrates with the User Points module). The newest 7.x-4.0 version of Answers also comes with the (new) `Answers Theme` sub-module, which you can see at work in this example question. Note the "***points***" that are shown below each author (user) to the left of a question or answer, which is similar to the "*user profile of a comment*" in your question.

These points are shown via what you can see in this template file (used for nodes of type "Question"), the template used for nodes of type "Answer" is similar. Both templates are part of the `Answers Theme` sub-module. More specifically both templates have a line that looks like so:

```
<?php print userpoints_get_current_points($node->uid); print ' ' . t('points'); ?>

```

So to complete the answer to your question, this is how you can get it to work:

* Use a template related to the comments where you want to show the user points.
* Add a line similar to the code above, using `userpoints_get_current_points` and replace `$node->uid` in it by the user id of the user who posted the comment.
* Refer to the documentation about userpoints\_get\_current\_points if you need more details.

Disclosure: I'm a co-maintainer of Answers.

---
Tags: users, userpoints
---


# Question
Title: Disabled item in menu in menu_tree_all_data
I want to fetch all menu item list from specified menu list, I can fetch all of them with `menu_tree_all_data`, It return all item of `menu` and when I looked in in result I don't see `enabled` property my sample code

```
  $menuItems=menu_tree_all_data('menu-footer-menu');
  dpm($menuItems);

```

(after that I put this in `foreach` statement and print them, but I want exclude disabled menu items)

My question is how can I find out that the menu item is disabled ?

# Answer
> 4 votes
'hidden' key in the array returned, will tell you if the menu links is enabled or disabled. For all disabled menu links hidden will be '1'.

# Answer
> 0 votes
I am trying to remove some menu items from the admin menu (which don't have any value in "title" field. We can have any other criteria to identify our target menus) as below (in theme\_preprocess\_page()).

**Please note:**

1. We are not supposed to make any changes in the already defined access configurations for those menus. We are not supposed to make any changes in the menu path.
2. Here, in this use case, the menus were showing in admin-menu list as those started with "admin/". Example: "admin/entity\_ref\_search/%".
3. We need to clear cache after adding this code (as changes are related with menu).

```

$menu_tree = menu_tree_all_data('management');
foreach ($menu_tree as $key => $menuItem) { // Runs once
  if (isset($menuItem['below']) && is_array($menuItem['below']) && !empty($menuItem['below'])) {
    foreach ($menuItem['below'] as $menu_link => $value) {
      if ($value['link']['title'] == '') {
          $value['link']['hidden'] = 1;
          menu_link_save($value['link']);
      }
    }
  }
}

```

---
Tags: routes
---


# Question
Title: How to show year/months in archive block?
I want to create a archive block for blogs. I tried by using default archive view block, bot that structure is not suitable for my requirement. I need years to display and when I click on years, months should display like below:

```
           2016
             Jan 2016
             Feb 2016
           2015
             Jan 2015
             Jan 2015
           2014
           2013
           2012

```

In the same way after a click on year/month, related data should get display.

# Answer
Use the Views module, then add the creation date of the blog to your views fields; it will be displayed.

* Create a new view that shows only nodes whose content type is *blog*
* Select the format you want
* In the fields section, add the title and other fields you want to display
* Add the date field
* Save it; you should get what you wanted
> 1 votes

---
Tags: views, blocks
---


title: Setting import to run every 15 minutes

text:
# Question
Title: Setting import to run every 15 minutes
I am using Drupal 7.43, and I want to read my data from an external database every 15 minutes. My site is hosted on an Ubuntu server.

I am using Feeds importer with SQL parser. From import/feed\_from\_feed\_db, all data is correctly imported; so, the importer runs correctly.

How can I set the feed importer to automatically run every 15 minutes?

# Answer
> 1 votes
For periodic import select `As often as possible`.

Then use Ultimate Cron and make the Feeds & Scheduler cron run every 15 minutes only, this way cron will not do other tasks that you don't need to do every 15 min.

# Answer
> 0 votes
You can use Rules or triggers to make the feed importer run with the cron task

---
Tags: 7, feeds, cron
---


# Question
Title: How to implement admin verification for selected user profile fields?
After the user fills the registration form, if the profile is appropriate, the administrator user approves it, and the profile goes live; if it is not appropriate, the administrator user will reject it, but the user still has the chance to proceed with changing the picture and content until it is appropriate. The administrator user will then review for the second time to be sure everything is fine, and the profile will go live.

How can I achieve this?

# Answer
> 1 votes
### Step 1: Create a designated role

Create a role like (say) "`Member`", and use this role within Drupal's Permission system to disallow access to anything on your website for users who do not (yet) have access to this "`Member`" role. Make sure that for profiles that did not go live yet, you do not grant access to this role.

### Step 2: Activate user accounts after registration

When a new registration request arrives, check if it satisfies some minimal requirements to have the account's status be changed to "active" (you don't want to do so for e.g. spammers).

If the request does satisfy your requirements, the administrator just grants the `Member` role (and is finished with this registration request review).

But if it doesn't satisfy your requirements yet, then the administrator should NOT (repeat NOT) grant the designated role from Step 1. To allow the admin to indicate "I reject", use the Flag module so that the admin can flag such user. Since flags are entities (fieldable), you could also add a (text?) field to have the admin add some kind of "reject reasons". Such flagging could then result in sending an eMail to the registered (not approved yet) user to ask for appropriate changes by the registered user.

### Step 3: Wait for the user to apply account updates

After the user (who does not yet have the "`Member`" role applied new updates to relevant profile fields, send an appropriate eMail to the administrator to request a new profile review. To do so, use the Rules module with a custom rule that looks similar to this one (in Rules export format):

```
{ "rules_notify_admin_about_selected_profile_updates" : {
    "LABEL" : "Notify admin about selected profile updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : { "data" : [ "account:uid" ], "value" : [ "site:current-user:uid" ] } },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-to-be-approved" ],
          "value" : [ "account:field-to-be-approved" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Thanks for updating your account, the site administrator will soon review your updates." } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Updated profile needs your review",
          "message" : "Please review the updates to the profile of user [account:name], located at [account:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Some more details about the magic in the above rule (use the Rules UI to import it in your own site, after you applied relevant changes like the field name):

* **Rules Event**: After updating an account
* **Rules Conditions**:
    + An entity of type "user" is updated.
    + The account being updated is from the currently logged in user.
    + The user does NOT have the role with ID=4 (which is assumed to match the `Member` role, adapt this ID to fit your needs).
    + The actual profile field is "some" field you want to monitor / review / approve. In this case I used a field with machine name `field_to_be_approved` (adapt to fit your own needs, and add similar conditions if you want to check other fields also).
* **Rules Actions**:
    + Show an informational message to the user who performed these updates (though only if all Rules Conditions are satisfied).
    + Send an appropriate eMail to the site admin (adapt the content of it to fit your needs).

### Step 4:

You may want to add an extra Rules Action in the previous step to unflag the user again. So that the administrator can fag the user again if after updating the profile the administrator still rejects (by repeating from Step 2). However I recommend to NOT add such extra step, so that the administrator can still see the "reject reason" (from Step 2). And if a 2nd reject is needed, all it takes for the admin is to (a) unflag the user and (b) right away flags the user again, but now possibly with a new reject reason. True, an extra click for the administrator, but the advantage is that the prior reject reason (if used) did not automatically get deleted.

At the point where the updates are OK, just have your admin grant access to this role for any registered user as soon as "the profile goes live". A possible way to further automate this is to create another rule which automagically grants the `Member` role after the admin "unflags" the user (= removes the flag set in Step 2). If you wonder how to do so, use this link ...

### Bonus:

The above approach, with some minor variations, could also be used to catch users who after their account got verified, update their profiles in a way that would not have been allowed when they first registered.

---
Tags: 7, users
---


# Question
Title: How to sell digital goods (redeem codes) using Drupal?
I'm considering Drupal as a platform for a web project I'm working on. I'm looking for a way to sell redeem codes using UberCart, Drupal Commerce or some other module.

The client will be able to buy a single code or several codes and receive it/them by email.

Redeem code format : `201504[variable_value]`, eg : `201504846, 201504965, 201504347...`

Any ideas on how to manage this? Will every code be considered as a product (unique SKU)?

I need to be able to import the codes into the Drupal store. How will I be able to achieve this? I buy the codes in bulk and get them in an Excel spreadsheet.

# Answer
> 4 votes
There's a UC solution called UC Product Keys out there for this particular use case, but you're better off avoiding it; the project has no 7.x version and is minimally maintained.

The Drupal Commerce equivalent is Commerce Product Key...

> This module lets sites implementing the Commerce module, attach product keys to orders. Product keys / Vouchers are strings of text that are used to unlock or activate a piece of software.
>
> Right now we have an entity that can be attached to a product and then assigned via a rule to a product once it has been bought. The required actions and rules events are fleshed out and simply require the wiring up of the rules to meet you scenario.

It probably won't do everything you need (e.g. import license keys), but it should be a good starting point to build your own product key solution off of.

# Answer
> 0 votes
I would **Not** use Drupal Commerce (as in your question) for this. But instead use an approach as detailed below.

# Part 1 - Create nodes

Starting from your spreadsheet, you should be able to transform them (easily) in a CSV file. Use something like the Feeds module to automatically create a single node for each of your redeem codes you want to be able to sell.

# Part 2 - Use Light Shop

Use the Light Shop module, a simple and lightweight e-commerce solution. Here is a quote from its project page:

> * Session-stored basket.
> * Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
> * Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
> * Orders history. For each order will be created a separate node.
> * There is no dependence on other modules.
> * Full support for working with anonymous users
> * Integration with Views.

The ***Node based shopping*** could be a perfect fit for your nodes created as described in **Part 1**.

---
Tags: commerce
---


# Question
Title: How can an entity reference field be displayed as a select list that shows the selected entity?
# The Problem

I have a couple of entity reference fields that references a hierarchy of nodes. For the sake of simplicity let's use just the top level example **Video Game -\> Video Game Release**

So when I look at the video game "Assassin's Creed 2" I see two releases "Assassin's Creed 2" and "Assassin's Creed Ezio Trilogy".

Background info that isn't necessarily important to the question:

> ! The reason for the entity reference is on "Assassin's Creed Brotherhood" I would also have two releases "Assassin's Creed Brotherhood" and "Assassin's Creed Ezio Trilogy".
>
> * Assassin's Creed 2 (Node: game, ID: 1)
>     + Assassin's Creed 2 (Node: release, ID: 2)
>     + Assassin's Creed Ezio Trilogy (Node: release, ID: 3)
> * Assassin's Creed Brotherhood (Node: game, ID: 4)
>     + Assassin's Creed Brotherhood (node: release, ID: 5)
>     + Assassin's Creed Ezio Trilogy (Node: release, ID: 3)

When I view the node "Assasin's Creed 2" I'm currently seeing both releases one after the other. I styled these using display suite and they look fine. However I want to display only one of them at a time with a tab, select list, or something of the like to allow me to switch between them.

# My thoughts

* I was unable to find a module that could perform this but I feel one may exist.
* I could use a simple jquery tab ajax but wasn't sure if their was already a drupal way to do this.
* Perhaps I could use exposed views and a views embed field to show all the referenced nodes but then the performance would suffer significantly.

# The question

**How do I display an entity reference field as tabbed or select list content?** Preferably without the performance drop of an embedded view.

# Answer
> 0 votes
You have 2 relatively simple options without creating your own module and field display code (in a module).

1. use Views to generate the select lists you want. You can do this for example with a ctools dropdown or jumpto displays. While you're using a view you can always set Views to cache the results of your view so its not cumbersome after the 1st page load for all other visitors. You can even define views and attach them to your node if you want with field\_views\_field module.
2. Use Display Suite on your site and create a Custom Field in DS for any fields you want custom output for, like your select list. Then in the PHP area of the custom field you can access the currently loaded `$entity` fields and generate whatever HTML you want for your field output. You would then hide the default field display of your field, and show your custom DS created field for your content type.

I'm about to do (2) above with a slideshow content type where per-slide the content editor can select the text foreground and background color using the field\_color module which would best match an uploaded image to the Node. Then in DS I will make a custom "slide\_text" dyanamic field that examines the color values and basically outputs:

```
<?php
// This is pseudocode and untested.
$wrapper = entity_metadata_wrapper('node' $entity);
$text_color = $wrapper->field_foreground_color->value();
$bg_color = $wrapper->field_background_color->value();
$text = $wrapper->field_slide_text->value();
echo <<<EOFHTML
<span class="ds-slide-content-field"
      style="color: $text_color;
             background-color: $bg_color">
    $text
</span">
EOFHTML;
?>

```

---
Tags: entities, display-suite
---


# Question
Title: add product with special price to cart drupal7
I used the following code to implement "add to cart" in my tpl.php file, and it works fine:

```
$product=commerce_product_load($node->field_product['und'][0]['product_id']);
$line_item = commerce_product_line_item_new($product,1);
$line_item->data['context']['product_ids'] = array($product->product_id);
$show_quantity = TRUE;

$form = drupal_get_form('commerce_cart_add_to_cart_form', $line_item,$show_quantity);
print render($form);

```

Right now, it can only use its original price. However, I want to add this product with a special price to the cart and use this special price to checkout.

I have already created a "Price" field named "field\_special\_price", and if I use `print_r($product)`, I can see its value and can use the value by `$product->field_special_price['und'][0]['amount']`

# Answer
> 1 votes
You need to use a rule that acts on the "Calculating the sales price of an item" and then set the price using that rule. Here is an example: https://drupalcommerce.org/user-guide/sell-price-calculation

# Answer
> 0 votes
Thank you @nvahalik!

Based on @nvahalik answer, I create a new rule. I created a new field because I have so many different products and each product has its own special price. Here are the steps:

1. **create a new price field named "field\_special\_price"**
2. **create a new pricing rule** (**event:Calculating the sell price of a product**) (you can find the steps in the link from @nvahalik answer)
3. **Add first condition** : **Entity has Field** (the image is my first condition)
4. **Add second condition: Entity has Field**

Entity-Data selector: "commerce-line-item:commerce-product"(based on first condition)

Field-Value: "field\_special\_price"

5.**Add third condition: Data value is empty**

Data to check: commerce-line-item:commerce-product:field\_special\_price(based on second condition)

Select "Negate"

6. **Add first action:Calculate a value**

Hint: Mix "commerce-line-item:commerce-product:field\_special\_price:amount" & "commerce-line-item:commerce-product:commerce-price:amount"

7. **Add second action: Set the unit price to a specific amount**

Hint: Amount- Data selector: "(the variable name from first action)"

---
Tags: 7, commerce
---


# Question
Title: What is the correct way to update existing module's rules programmatically?
I want to provide an update for my custom module, which also has some rules provided via `hook_default_rules_configuration`.

Now, how can I update those existing rules? Can I re-import them? Override them somehow? I cant find anything about this in the documentary or an respective hook.

There seems to be a hook to respond to rules being updated, so I guess there must be a way to provide updates for custom rules...

At first I thought it was hook\_default\_rules\_configuration\_alter but it doesnt seem to work as expected since I just want to import JSON.

For instance, using views I can simply load all `.inc` files and save them via `views_save_view` like in this question \- isnt there a similar way in rules?

# Answer
> 7 votes
You can export the rules configuration via the Rules UI and then implement hook\_default\_rules\_configuration\_alter() like this:

```
/**
 * Implements hook_default_rules_configuration_alter().
 */
function MODULENAME_default_rules_configuration_alter(&$data) {
  if (isset($data['commerce_cart_add_to_cart_message'])) {
    $data['commerce_cart_add_to_cart_message'] = entity_import('rules_config', '{ "commerce_cart_add_to_cart_message" : {
        "LABEL" : "Display an Add to Cart message",
        "PLUGIN" : "reaction rule",
        "OWNER" : "rules",
        "TAGS" : [ "Commerce Cart" ],
        "REQUIRES" : [ "rules", "commerce_cart" ],
        "ON" : { "commerce_cart_product_add" : [] },
        "IF" : [
          { "data_is" : { "data" : [ "commerce-order:commerce-nocart" ], "value" : "0" } }
        ],
        "DO" : [
          { "commerce_cart_add_to_cart_message" : { "commerce_product" : [ "commerce-product" ] } }
        ]
      }
    }');
  }
}

```

Just change the instances of `$data['commerce_cart_add_to_cart_message']` to use your rule machine name and replace the export string with your own.

You can also use rules\_import() instead of entity\_import(). Either is acceptable.

Since the rules module loads default rules from code into the database and from then on loads them from the database, it won't immediately pick up your override. To make it do so navigate to the Rules UI and revert the rule. It will revert back to the default code, which will be your override.

To programmatically revert a rule you can do this (again replacing the rule machine name):

```
if ($rules_config = rules_config_load('commerce_cart_add_to_cart_message')) {
  $rules_config->delete();
}

```

An example usage of that may be to do it during an update function for a custom module.

It may seem wring to be deleting it but delete and revert are equivalent for rules that are provided by code because delete means delete from the database. If this was a rule created via the UI then it would be gone, however a rule from code will just delete from the DB and then read in again from the code.

Unfortunately there are currently only drush commands for enable/disable of rules. There is a feature request for a delete/revert command at https://www.drupal.org/node/2507187

# Answer
> 2 votes
To update module's rules programmatically you can load them and change them. Example of removing single action:

```
$rule = rules_config_load("some_rule");
foreach ($rule->actions() as $action) {
  if (strpos($action->getPluginName(), 'drupal_message') !== FALSE) {
    $action->delete();
  }
}
$rule->save();

```

If it's one time change, add it into hook\_update.

See: RulesPlugin for API.

---
Tags: 7, rules, updating, importing-exporting
---