# Question
Title: Alter element_info and troubleshoot changed elements
Ubercart defines the following `uc_price` type in `uc_store_element_info`:

```
$types['uc_price'] = array(
  '#input' => TRUE,
  '#size' => 15,
  '#maxlength' => 15,
  '#autocomplete_path' => FALSE,
  '#process' => array('ajax_process_form'),
  '#element_validate' => array('uc_store_validate_number'),
  '#theme' => 'textfield',
  '#theme_wrappers' => array('form_element'),
  '#field_prefix' => $sign_flag ? '' : $currency_sign,
  '#field_suffix' => $sign_flag ? $currency_sign : '',
  '#allow_negative' => FALSE,
  '#empty_zero' => TRUE,
);

```

Assume I want to allow negative prices by setting `#allow_negative` to TRUE. (Maybe this is a bad idea, but play along.) Maybe I will need to replace the `#element_validate` array with a custom function as well.

From reading the API documentation here: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_element\_info\_alter/7.x it looks as if making a custom module and implementing `hook_element_info_alter` should let me do this. I made a module called `customcode` and implemented the following function:

```
function customcode_element_info_alter(&$type) {
  drupal_set_message('Altering uc_price');
  if (isset($type['uc_price'])) {
    $type['uc_price']['#allow_negative'] = TRUE;
  }
} /* end hook_element_info_alter */

```

but this does not work. Maybe this does not work for obvious reasons but I am pretty confused, and web searching (on this site and elsewhere) is not clearing up my confusion. I could easily believe I am specifying the array element incorrectly, but without troubleshooting information it's difficult to figure out what is going on.

Here are some questions:

* How do I see the value of the `$type` array? When troubleshooting other forms I have used `print_var` or `dpm`, but those do not do anything here. I do not understand at what point this code is executed and how to display output from it. The `drupal_set_message` displays nothing.
* Is `hook_element_info_alter` the way I want to modify this element? If not, what approach should I take? I obviously do not want to hack the Ubercart module unless there is no other choice.
* If so, is creating the function with the name I have chosen (`customcode_element_info_alter`) correct? When I use `hook_form_alter` I need to include the original form ID in the name. I do not understand how this hook knows enough to alter the data in `uc_store_element_info`.

Thanks for any help you can offer.

# Answer
> 0 votes
The underlying problem was caching. I thought I had cleared cache, but apparently not.

Here are answers to my questions:

As suggested above, use `watchdog()` to see the value of the `$type` array. Here is a (probably dangerous) snippet:

```
watchdog('customcode', 'uc_price after mod: <pre>'.
print_r($type['uc_price'], TRUE) . '</pre>');

```

`hook_element_info_alter` is how I want to modify the element, and the function should replace `hook` with the name of the custom module.

It looks as if all `hook_element_info_alter` hooks are called after all type elements are defined somehow, but I am still fuzzy on this.

I am not certain when hook\_element\_info\_alter is called, but it appears to be called early (there is no need to visit the form in question) and it appears to be cached for a long time.

My strategy of setting `#allow_negative` to `TRUE` was in fact the right approach, because the validation function `uc_store_validate_number` takes this into account. Otherwise I would have had to unset the validation function and replace it with a custom one.

---
Tags: 7, forms, ubercart
---


title: How to add the sum in a Webform Report?

text:
# Question
Title: How to add the sum in a Webform Report?
I would like to have the total sum of a number field in a report created with Webform Report.

How can I get the total sum of that column table?

# Answer
> 0 votes
Instead of using the Webform Report module, you can use Views and Views Aggregator Plus to display the submission data. You can use the aggregation function ***sum*** for the selected fields (to aggregate your webform submission results tables).

Credits: Waluyo Adi Siswanto.

---
Tags: webforms, log-messages
---


title: Theming forms. Form-element

text:
# Question
Title: Theming forms. Form-element
Please, help. Is it possible implement different templates for form-element.html.twig? For form 'user-form' one template, and for other forms second template.

# Answer
As you requested, this is an example how I did using field names.

**In your .theme file:**

```
function THEME_preprocess_form_element(&$variables) {
  //This is a list of fields in contact form
  $showAfter = array('name', 'mail', 'subject[0][value]', 'message[0][value]');
  if (in_array($variables['name'], $showAfter)) {
    //If is one, I change here how to display instead using different twig file
    $variables['element']['#title_display'] = 'after';
    $variables['label_display'] = 'after';
  }
}

```

Now, if you want use different twig file for each field name use this...

**.theme file**

```
function THEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#name'])) {
    //Name can be a string like this, 'subject[0][value]'.
    //When this happen, I just get 'subject'.
    $suggestions[] = 'form_element__' . explode("[", $variables['element']['#name'])[0];
  }
}

```

Then in your HTML appear something like this:

```
<!-- FILE NAME SUGGESTIONS:
   * form-element--subject.html.twig
   x form-element.html.twig
-->

```

**Note:**
The main problem is how you get form\_id in `preprocess` or `theme_suggestions` (form\_element Hook), I didn't find a way to get this information.
> 2 votes

# Answer
I found out another way to solve my problem. In form\_alter function i added this code: $form\['custom\_field'\]\['theme\_wrapper'\] = 'form-element-custom.html.twig'; And, its help me.
> 0 votes

---
Tags: theming, forms, 8
---


# Question
Title: Allow Role to change only Moderation State of Content Type without possibility to edit content fields
The system we are building has a role Publisher. It's task is to change Moderation State of a content (news content\_type) without having a possibility to edit an actual content.

In short, the user in role Publisher sees all News created by other users and only has permission to change its state.

In short, how do I allow a user in a role to edit only 1 field and block the rest?

# Answer
> how do I allow a user in a role to edit only 1 field and block the rest?

The standard solution is the Field Permissions module:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

It provides you with a role-based UI like so:
> 0 votes

---
Tags: 7, workbench
---


# Question
Title: How to create a dynamic menu block system with 3-tier system?
I want to create a complex menu system as described in the following image:

It looks complex but logically it is simple.

1. I want to create a block containing Menu items.
2. **Brief description of image for better understanding:** There is a Standard main-menu as with all sites, under that, block is there as scenario-1 and scenario-2, I have just make two copy for better understanding. That block I want to keep in first sidebar. Block has three tier, it is just like M-item(main-menu) -\> Its sub-menu items -\> Its sub-menu items -\> Its sub-menu items (So, it is like **Parent -\> child -\> child -\> child**)
3. Logic: Hence, when user clicks M-item-1(parent, from main-menu) -\> The block's first tier should show that main-menu item and its sub menu under that. Now suppose user clicks M-item-1-B(tier-1 item) hence in the tier-2 that item should display its sub-menu and M-item-1-B should be as title of tier-2 and same way if from tier-2 if user clicks M-item-1-B-b, its sub-menu should display as in the Tier-3. In short I want to display - 3-tier of menu items in one block only. Hence my purpose is to make the entire block dynamic. By default each tier's first menu item should show its sub-menu (as shown in the Scenario-1)
4. All the menu items which are active should show themselves highlighted (like what comes with any standard menu, when we click that item gets highlighted).
5. Path dynamics: Instead of click tier by tier if, I paste the path upto 3rd tier, the block should dynamically detect and show accordingly in the block.
6. This block or its all three sections are not drop-down type, it is just normal menu block.
7. The menu items is divided into two column as shown in the image block.

**What I tried:** I tried to achieve by this using the panels module(mini). I choose layout of 3 column and several row. And add the menu in the as content manually and set the visibility as per the path. But this is not a feasible. As you can see for the second tier I have to make the 6X2 panes and for 3rd tied 6X6X2 panes (2 is for 2 columns). This is not at all feasible. I did not try entirely, but i tried to see it, it is working with panel visibility setting.

# Answer
# Part 1 - Rules is definitely your friend!

It seems that you should definitely have a look at how the the Rules Block visibility module can help you in "reducing" the challenge contained in your question here.

Admitted, you'll probably need MORE then just that module (and appropriate custom rules) to make it work, but I would definitely recommend this module as part of the solution you're looking for.

Even though your question does say so (yet), I imagine the various scenarios / menu items each also correspond to some combination of paths (URLs). With that, and by using the Rules event "Drupal is initializing", you should even get closer to what you're looking for.

And to avoid you'd get too many (separated) custom rules to make it all work, I'd also try to keep your number of custom rules to a minimum, by also adding the Conditional Rules module to this mix.

# Part 2 - BEAN might help too!

Because you have quite some blocks-related requirements, I'd definitely also have a look at the Bean module, to check if it can help also to answer this question. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

So by adding appropriate fields to your blocks, you may be able to reduce the number of blocks you'd actually need. E.g: maybe your Scenario 1 could be implemented with just a single block.
> 1 votes

---
Tags: 7, blocks, navigation
---


title: hook_user_insert not working

text:
# Question
Title: hook_user_insert not working
I am new to drupal. When user register into my website I need to get the users details and passed to a thirty for server . I am trying the following hook,

```
function compass_preprocess_user_insert(&$edit, $account, $category) {
  db_insert('test')
    ->fields(array(
      'accountid' => $account->uid,
    ))
    ->execute();
}

```

here compass-my theme name Please help me...

# Answer
> 2 votes
`hook_user_insert()` can only be implemented in a module, not a theme. Themes are just for styling/marking up content that modules produce, they shouldn't contain advanced logic like that.

You'll need to add a custom module and implement the hook in there to continue.

---
Tags: users, hooks
---


# Question
Title: How to implement just a 'Purchase Order' solution (without Drupal Commerce)?
Here is the situation: I need create a content type 'Purchase Order' with just few fields: date, product to buy, quantity, price unit, price total, author. The goal is don't need be finding in the future the SKU of products which we bought before, and in the finish of the year see how many papers or PC we bought. We are small group and I don't believe a complete 'Drupal Commerce' solution will be necessary, just a content type, with views for some basic reports.

I though make some small content type 'Purchase Order' with a entity reference to the product(s) content type but I stuck in the quantity field (and price). The problem come when I referenced the product, **add a field to that relationship for the quantity**, and later see in a custom view how many times that product was bought (and link the orders). Also, take the price from the related products, multiply by quantity and count the total price.

Some idea for Drupal 7?

# Answer
> 1 votes
Below are 2 possible alternatives (options) for setting up a simple shopping cart without using Drupal Commerce (as in your question) (or Ubercart) modules.

# Option 1: A lightweight e-shop

If you're only looking for a simple and lightweight e-commerce solution, then have a look at the Light Shop module. 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.

# Option 2: A simple shopping cart

If you're only looking for a shopping cart, then have a looking at the Basic Cart module. Here is a quote from its project page:

> Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
>
> **Main difference from Ubercart and Commerce:**
>
> The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
>
> **Features:**
>
> * The possibility of choosing the content types that can be added to the cart.
> * The possibility of sending, or not, an email to the customer once an order is placed.
> * Custom email messages for both the site administrator and the customer, along with the order details.
> * Order registration and listing in the administration area using Views module.
> * Integration with Rules module.
> * A block with the contents of your shopping cart.

Here is a screenshot of it (note the `Checkout` button also ...):

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


# Question
Title: Programmatically do something when a node is updated
I want to do something when a node gets updated. To keep it simple, lets say display a drupal message.

**hello\_world.routing.yml**

```
hello_world:
    path: /node/{node}
    defaults:
        _controller: Drupal\hello_world\Controller\HelloWorldController::hello_world_entity_update
    requirements:
        _permission: 'access content'

```

Not sure if the path should be `/node/{node}/edit` instead.

**HelloWorldController.php**

```
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloWorldController extends ControllerBase {

  public function hello_world_entity_update(Drupal\Core\Entity\EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }
}

```

Since hook\_node\_update() was depreciated, I assume we now have to use hook\_entity\_update().

I am not getting the message upon updating a node, what I'm I missing or doing wrong?

---

### Update

> Just so I don't confuse anyone. I was brainwashed into thinking I needed a routing file and a controller. All the D8 examples out there use them.
>
> **Since I was not creating any pages**, turns out **I did not need a routing.yml file nor a Controller.php file** nor the /src folder. All I had to do is approach this like Drupal 7, all that I needed was the .info.yml file and a .module file to put the hook.

# Answer
Hooks are still implemented as global, procedural functions; you need to declare them in the .module file just like Drupal 7, not in a controller class:

```
function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // ...
}

```

It's also worth noting that `hook_ENTITY_TYPE_update()` also exists, so you can still use `hook_node_update()`:

```
function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  // ...
}

```
> 13 votes

# Answer
1. You need not define any controller for this .
2. Write this code in your custom .module file.

use Drupal\Core\Entity\EntityInterface;

```
 function module_name_entity_update(EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }

```
> 3 votes

# Answer
There are lots of hooks are available for node.

You can inherit in template.php file and write down your code.

you can use hook\_node\_update in template.php
> -2 votes

---
Tags: 8, hooks
---


# Question
Title: LoginToboggan redirect to the same page on Drupal-7
I have a Drupal-7 website and I use LoginToboggan module for login.
Is there a way to override this module or change the settings, in order to redirect users to the same page after successful login, and not on the user's profile page?

# Answer
> 0 votes
I found the answer, what did it was the Login Destination module!

---
Tags: 7, authentication-authorization
---


# Question
Title: Calling a class defined from another module
I am calling the method defined in a class implemented from another module using the following code.

```
use Drupal\module_name\MyClassName;

$instance = Drupal\module_name\MyClassName::getinstance($host, $user, $pass);

```

My code doesn't work, as I get an error about a class not found. What am I doing wrong?

The class is contained in module/src/controiller/controller\_name.php.

# Answer
> 6 votes
In your comment, you say the class is inside module/src/controiller/controller\_name.php, but you refer to the class as `Drupal\module_name\MyClassName`. That is wrong.
Assuming module\_name is the directory containing your module (and the short name of the module itself), and that module\_name/src/Controller/controller\_name.php is the file containing the class definition, you need to use the following code.

```
use \Drupal\module_name\Controller\MyClassName;

$instance = MyClassName::getinstance($host, $user, $pass);

```

That is evident in any file referring a class, for example user.routing.yml.

```
user.logout:
  path: '/user/logout'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::logout'
  requirements:
    _user_is_logged_in: 'TRUE'

```

As you notice, the class is referenced as `\Drupal\user\Controller\UserController`, not `\Drupal\user\UserController`.

Also, the filename is generally the name of the class plus the php extension, so in your case the file name should be module\_name/src/Controller/MyClassName.php, not module\_name/src/Controller/controller\_name.php.

As side note, if you are calling a static method for a controller class, you probably need to do something more than just invoking it. Normally, controllers get also the dependency injection container; without that, they would not work. See for example `UserController::create()`.

```
public static function create(ContainerInterface $container) {
  return new static(
  $container->get('date.formatter'),
  $container->get('entity.manager')->getStorage('user'),
  $container->get('user.data')
  );
}

```

If you call controller a class that is not a controller class as Drupal defines that, then your code could work; differently, if you are calling a Drupal controller class, resolved the error about a class not found, you will get more errors to fix.

# Answer
> 2 votes
Make sure your class is under my\_module\src, in a file called MyClassname.php, then refer to it via its fully qualified namespace:

```
$instance = Drupal\my_module\MyClassname::getinstance($host, $user, $password);

```

Or alias it:

```
// Top of file
use Drupal\my_module\MyClassname;

// Later on
$instance = MyClassname::getinstance($host, $user, $password);

```

---
Tags: 8
---


# Question
Title: How to call template when Custom form is submitted?
I have created custom form and on submit of that form, I need to fetch data from database and need to display that content in well structured format in different template.

I am able to create form, on submission, I am able to fetch data from database but I am **not able to pass** that result to another template and display data on that template. I have also tried with

```
 function nexposed_menu() {
  $items = array();

  $items['form-example'] = array(
    'title' => 'Example Form',
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nexposed_form'),
    'access callback' => TRUE
  );
  return $items;
}

function nexposed_form($form, &$form_state) {
  $toppings = array(
    'Jan' => t('Jan'),
    'Feb' => t('Feb'),
    'Mar' => t('Mar')
  );

  $form['month'] = array(
    '#title' => t('Months'),
    '#type' => 'checkboxes',
    '#description' => t('Select the Month'),
    '#options' => $toppings,
  );
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}

function nexposed_form_validate($form, &$form_state) {
}

function nexposed_form_submit($form, &$form_state) {
  drupal_set_message(t('Search submitted successfully.'));
  $query = db_select('node', 'node');
  $query = $query->fields('node', array('nid', 'title'));
  $query->condition('node.type', 'events');
  $rows = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

  return theme('event_page', array('data' => $result, 'paging' => $paging));
}

```

Where `$result` contains data in the key value pair format, but that template is not called rather no result is displayed.

Any help regarding this is highly appreciated. Thanks in advance.

# Answer
Please update your \_menu function with this code.

```
  function filterevents_menu() {
  $items = array();

    $items['events-filter'] = array(
        'title' => 'Events Listing',
        'description' => '',
        'page callback' => drupal_get_form,
          'page arguments' => array('filterevents_form'),
        'access callback' => TRUE,
    );
    return $items;
  }

```

And then clear drupal cache. Hope it will work.

Thanks.
> 2 votes

# Answer
Please follow the procedure given in the below link, might be it will work

http://themery.com/dgd7/advanced-theming/forms/with-templates
> 0 votes

---
Tags: 7, theming, hooks
---


# Question
Title: How to use Rules to fetch domain Whois Data, parse the data and save it to fields?
For a domain management website I would like to import all Whois data to entity fields. A domain is an (ECK) entity, with the fields corresponding with the Whois data.

There are public Whois api's available, such as http://bulkwhoisapi.com/ but I'm not sure which one would best serve the import method I want to use.

How can this be accomplished?

**Note**: My preference is to use Rules and not create a custom module.

# Answer
> 1 votes
When you want to use Rules, you still need to have a connection between Rules and the API. The Rules module by default cannot make API requests (though some contrib module might provide it).

As an alternative I'd like to present to you, the Feeds module.

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

This module is designed to perform (periodic) requests to external API's and store the data locally. Plus there are a lot of video tutorials out there to help you with this.

The downside is that feeds by default cannot save to an ECK entity (it can save into a node). The Feeds ECK Processor is currently under review and not yet ready for production. The Feeds Entity Processor might work (suggested on the Feeds ECK Processor application page), but this is unconfirmed. Or you can use Feed Rules to obtain the data with Feeds and then send it to Rules where you can attach it to your entity.

So far this seems possible. The only problem is that feeds does not accept input parameters, so you'd have to create a new feeds importer for every domain...

It is probably not the answer you were hoping for, but perhaps someone else knows how to resolve this last missing piece.

# Answer
> 0 votes
I'd look at writing a custom module that hooks into `_presave()`, uses the phpWhois library to grab the information, and then stores it to the proper fields.

---
Tags: 7, rules
---


# Question
Title: Some tags in the output from my controller are filtered away
I have a controller defined in MODULE.routing.yml which returns:

```
return array(
      '#type' => 'markup',
      '#markup' => $this->content(),
      '#attached' => array(
        'library' => $libs,
      ),
    );

```

The content contains H2, INPUT and SELECT (amongst others). The INPUT and SELECT are removed so I guess there's an input filter being run on this markup.

How do I control the input filter for this controller and/or disable it completely?

# Answer
> 2 votes
That is behavior Drupal 8 has for the #markup property, as described in Render API overview. It is different from the behavior Drupal 7 had; if you are converting code from Drupal 7, you need to change that part of the code accordingly.

> **#markup**: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through `\Drupal\Component\Utility\Xss::filterAdmin()`, which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, `<script>` and `<style>` are not allowed.) See `\Drupal\Component\Utility\Xss::$adminTags` for the list of tags that will be allowed. **If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed\_tags to alter which tags are filtered.**

The highlighted part tells you how to solve the filtering of tags.

See also the next part of the documentation.

> **#allowed\_tags**: If #markup is supplied this can be used to change which tags are using to filter the markup. The value should be an array of tags that `Xss::filter()` would accept. If #plain\_text is set this value is ignored.

---
Tags: 8, input-formats, page-controller
---


# Question
Title: How to include a form with Ajax callback using form_load_include
i have a location.inc file that have a form with a 3 level dependent dropdown. when i execute this file by itself the code works 100% fine. but now i need to call that form into another form (register\_contratista.inc). The form\_load\_include i'm using in register\_contratista.inc its working...it render the form items into the new form but just when i select an options at the first dropdown it gives me an ajax error. I have no clue why it's happening been stuck for hours with this error.

I believe the problem is that the callback functions from location.inc are not working through the form\_load\_include.

this is the code from location.inc:

```
 <?php
//define types of locations.
define("LOCATION_TYPE_COUNTRY", 1);
define("LOCATION_TYPE_STATE", 2);
define("LOCATION_TYPE_CITY", 3);

// start location form creator.
function location_form($form, $form_state) {

  $countries = _location_get_countries(); //get all active countries

  $flat_countries = array(
    '' => '-- Seleccione país --',
  );

  $flat_countries = location_flatten_locations_array($countries, $flat_countries);
  $flat_states = array(
    '' => '-- Seleccione departamento --',
  );

   $country_id = '';

 if(isset($form_state['values']['p_ctry'])) {
    $country_id = $form_state['values']['p_ctry'];
    $states = _location_get_states($country_id);
    $flat_states = location_flatten_locations_array($states, $flat_states);

 }

 $flat_cities = array(
    '' => '-- Seleccione ciudad --',
    );
  $state_id = '';

   if(isset($form_state['values']['p_dept'])) {
    $state_id = $form_state['values']['p_dept'];

    $cities = _location_get_cities($state_id);

    $flat_cities = location_flatten_locations_array($cities, $flat_cities);
  }

    $form['p_ctry'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione país del proyecto'),
    '#options' => $flat_countries,
    '#default_value' => $country_id,
    '#required' => TRUE,
    '#ajax' => array(
        'callback' => 'location_country_change_callback',
        'wrapper' => 'state-wrapper',
        ),
    );

    $form['p_dept'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione el departamento/estado'),
    '#prefix' => '<div id ="state-wrapper">',
    '#options' => $flat_states,
    '#default_value' => $state_id,
    '#suffix' => '</div>',
    '#ajax' => array(
        'callback' => 'location_city_change_callback',
        'wrapper' => 'city-wrapper'
        ),
    );

    $form['p_city'] = array(
    '#type' => 'select',
    '#title' => t('Seleccione ciudad'),
    '#prefix' => '<div id ="city-wrapper">',
    '#options' => $flat_cities,
    '#suffix' => '</div>',
    '#default_value' => isset($form_state['values']['p_city']) ? $form_state['values']['p_city'] : '',
    );

  return $form;

}

function location_country_change_callback($form, $form_state) {
  return $form['p_dept'];
}

function location_city_change_callback($form, $form_state) {
  return $form['p_city'];
}

function location_flatten_locations_array($array, $start = array()) {

  if(is_array($start)) {
    $result = $start;
  } else {
    $result = array();
  }

  asort($array['by_name']);

  foreach($array['by_name'] as $item) {
    $result[$item['id']] = $item['name'];
  }

  return $result;
}

function _location_get_locations($location_type){

    $location_type = intval($location_type);
    static $locations = array();

    if(!array_key_exists($location_type, $locations)) {

       db_set_active('civilproconstru');

      $query = 'SELECT * FROM `location` WHERE `location_type` = '.$location_type.' AND `is_visible` = 1';

      $result = db_query($query);

      foreach ($result as $row) {
          $name = $row->name;
          $id = $row->location_id;
          $parent = $row->parent_id;

          $record = array(
            'name' => $name,
            'id' => $id,
            'parent' => $parent,
          );

          $locations[$location_type]['by_name'][$name] = $record;
          $locations[$location_type]['by_id'][$id] = $record;
      }

       db_set_active();

    }
    return $locations[$location_type];
}

function _location_get_countries() {
  return _location_get_locations(LOCATION_TYPE_COUNTRY);
}

function _location_get_states($country_id = null) {
  $states = _location_get_locations(LOCATION_TYPE_STATE);
  if(!is_null($country_id)) {
    $closure = function($item) use($country_id) {
      return $item['parent'] == $country_id;
    };
    $states['by_name'] = array_filter($states['by_name'], $closure);
    $states['by_id'] = array_filter($states['by_id'], $closure);
  }
  return $states;
}

function _location_get_cities($state_id = null) {
  $cities = _location_get_locations(LOCATION_TYPE_CITY);
  if(!is_null($state_id)) {
    $closure = function($item) use($state_id) {
      return $item['parent'] == $state_id;
    };
    $cities['by_name'] = array_filter($cities['by_name'], $closure);
    $cities['by_id'] = array_filter($cities['by_id'], $closure);
  }
  return $cities;
}

```

And this is the code from register\_contratista.inc where i'm doing the form\_load\_include

```
<?php

function registro_contratista_page($form, &$form_state){

  form_load_include($form_state, 'inc', 'lc_core', 'location');
  $renderable = drupal_get_form('location_form', $form_state);
  $location = render($renderable);

  $form['usuario'] = array(
  '#type' => 'fieldset',
  '#title' => 'Registro de usario',
  '#description' => 'Información necesaria para el registro de usuario en la plataforma.',
  '#tree' => TRUE,
  );

  $form['usuario']['name'] = array(
  '#title' => 'Nombre de usuario: ',
  '#description' => 'Nombre de usuario con el cual se identificará en la plataforma, puede ser diferente a su nombre y debe contener máximo 12 letras.',
  '#type' => 'textfield',
  '#size' => '20',
  '#required' => TRUE,
  );

  $form['usuario']['mail'] = array(
  '#type' => 'textfield',
  '#title' => 'Correo electrónico: ',
  '#description' => 'Correo electrónico con el cual administrará su cuenta en la plataforma.',
  '#required' => TRUE,
  );

  $form['ubicacion'] = array(
  '#type' => 'markup',
  '#markup' => $location,  //HERE I RENDER THE FORM FROM location.inc
);
     $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

function registro_contratista_page_submit($form, &$form_state) {

    $new_user = array(
          'name' => $form_state['values']['usuario']['name'],
          'pass' => user_password(),
          'mail' => $form_state['values']['usuario']['mail'],
          'init' => $form_state['values']['usuario']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_pais' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_pais']))),
            'field_dept' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_dept']))),
            'field_city' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_city']))),
    );
 user_save(null, $new_user);
}

```

And this is the error i'm getting:

> Any idea where this error it's coming from???

---

## UPDATE: NEW THEORY.

I'm not sure if this is the problem or not, i just got this new theory that might be the cause of the problem. As you can see at location.inc i have two functions like this:

```
function location_country_change_callback($form, $form_state) {
  return $form['p_dept'];
}

```

That are the ones to update the options value of the second and third select list, this function works properly when executing the location.inc separately but when using it with form\_load\_include it is not working because the function can't find the field (in this case) "\['p\_dept'\]" so when i choose an option at the first dropdown i'm getting error because it doesn't know where to put the new values.

If this is the problem is there any way to specify to put those values at a specific field from a different form? like using $form\_id? something like:

```
$form_id = 'my_new_form_id';
function location_country_change_callback($form, $form_state) {
  return $form['p_dept'] at $form_id;
}

```

> First let me know if you agree or disagree with this theory and if you do, how could i fix it?

# Answer
> 0 votes
Ive been through a lot of that kind of error. When you are sure there's really nothing wrong with your code, check your values queried from the database. There might be unwanted characters in your data. Sanitize your data.

In my case, I encountered `ñ` characters, so what I did is clean the string before saving it in a variable.

```
 foreach ($result as $row) {
     $name = myid_clean_string($row->name);
 }

 //A function that cleans a string by replacing '?' by 'ñ'
 function myid_clean_string($word){
     return str_replace('?','ñ', trim($word));
 }

```

You might do the same. Just check your data. Abba Yahweh bless you.

# Answer
> 0 votes
The callback functions might not be visible to the calling form. You can test it by moving the callbacks back into register\_contratista.inc.

---
Tags: forms, ajax
---


title: Insert a value to $form_state

text:
# Question
Title: Insert a value to $form_state
```
    function form_example_form($form, &$form_state) {
      $form_state ['store_value'] =1;
      $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
      );

  return $form;
}

```

How to do this in drupal 8

# Answer
Insert the the value in `$form_state`:

```
$form_state->set('store_value', 1);

```

And then later for example in `submitForm()`:

```
$value = $form_state->get('store_value');

```

Don't use getValue() or setValue(), because this is for submitted values.

If you are migrating more forms from D7 to D8, use this as reference:

$form\_state is now a classed object
> 10 votes

# Answer
`$form_state` is a instance of FormState object, you need use `setValue($key, $value)` method to store values on it.

Check the docs for additional info.

**From docs:**

> Parameters
>
> string|array $key: Values are stored as a multi-dimensional associative array. If $key is a string, it will use $values\[$key\] = $value. If $key is an array, each element of the array will be used as a nested key. If $key = array('foo', 'bar') it will use $values\['foo'\]\['bar'\] = $value.
>
> mixed $value: The value to set.
> 0 votes

---
Tags: forms, 8
---


# Question
Title: How do I alter the default node URL rendered in a view?
I have a view that shows a list of node titles, where the node title is linked to the node detail page. I want to alter the node URL with a custom one.

How can I alter the node URL?

# Answer
Usually when you set a URL alias when you creating/updating a node this new url will be used for your nodes links. If you didn't set a URL alias for your nodes, clear the caches after set. In my dev site working fine just doing this.
> 0 votes

---
Tags: views, 8
---


# Question
Title: How do I determine the route of my view?
I made a new view page and I want it to be in the router table so that I can know its route, but it's not there. How can I determine the route of this view or insert it into the router table?

# Answer
> 0 votes
To find out what the route was for a view, I actually ended up doing this in a custom module, and then looking at the page route in the object.

```
/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_page(&$variables) {
  dpm(\Drupal::request());
}

```

---
Tags: 8
---


# Question
Title: How to allow all commerce customers to use their billing address as their shipping address, in Commerce Shipping 2.X?
Almost all shopping sites have a feature to allow customers to use their billing address as their shipping address, to save them typing it in twice in the very common case of a customer having the same shipping address as their billing address. This should be possible both for customers with accounts, and for anonymous customers.

Looking for this feature in Drupal Commerce, I find some hacks suggeested in 2012, and a long issue report that seems to suggest this feature has been implemented.

However, the steps listed in that issue seem to be for the 1.X branch only, not the 2.X branch, and seem to no longer apply:

> For people who are a little lost like me, this is where you will find the settings:
>
> * store/customer-profiles/types/billing
> * store/customer-profiles/types/shipping
>
> Halfway down the page, under Format Handlers, you'll see a checkbox with the following text:
>
> "Copy billing address (required to be activated on billing profile along with the profile you want to copy the address on to. In order to work properly, the two addresses need to be on the same page.)."
>
> Check this on for both the billing and shipping profile types. Save both. I'd imagine you also need to make sure the other format handlers are identical between the two profile types--though I haven't tested it.

Those pages have moved, and I can't find any such checkbox in their new equivalent. Likewise this related question is 1.X only.

How do we enable this common feature in the 2.X branch of Commerce Shipping?

# Answer
Go to **Checkout Settings** (`admin/commerce/config/checkout`). Find **Shipping Information** pane and click `configure`.

You'll see setting for copying billing address right there (screen below)
> 2 votes

---
Tags: 7, commerce
---


# Question
Title: create a custom form based on user fields
I created new menu item witch I want to insert a custom form to edit some user fields :

```
$items['user/%user/edit-custom'] = array(
  'title' => 'Knowladge',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('user_profile_form_custom', 1),
  'access callback' => 'user_edit_access',
  'access arguments' => array(1),
  'type' => MENU_LOCAL_TASK,
);
return $items;

```

Then the custom function that return the form :

```
function user_profile_form_custom(){
  module_load_include('inc', 'user', 'user.pages');

  global $user;
  $user = user_load($user->uid);

  $form = drupal_get_form('user_profile_form', $user, 'account', 'custom');

  return $form;
}

```

When visiting `"user/%user/edit-custom"` page I can see the profile page, then with some logic code in `hook_form_alter` I can hide some fields and show up only needed fields...

But the problem that I can't save the form, I get this error :

> Fatal error: Call to undefined function user\_profile\_form\_validate() in path\_to\_drupal/includes/form.inc on line 1514

this solution is inspired from answers described in this post .

Have you any idea please how to solve this, or if you have another way to get some user fields, edit them in a custom page, and save the changes.

Thanks in advance.

# Answer
> 0 votes
Is it possible you missed the comment (below)? It's on the post you linked to.

> "module\_load\_include('inc', 'user', 'user.pages'); should be added to hook\_init() otherwise all profile form functionalities that require AJAX calls will return the error 'Call to undefined function user\_profile\_form\_validate().'"

# Answer
> 0 votes
Adding the parameters `$form` and `&$form_state` in the custom function must correct the bug!

# Answer
> 0 votes
Instead of module\_load\_include(), use form\_load\_include().

Here's the code:

```
global $user;
$account = user_load($user->uid);

$form_state = array();
$form_state['build_info']['args'] = array($account);

form_load_include($form_state, 'inc', 'user', 'user.pages');

$form = drupal_build_form('user_profile_form', $form_state);

$output = drupal_render($form);

return $output;

```

---
Tags: 7, users, forms
---


# Question
Title: Chosen Module working on one <select> but not other selects
I use drupal 8 and chosen module and I set "Minimum number of options for single select" and "Minimum number of options for multi select" and "Minimum number to show Search on Single Select" to "always apply" . Now I create advanced searche with views and use 2 filter criteria whit entity refrenced exposed. When I set one of them setting to dropdown and other to autocomplete , it worke correctly . But when I set all of them settings to dropdown chosen not work .

# Answer
Set above code in theme.libraries.yml and it worked .

```
  dependencies:
    - core/jquery
    - core/drupal
    - core/jquery.once

```
> 0 votes

---
Tags: 8
---


# Question
Title: Superfish menu is not responsive for mobile screens
i'm using drupal 7 and superfish 7.x-1.9, the problem is when i reduce the browser, the menu is not responsive, it still be the same nothing moves, i'm working on it for hours now and nothing

Please any help on configurations ?

Here a screenshot of the desktop menu :

And here the same menu with browser reduced on width :

# Answer
> 1 votes
Superfish has a pretty extensive settings/configuration area, all of which, do take away any necessary programming for menus, and make setting up a complex menu simple.

You are probably missing a mobile declaration somewhere in the settings/config, I would read up on the Superfish documentation here: https://www.drupal.org/node/754652

This also has other useful links that may assist with your situation.

---
Tags: 7, navigation
---


# Question
Title: Drupal 7 Views: Use one views.tpl.php file for multiple views
Views allows you to customize output with tpl.php files.

My theme directory is getting overloaded with the .tpl.php files! Many of the files repeat the same content.

I would like to use the same tpl.php file for multiple Views. How can I do this?

Ideally, I would like to call a template file when a tag has been applied to a View.

---

**Steps I have Tried**

**Use Multiple Views displays:** This thread suggests putting all the Views that use the same template file into one view and then creating separate Views displays for them.

This isn't practical for my situation, as my Views have very different fields, which would result in a lot of overriding (which makes them harder to manage).

**Views Pre Process** This article suggests to use a Pre Process function. You can then select specific views and use a theme hook suggestion to load template files. However, the code it provides is incomplete, so it's not clear how to load the template files. It's also not clear how to load different field/row/display/style templates for a single view (as a View template can take one of a field, row, display or style template).

# Answer
> 11 votes
In Views 3 you can add tag “template1” to your views and create template `views-view--template1.tpl.php`.

Multiple tags supported.

# Answer
> 1 votes
Even for a cloned view, we can add tags (comma separated) and create a common template for multiple views.

---
Tags: views, theming
---


title: Clear block cache in panels page

text:
# Question
Title: Clear block cache in panels page
I'm having trouble with refreshing content in a block created with a custom module, placed within a panels page. My end goal is to display either regular or seasonal hours based on a set date range. My `hook_theme()` implementation looks like the following:

```
function daily_hours_theme() {
  if (daily_hours_is_summer()) {
    $table_template = daily_hours_get_summer_vars();
  } else {
    $table_template = daily_hours_get_regular_vars();
  }
  $items =  array(
    'todays_hours_table' => $table_template,
    'daily_hours_text_content' => array(
      'render element' => 'element',
    )
  );
  return $items;
}

```

I'm using `hook_block_info()` to test cache settings; the following doesn't seem to have an effect on caching:

```
function daily_hours_block_info() {
  $blocks['hours_table'] = array(
    'info' => t('Daily Hours Table'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

```

And `hook_block_view()` to call the theme function:

```
function daily_hours_block_view($delta = '') {
  switch ($delta) {
    case 'hours_table':
      $block['content'] = theme('todays_hours_table');
      break;
  }
  return $block;
}

```

Ideally, I'd clear the module's block data at midnight every day, but I'd settle for just knowing how to implement any caching rules in this context.

# Answer
The variables were being cached at some point in the `hook_theme()` function, so after reading the documentation on `hook_theme()`, I moved the logic to conditionally use different variables in to my `hook_block_view()` implementation, passing them in to the call to `theme()` at that point. So that function looks like the following:

```
function daily_hours_block_view($delta = '') {
  if (daily_hours_is_summer()) {
    $variables = daily_hours_get_summer_vars();
  } else {
    $variables = daily_hours_get_regular_vars();
  }
  switch ($delta) {
    case 'hours_table':
      $block['content'] = theme('todays_hours_table', $variables);
      break;
  }
  return $block;
}

```

And my `hook_theme()` function:

```
function daily_hours_theme() {
   $items =  array(
     'todays_hours_table' => array(
       'template' => 'hours_table',
       'variables' => array(
          // set default variables here
       )
     )
   );
   return $items;
 }

```

The cache setting in my `hook_block_info()` implementation did not seem to have an impact once I set up the logic in the `hook_block_view()` function.
> 0 votes

---
Tags: 7, blocks, panels, caching
---


# Question
Title: How to display visitor's country flag depending on the visitor's IP address?
How can I display **Visitor**'s country name and flag and depending on his IP address in a block?

# Answer
> 2 votes
The Smart IP module can give you the user's IP address. The following code should give you a block, assuming you have flag images whose file names match the country code, e.g. "ie.png" for Ireland and those file are in "/sites/default/images".

```
function mymodule_block_info() {
  $blocks = array();
  $blocks['flag'] = array(
    'info' => t('Country flag')
  return $blocks;
}
function mymodule_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'flag' :
      $block['content'] = _flag_block_view();
      break;
  }
  return $block;
}
function _flag_block_view() {

  // Get the IP address
  $smart_ip_session = smart_ip_session_get('smart_ip');
  if ($smart_ip_session['location']['country_code']) {
     $code =  $smart_ip_session['location']['country_code'];
     $output = '<img src="/sites/default/files/images/' . strtolower($code) . '.png />';

  else {
    $output = "Nothing";
  }
  return $output;
}

```

The above is a simplistic solution. In practice you might want to make better provision for country codes and/or flag images not being available, add alt and/or title attributes to your tag, etc.

Also bear in mind you will need to choose a source of IP geolocation data. See this answer for info on that. And, remember geolocation data is not guaranteed to be 100% accurate.

---
Tags: location
---


# Question
Title: How do I attach a library to contact forms?
Simple question, I just need to know how to attach a library to Drupal 8's contact forms. I recently made a similar post for attaching a library to a view, that was accomplished by adding `{{ attach_library('mytheme/mylib') }}` to views-view--myview.html.twig, but doing the same to contact forms is less obvious. If the preferred way to attach a library is through twig templates can someone please advise me on what the naming convention is for contact-form twig templates?

# Answer
> 1 votes
Enable twig debug in your develop environment, then you can see through HTML comments all theme suggestions, then create a twig file with based in what you want template.

Original post here.

> # Debugging Twig templates
>
> The Twig templating engine offers a debug tool.
>
> The Drupal 8 implementation also adds an additional tool that allows you to locate the template that outputs the markup.
>
> ## Enable debugging
>
> You enable Twig Debugging in sites/default/services.yml. (If services.yml does not yet exist; copy default.services.yml and rename it to services.yml.)
>
> Set the debug variable to true.

```
parameters:
  twig.config:
    debug: true

```

Just pay attention, if you not using site's default folder, use that you created.

After turn on debug, clear the cache, then you will see something like this in your HTML

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
   x form--feedback.html.twig
   * form.html.twig
-->

```

If you need create a new name suggestion for a element, use `THEME_theme_suggestions_HOOK_alter` in your `.theme` file, and add your suggestion.

Example:

```
function THEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'form__' . $variables['element']['#form_id'];
}

```

---
Tags: theming, 8, emails
---


title: Broken modules are not rolled back

text:
# Question
Title: Broken modules are not rolled back
I try to develop a D8 module with entities. A lot of them ^^. But there is an issue with the way D8 handles the creation of tables during the installation process. If the definition of the entities is not correct D8 can't create the table. But the module is enabled anyway.

Now D8 is not able to uninstall the module. I have tried `drush pm-uninstall`, `drush cr`, `drush dre` on the module. The uninstall process fails every time because D8 cant find the table and is obviously not aware of the failed installation of the module.

The only way I figured out was to create the tables with the primary key and then to uninstall the module. That works, but is very time consuming. How can I force uninstall my module even if the corresponding tables doesn't exist? And why is D8 ignoring the fact that the module was not installed correctly in the first place?

# Answer
This is a known bug: https://www.drupal.org/node/2563515

As a workaround, remove the entity type definition (e.g. by removing the @ so it doesn't parse it as an annotation), clear cache, then uninstall.
> 4 votes

# Answer
You can uninstall the module from database from config.extension and remove blob there. I know that is very silly but till now we have this resolution.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: drupal 8.1 blocks config choices different from D8
I did a migration in Nov/2015 of my D6 to D8 and the blocks look like this.

>

Then I repeated the migration of my D6 to D8 on May/2016 and my blocks look like this.

>

They are different.

Where is the documentation for the configuration of the block visibility

Thanks,

# Answer
> 0 votes
This is not a difference between 8.0 and 8.1, it happens in both versions.

It is a core bug, triggered by ctools. See https://www.drupal.org/node/2632434

---
Tags: 8, blocks
---


title: Alter form value in submit_preprocess

text:
# Question
Title: Alter form value in submit_preprocess
How do I change a value, in this case the title field of a node object form, in the preprocess function of the form\_alter hook.

```
$form['actions']['publish']['#submit'][] = MODULE_submit_preprocess';

function MODULE_submit_preprocess($form, FormStateInterface $form_state) {

   $form_state->setValue('title', 'Updated Title'); //not working...

   $fstate = $form_state->getFormObject()->getEntity();
   dsm($fstate);
}

```

**dsm result**

```
stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
            [title] => Array
              (
                  [x-default] => Array
                    (
                         [0] => Array
                          (
                             [value] => Old Title

```

# Answer
To change Entities fields its better use `MODULE_ENTITY_presave()` function (more info in docs).

In this case that you need change a node field use this function:

```
function hook_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->set('title', 'Updated title');
}

```
> 1 votes

---
Tags: 8, forms, theming
---


title: How to create views grouped by title

text:
# Question
Title: How to create views grouped by title
I want to build a view sorting it on the basis of the term field. I need to show the term as a title in each group, like this:

* Term 1:

+ node1
    + node2
* Term 2:

+ node3
    + node4
* Term 3: ...

How can I achieve this?

# Answer
> 1 votes
**Steps to show the view in this ways is**

* Create an Unformatted view showing Title and Terms.
* Term field should be excluded from the display.
* Do a grouping of the term field.(Unformatted Format -\> Settings)

Save the view and check the result of the view.

Hope that this helps.

---
Tags: 7, views
---


# Question
Title: How to know what Drupal theme is this site using?
Does anyone know which Drupal theme this site is using? I am interested in purchasing a copy.

http://www.evolution-xy.fr

And also how to create a pedigree chart like that one with Drupal?

http://www.evolution-xy.fr/index/bovin/fiche/66/FR3529132100

When I checked the source code of the site, I found this line. `<meta name="Generator" content="Drupal 7 (drupal.org)"; />`, which makes me believe it's a Drupal site.

# Answer
> 1 votes
Looks like a custom theme to me. Here is why I think so: I see nothing in the code to points to a known Drupal theme. The theme in the code is called Evolution (name of the site) which usually means a custom theme was built. Also, a search for Evolution Drupal Theme shows nothing that looks like the sites theme. Although, I could be wrong, just a guess.

# Answer
> 1 votes
You can get it from source of any page. Have a look for the javascript array at the top/bottom of the page that begins with:

```
jQuery.extend(Drupal.settings, {...

```

There's a setting in that array called "theme" which contains the name of the theme being used for that page.

FYI - The site of yours uses Evolution theme.

Hope that this helps.

---
Tags: theming, charts
---


title: Execute reaction rule programmatically

text:
# Question
Title: Execute reaction rule programmatically
I want to run Commerce rule "Create a new account for an anonymous order" from code. I can create user with `user_save` and etc, but I like this rule and want to reuse it.
After a hour I finished with this code:

```
// Load reaction rule by name.
$rule = rules_config_load('commerce_checkout_new_account');
// We need $state for 'evaluate' or 'fire'.
$state = new RulesState();
// Add 'commerce_order' parameter to state.
$state->addVariable('commerce_order', $line_item_wrapper->order->value(), array('type' => 'commerce_order', 'label' => 'Commerce order'));
// Execute rule.
$rule->evaluate($state);
// How can I get created user account from $rule?
// Now I have to do user_load_by_mail().

```

It works but I don't think it is the best way.
I especially don't like to create `RulesState` manually. I know there are `setUpState()` and lots of other methods. I want to find the best solution without creating new Rules component.

# Answer
As a related solution, it's much easier to execute a **Rules *Component*** programmatically. They're designed for that.

For example, consider a **Rules Component (type "Rule")** that accepts a `$commerce_order` parameter.

In this case, it happens to process a queued order item from a cron queue, pushing the order to a remote system via an API.

```
function MODULE_queue_iwi_push_instant_sale($item){
  try{
    if($order = commerce_order_load($item['order_id'])){
      // Invoke the rules component programmatically
      // passing the $order parameter
      rules_invoke_component('rules_iwi_push_instant_sale', $order);
    }
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
  }
}

```

I like to think of Rules Components as similar to functions that can be called, passing parameters and potentially returning a value. They can do other magical things as well. See `rules_invoke_component`

Reaction rules on the other hand are event driven, triggered by some event such as node\_save and passed the relevant parameters. See `rules_invoke_event`

More info on Rules Components here: https://drupal.org/node/1582182
> 5 votes

# Answer
Thanks for the answers. After reviewing the code here, I've created a helper function that works to execute a rule directly (not a component) and is a little simpler/cleaner than the initial code.

You have to look at the rule in the UI and figure out parameters (In conditions, sometimes wrapped and sometimes loaded objects. Experiment.), event machine id (in delete event URL), and rule machine id (in rule edit URL).

Example: send a commerce order email.

```
    $order = commerce_order_load(285);
    $params = array('commerce_order' => $order);
    $status = mysite_test_fire_rule('my_rule_machine_name', 'commerce_checkout_complete', $params);

/**
 * @param $name string Machine name of rule to fire. From UI edit url.
 * @param $event string Machine name of event. This is a protected property on rule.
 *        dpm($rule->events) or get from the delete button URL on the rule itself.
 * @param $params array of parameters to pass to function, key value paired. Name of param, value of param
 *
 * @source http://drupal.stackexchange.com/questions/45183/execute-reaction-rule-programmatically
 */
function mysite_test_fire_rule($rule_name, $event, $params){
  $rule = rules_config_load($rule_name);
  $state = new RulesState();
  foreach ($params as $param_key => $param) {
    $state->addVariable($param_key, $param, $rule->parameterInfo(TRUE)[$param_key]);
  }
  return $rule->fire($state);
}

```
> 2 votes

# Answer
Personally I perferred not to do it with Rules but to do it with the checkout hook. To each his own though.

```
function hook_commerce_checkout_complete($order) {

        global $user;

            $customer_id = (empty($order->data['self']['CustomerID'])) ? 0 : $order->data['self']['CustomerID'];
        //Create a user if the person is anonymous
        if ($user->uid == 0) {
        //Ignore my customization here, I passed in form data from a custom form to this part, you can just as easily get access to shipping/billing entity data to do the same thing.

            $new_uid = user_creation($order->data['self']['ShippingEmailAddress'], $order->data['self']['ShippingEmailAddress'], $order->data['self']['Password'], $customer_id, $order->data['self']['FirstName'], $order->data['self']['LastName']);
            unset ($order->data['self']['CustomerID']);
            //Set the user id to the newly created user id

            $order->uid = $new_uid;
        } else {
            //Since the user is not anonymous we set the $uid to the value of the currently logged in user
            $order->uid = $user->uid;
        }

```
> 0 votes

# Answer
I don't think there is a better way. As it appears firing event rules from code is not a common thing. the only place I was I found using this is on commerce product pre calculate http://www.rit.edu/drupal/api/drupal/sites%21all%21modules%21commerce%21modules%21product\_pricing%21commerce\_product\_pricing.module/function/commerce\_product\_pre\_calculate\_sell\_prices/7.41 same RulesState() creation as yours
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: 7 - Views Filter where one field equals Logged in User's Email field
On a custom content type I have created, there is a List(text) field called "Assigned to" that has a drop down selection of certain emails. (E.g user1@domain.com, user2@domain.com, user3@domain.com, etc.)

I have a separate view that displays fields from that content type.

I am looking for a way to filter results where the Logged in User's email field equals what is in the "Assigned to" field.

I thought of using a Contextual Filter, but that would require the user's email to be in the URL.

Could I use php code as a way to make the default contextual filter value equal the logged in user's email?

I have tried to use the following with no success:

```
global $user;
echo($user->mail);

```

Thank you.

# Answer
> 2 votes
Add your `"Assigned to"` field as contextual filter, and set "provide default value" to PHP code just like you were thinking, but change your php snippet to return a value instead of printing:

```
global $user;
return $user->mail;

```

# Answer
> 0 votes
It is possible to provide a default value of the currently logged in user to the contextual filter. When you're configuring your contextual filter look for "Provide default value" and "type" and you'll see some options in there, the user ID for the logged in user is directly underneath the option for getting the user through the URL. You might have to play with the settings a bit but that might give you a start.

---
Tags: views
---


# Question
Title: How to disable breadcrumbs for certain pages?
How can I just disable breadcrumbs for certain pages on drupal 8?

There is a module for this on D7, is it easy in D8?

# Answer
> 9 votes
Your Breadcrumb is a block that you place in Block Lay-out. Then just change its visibility.

---
Tags: 8, breadcrumbs
---


# Question
Title: No more coding with Tool builder in ELMSLN?
I am not a coder, but have lots of ideas that I want to realize. Recently there was a blogpost from *btopro* (Bryan Ollendyke) from the ELM Learning Network showing a video on https://www.elmsln.org/blog/post/tool-builder.

Suppose you have an idea, but are not that good in Drupal. In the video you can see that when you can create a view, a content type, a block and a point to Github you are able to make a contribution as a non-coder.

Can this also be done with other Drupal stacks and a point to a git like Github?

I will clearify more by quoting Bryan, the developer:

> This is one of the more insane things I've ever added to the project. It will, pave the way to fundamentally changing who can contribute "code" and ideas. Ideas shouldn't stem from one person, or one group of people simply because they know how to write code and understand version control. I'll let the video speak for itself but I'm having trouble containing my excitement throughout said video. We are moving beyond simple remix culture with this and into the elimination for the need to have developers to make meaningful, code based, contributions. People can model their ideas and show us instead of just describing them in the queues. This is what I mean when I say things like "unleashing innovation" or "sustainable innovation". We want to empower you to empower and education others through constructing technology and then be able to share those constructions with others.

# Answer
The ELMSLN Tool Builder as demonstrated in the video appears to be like a set of magic buttons, which:

* use as **input** the various options of a Drupal website that is configured using site building techniques only. So there is no custom Drupal coding involved, which is typically done by Drupal developers writing all sorts of PHP, JavaScript, etc.
* include all sorts of code generation processes to automagically **generate** a Drupal "*install profile*".
* use Drush and GIT, behind the (video) scene, to have the **output** delivered to an appropriate GIT repository, such as GitHub.

For this "magic" to work (without traditional coding), there are a few criteria (challenges) to keep in mind when you're clicking together these types of contributions, as further detailed below.

# Do the modules you're using support import / export?

it is crucial that you're using (contributed) modules that do support "export" of the items that the Drupal site builder has put (clicked) together. Modules such as Views, Rules and Flag are known to come with these import/export facilities.

However, if there are also *blocks* involved, then you're out of luck for such import/export facilities, since the (core) block module does not have these facilities. Unless ... you use the BEAN module for creating blocks (that module will ensure you can also import/export your blocks).

But, assume your contribution also comes with some set of special "roles" ... which you cannot import/export out-of-the-Drupal-box. You'll have to find a way to also make those exportable (hint: *there is a module for it* ... also!)

# How to package the various functions of your contribution?

This is where the Features module joins the game. It is typically used to select (using site building) the various parts of a site (some views, rules, content types, fields, required modules, etc). The result of this is that you (automagically) generate PHP code (behind the scenes), which at first seems like a typical Drupal module (with a .info file, a .module file, etc). You'll typically have "a number of features" (Drupal-like modules), eg just a few, or a dozen or so. Refer to the article about "Creating content types and fields using a custom module in Drupal 7" for an interesting recap of how use Features to "generate" a custom module for creating some content types and its related fields (and module dependencies).

But putting together the sets of these features is really (repeat: really) an art. Because it is extremely hard to not run into the typical issues (pains) of using Features. Refer to my answer to "How to use the Features module in a 3 dev environnement?" for (way more) details about that challenge ...

# Version management and migration management?

It's relatively easy to automagically generate a 1.0 version of such contribution. But think about what it would take to later on generate a 1.1, 1.2, or 2.0 version at some point in the future. Yes there is the Features Diff module, but that's only part of the puzzle when it comes to upgrading.

Even if version management turns out to be doable (fairly easy?), what would be the solution to (also automagically?) ***migrate*** the existing content created in (say) a 1.0 version of it towards its (say) 1.2 version equivalent. Do you want to restart from scratch (empty content) when you're launching 1.2? Open question (at least for me): if you do not want to restart from scratch, then how would such content migration procedure be generated automagically?

# Conclusion

Something like ELMSLN Tool Builder looks easy to get started with it, but the longer you'd be using such contributions, and the more functionality they come with, the more challenging things will become. Don't take "my" word for it, just verify on drupal.org what the maintenance status of most Drupal distributions look like. Yes there are ***some*** well maintained, amazing distributions, but also ***quite a lot*** that are not.
> 1 votes

# Answer
Well, if you just want to ship configuration, you can always use something like Features and distribute Views, content types, etc. in that way. It requires a basic knowledge of how to use Git.

But in all honesty, if you're wanting to developer and distribute Drupal based software, you should either get better at Drupal or find a developer to help you out.
> 3 votes

# Answer
Pierre.Vriens write up is absolutely correct. Tool Builder is intended for those that could learn site building (quickly) to be able to portray their idea to the ELMSLN core development team. It is intentionally not a sustainable solution.Features Builder, Profiler Builder, and Drush Recipes are intended (usually) as the starting point for building something more sustainable. While you CAN build sustainable things using the innovation builder in elmsln, as the lead developer, would probably recommend using the tool to get a sense of how to start your next big idea but then branching from there. Similar techniques and using it as a base line lead to things like: We stole this site and you should too.
> 2 votes

---
Tags: 7
---


# Question
Title: Is there an option to somehow display all nodes that that doesn't have a menu link?
As almost all users here know, you can set up a menu link to each node from the "Menu settings" tab in the node's edit form.

Is there an option to show all nodes that don't have a menu link?

I tried to create a view and use the filter criteria to achieve that, but no relevant filtering option appeared for me there.

# Answer
> I tried to create a view and use the filter criteria to achieve that, but no relevant filtering option appeared for me there.

A workaround would be:

1) Add a Boolean type field to your content type.

2) Check-mark the field for all the nodes that have a menu link

3) Filter view by your boolean field. (where the boolean is false, unchecked, equal to 0)

**Bonus:** If you're using Drupal 7 you could use Menu Rules which lets you add the a condition

> Conditions: \- Node has menu entry - checks if the node has a menu link.

Therefore, you can use rules to automatilly check or uncheck your boolean field, that way you don't have to remember to check it or uncheck it, when you check or uncheck the menu link option.

> **Note:** As pointed out, if you have lots of menu link nodes, which would make ✓ check marking all their boolean field annoying and time consuming, you can create a Rule Component that uses Views Bulk Operations with the **Node has menu entry condition** to check mark all of those nodes boolean fast.

**Bonus 2:** If you did Bonus 1, you can use Field Permissions to hide your boolean field from the edit page.
> 1 votes

# Answer
I think the best approach to handle this would be to get all of the menu items, and the nodes associated to them. Then perform a EntityFieldQuery on nodes. Making sure that your query includes a 'NOT IN' condition, and use the ids from the nodes you discovered in the menu as the values.

This would return all nodes not in your menus.
> 1 votes

---
Tags: nodes
---


# Question
Title: How to handle multiple stores and multiple store admin users
Is it possible to create a restaurant(multi-store) online delivery system using Drupal commerce and OG? It has multiple stores(restaurants) in different locations which can be manageable by individual restaurant admins. The super-admin also have full control over all restaurants- can create products for each restaurants.

We have up to 40 restaurants and each restaurants have different products(food items). Each restaurant admin need to add/update own products and own store addresses, delevery time, etc

I have checked with Commerce Marketplace and seems difficult to implement.

Please share your valuable thoughts.

# Answer
> 0 votes
I am currently working on a similar project and I am using commerce marketplace. Had faced some issues, but overall it was a smooth journey using marketplace. Also, it is not difficult to implement.

# Answer
> 0 votes
Another approach, which I use for a multi-restaurant installation, is an alternative version - commerce marketplace by maciej.zgadzaj.

> Module package providing overrides for default Drupal Commerce behaviors allowing to use DC-based stores to create multiple-merchant marketplace (like Etsy, Amazon, etc).

Admin creates all the stores (restaurants). Then each store has its own products i.e. food items. I believe this version fits better with drupal commerce. Make sure each store's products have unique SKU's.

For a guide on use cases and installation, see Commerce Marketplace: Installation and use cases. Just make sure you pull the latest version from git.

From your answer, I believe you are using the other version.

---
Tags: commerce, users, organic-groups
---


title: Dynamic allowed values list

text:
# Question
Title: Dynamic allowed values list
How to display dynamic allowed values list in drupal 8?

In drupal 6 while creating cck select list, I written php code instead of entering allowed values. The sample code of drupal 6 is as follows :

```
$query = db_query("SELECT distinct field_x_value as x FROM {node} n, {content_type_y} ctdr , {content_field_x} cfer WHERE n.nid = ctdr.nid and cfer.nid = ctdr.nid and field_x_value is not null and field_user_state_value = %d and n.status = %d and field_environment_value = %d", $user->user_state, 1, $environment);

```

How to do the same functionality in drupal 8?

# Answer
> 5 votes
It's not possible to set it in the UI, but it's still possible through code.

If you check the exported configuration for your field, you can see that it has an `allowed_values_callback` property. Create a custom module, create a function that returns the allowed values, set that property in config and then import the configuration again. Or use `drush cedit` or a similar tool.

# Answer
> 0 votes
You need to create one content reference field with manage fields in content type. Through which you can set default **content type** or you can set **views of reference** type in "Reference method" dropdown in CCK configuration field. No need of custom query.

---
Tags: 8, entities
---


title: Insert a node field programmatically

text:
# Question
Title: Insert a node field programmatically
I have a `<div>` containing a node (a Basic Page), which has a title, body and a header image. I do not want to display the header image inside that div, so I removed it from the block layout. I would like the header image to be in the html before the `<div>`, that is, outside of the div into which the given content type is outputted (so I cannot solve this via block layout, since the image field is to be outputted outside of the content block).

Can I somehow programmatically instruct my theme to display the header image of my Basic Page? Or is there a better way how to do it?

Example: I need to change this:

```
<div>
<img src="headerimage.jpg">
<h1>Title</h1>
<p>body</b>
</div>

```

to this:

```
<img src="headerimage.jpg">
<div>
<h1>Title</h1>
<p>body</b>
</div>

```

# Answer
> 0 votes
You can put php code in a block template and write something like:

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

```

and then access the specific field you want to show like:

```
print $node->title;
print $node->field_yourfield["und"][0]["value"]

```

Edit:

Also, you can modify the node template for the teaser, copying the node.tpl.php file in your subtheme (you can look how to make a subtheme here) and putting the html structure you want inside:

```
if($teaser)
{
...
}

```

There are other displays available for nodes other than page and teaser.

---
Tags: theming
---


# Question
Title: Post method not working on non-CRUD methods
I'm just trying to create custom rest service action but I can't get it. I have created end\_point called "testing". Whenever I try to post the data it shows access denied for authenticated user. Where I'm going wrong?

The steps I followed:

I can't get the name. What I expecting is the post call must return the username "abc" according to my below function.

```
function my_module_service_services_resources() {
    return array(
      'test' => array(
         'actions' => array(
            'username' => array(
              'check' => array(
                'help' => 'Checks username for uniqueness',
               'callback' => 'test_module_username_check',
               'access callback' => 'my_module_service_access',
                'access arguments' => array('view'),
                'access arguments append' => TRUE,
                'args' => array(
                  array(
                    'name' => 'username',
                    'type' => 'string',
                    'description' => 'The username to check',
                    'source' => 'data',
                    'optional' => FALSE,
                  ),
                ),
              ),
            ),
          ),
       ),
    );
  }

  function test_module_username_check($username) {
    return $username;
  }

  function my_module_service_access() {
    return true;
  }

```

# Answer
> 0 votes
After debugging the action method of **user/login** (default in services module), I found where I went wrong. In my code, I added extra array called **check** inside **username**. When I remove that array everything is going well. Here the updated code

```
function my_module_service_services_resources() {
    return array(
      'test' => array(
         'actions' => array(
            'username' => array(
              'help' => 'Checks username for uniqueness',
              'callback' => 'test_module_username_check',
              'access callback' => 'my_module_service_access',
              'access arguments' => array('view'),
              'access arguments append' => TRUE,
              'args' => array(
                array(
                  'name' => 'username',
                  'type' => 'string',
                  'description' => 'The username to check',
                  'source' => 'data',
                  'optional' => FALSE,
                ),
              ),
            ),
          ),
       ),
    );
  }

  function test_module_username_check($username) {
    return $username;
  }

  function my_module_service_access() {
    return true;
  }

```

---
Tags: 7, services
---


# Question
Title: Can you do branching multistep forms in ctools?
I'm using the ctools multistep form code in a couple of places in a project, and would like to branch the user's path through the form. That is, in step 1, I get some stuff from the user that allows me to determine that the user should be sent to either steps 2a, 2b, and 2c, or 3a, 3b, and 3c. I've been looking but haven't yet found anything out there about this; are branching multistep forms in fact possible with ctools?

# Answer
> 0 votes
Yes, branching logic can be done.

If your validation/submit handler for step 1 sets `$form_state['clicked_button']['#next'] = '2c`, your next step will be 2c.

There are a few gotchas, which may or may not surface depending how your forms are intended to be used, whether they allow stepping backwards, etc.

All your steps should at least be in `$form_info['forms']` so the wizard knows how to load them.

Note however, that if step 2c is not in `$form_info['order']`, the default "trail" generated by the wizard will not have any of the steps highlighted as it can't figure out where 2c fits in. Likewise, the next/previous steps around 2c may not be the ones you intended if 2c is not listed in the normal flow order.

The wizard basically pre-populates `#next` on your buttons based on `'$form_info['order']`, and then pushes that value into `$form_state['redirect']` in its own submit handler, so you have complete control of which step is next. You could manually override `$form_state['redirect']`, but the wizard should be able to manage it for you.

If your step progression is basically linear but you only want to "skip ahead" based on the selection in step 1, this works fine as you can simply add all steps to `$form_info['order']` in your page callback (or where you defines `$form_info`) and doing the next/back logic in your validation/submit handlers. The user will see all steps listed in the "trail" but may skip some depending on your conditional logic. (The back button also has `#next` set to say what it goes back to.)

If your step progression is truly branching and a fixed order including all steps would not make sense, I would recommend to hide the trail and re-implement it yourself using the logic which determines which steps go in which order.

---
Tags: 7, chaos-tool-suite, forms
---


title: How to export path breadcrumbs

text:
# Question
Title: How to export path breadcrumbs
I see written everywhere that Path breadcrumbs https://www.drupal.org/project/path\_breadcrumbs can be exported via features. But I am unable to see any Path breadcrumb option when I'm creating a feature, nor I see any export thing in Path breadcrumbs settings.

Do you know where/how?

# Answer
**Features:** Check if you have Path Breadcrumbs module checked in Features Settings (screenshot below). If it was checked and you still do not see it in the Features components list than something else is amiss.

---

**Export:** As for the direct **export of Path Breadcrumbs**, you can find "export" link while clicking on "edit" in path breadcrumbs actions list (screenshot below)

Hope this helps.
> 2 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: How to send a notification to admin on profile picture change?
I want the new uploaded pictures to be sent (notification) to me (admin) for review and approval just to be sure they are in line with the terms and conditions of the webpage. Naked or semi-naked pictures are strictly forbidden.

How can I achieve this?

# Answer
> 1 votes
I suggest you try to use a combination of 2 approaches, as further detailed below.

# Approach 1 - Prior approval required

If you'd use the the Profile 2 module, then the Profile 2 Moderation module, which depends on the Profile 2 module, enables moderation on user profiles. Here is a (self explaining?) screenprint from its project page.

Be aware however that, as mentioned on the project page, it requires a Profile revisions patch.

# Approach 2 - After the facts

Use the Rules module to be informed about all sorts of updates that you're interested in, similar to what's detailed in my answer to "How to send an eMail notification when a specific field of a node or user has been changed?".

With this approach, and as per all the great things you can do with this module, your options are virtually unlimited. This approach also allows you to implement this type of moderation using a granular approach: start small, maybe only using a few custom rules, and keep refining them and continue adding new ones.

Not to forget all the available integrations with tons of other modules, of which the Flag module is probably your very first priority to also add that module for what you're trying to implement. Just a basic usecase about this:

* Use Rules to *flag* any user for which some profile update happened.
* Use Views to build a list of such flagged users.

If you'd only implement these 2 bullets of this approach (a matter of minutes, say an hour at max), you'd already have a Version 1.0 of your **User Profile Moderation Dashboard** (call it your *MVP* if you prefer ...).

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

# Answer
> 0 votes
avatar approval this module worked great for me.

---
Tags: users
---


title: How to make authored on field emtpy

text:
# Question
Title: How to make authored on field emtpy
I have a content type with revision enabled, each time when I edit the node I can see **authored on** field has `created date` by default. I want this field to be empty so that it uses latest updated time as created time. How can I achieve it?

# Answer
> 3 votes
You might want to use rules 'After updating existing content of type typename' in events and 'set data value' timestamp to created date will accomplish your task easily.

# Answer
> 2 votes
You could use hook\_node\_presave() to accomplish this. Something like this might work:

```
function hook_node_presave($node) {
   // check so the node if of a specific type and a revision
   if ($node->type == 'your-type' && $node->revision == TRUE) {
     // sets creation date equal to the modification date
     $node->created = $node->modified;
   }
}

```

The above would go in a custom module file and you then have to rename the `hook` part to the actual name of your module.

---
Tags: 7, nodes
---


title: Store events for later retrieval

text:
# Question
Title: Store events for later retrieval
I'm sending out emails on certain events (e.g. new article, or in a cronjob if a certain node hasn't been updated in the last weeks).

Now, I want to track whether these emails get reacted upon. I can easily track the opening of a mail or the click on a link with Google Analytics using ?utm\_... query parameters, but can I store inside Drupal that a mail was sent?

For now I'm abusing `watchdog()` and its Views integration, but is there a better solution?

# Answer
I think you are looking for mail tracking module. Which is ditto to your description.
> 0 votes

---
Tags: log-messages
---


# Question
Title: How do I use the geoip_language_redirect module?
I am working on a multilingual website, and I have setup the multilingual concept successfully.
Now I want to redirect the users to the corresponding language URL based on the IP address or country. For example, if users are from france, I want to redirect them to http://www.example.com/fr like.

I found the geoip\_language\_redirect module, but I don't know how to use it.

Can anyone help me on this?

# Answer
> 0 votes
As the project page says, after you installed the module, you need to set up the *geoip\_redirect\_mapping* persistent variable with an array that associate the ISO country code with the language.

```
variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

```

For example, put the following code in setup.php, and save it in the same directory where Drupal has its cron.php and index.php.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
variable_set('geoip_redirect_mapping', array(
  'GB' => 'en',
  'FR' => 'fr',
  // …
));

```

Visit http://example.com/setup.php, and the variable will be setup. After this, you can delete the file.

If you have Drush, then you can alternatively execute the following command from the site directory (from the terminal).

```
php -r "print json_encode(array('GB' => 'en', 'FR' => 'fr'));"  | drush vset --format=json geoip_redirect_mapping -

```

For the rest, the module automatically redirects the users.

### Please note the following

The project page is a little confusing. It's not clear if the persistent variable is *geoip\_mapping* or *geoip\_redirect\_mapping*. I didn't find in the code any reference to that variable, so I cannot confirm which one is correct. I would try *geoip\_redirect\_mapping*, since that is the one used from the example code; if that doesn't work, I would try *geoip\_mapping*. If neither of them works, I would open a support request for the module, if there isn't one already, asking to change the project page to make it clearer.

---
Tags: users, i18n-l10n, redirection, multi-sites
---


title: #ajax callback uses the wrong callback

text:
# Question
Title: #ajax callback uses the wrong callback
I don't know why, but using this code, when I click on the *marker-category-add-submit* button, it executes the *type\_callback* callback, and not *marker\_category\_add\_callback*. Why?

If I comment all marker-type fields in my form, it uses the right callback.

```
function food_truck_form_admin() {
  $content_types = get_content_types();
  $markers_categories = variable_get('food_truck_form_marker_categories', array());
  $vocabulary = get_vocabulary();
  $marker_types = get_marker_types($vocabulary->machine_name);

  // MARKER CATEGORY
  $form['marker-category']['#markup'] = '<h2>Gestion des catégories de marqueurs</h2>';
  $form['marker-category']['#prefix'] = '<div id="category-wrapper">';

  $form['marker-category-add'] = array(
      '#title' => t('Nom'),
      '#type' => 'select',
      '#prefix' => '<div class="row"><div class="column">',
      '#options' => $content_types,
      '#description' => t('Ajouter une catégorie de marqueur')
  );
  $form['marker-category-add-submit'] = array(
      '#type' => 'button',
      '#suffix' => '</div>',
      '#value' => t('Ajouter'),
      '#ajax' => array(
        'callback' => 'marker_category_add_callback',
        'wrapper' => 'category-wrapper',
        'event' => 'click'
      )
  );
  $form['marker-category-remove'] = array(
      '#title' => t('Supprimer des catégories de marqueurs'),
      '#type' => 'select',
      '#prefix' => '<div class="column">',
      '#multiple' => TRUE,
      '#validated' => TRUE,
      '#options' => $markers_categories
  );
  $form['marker-category-remove-submit'] = array(
      '#type' => 'button',
      '#value' => t('Supprimer'),
      '#suffix' => '</div></div></div>',
      '#ajax' => array(
          'callback' => 'marker_category_remove_callback',
          'wrapper' => 'category-wrapper',
          'event' => 'click'
      )
  );

  // TEST ZONE

  $form['marker-type'] = array(
      '#title' => t('test'),
      '#type' => 'textfield',
      '#prefix' => '<div class="type-wrapper">'
  );
  $form['marker-type-submit'] = array(
      '#type' => 'button',
      '#value' => t('Ajouter'),
      '#ajax' => array(
          'callback' => 'type_callback',
          'wrapper' => 'type-wrapper',
          'event' => 'click'
      )
  );
  $form['marker-type-list'] = array(
      '#title' => t('test'),
      '#type' => 'select',
      '#suffix' => '</div>',
      '#multiple' => TRUE,
      '#validated' => TRUE,
      '#options' => array()
  );

  // $form = array_merge($form, generate_marker_types_management_form($markers_categories));

  $form['marker-wrapper-end']['#suffix'] = '</div>';

  // ATTACHEMENTS
  $form['#attached']['css'] = array(
      drupal_get_path('module', 'food_truck_form') . '/css/global.css',
      drupal_get_path('module', 'food_truck_form') . '/css/config_form.css'
  );
  $form['#submit'][] = 'food_truck_form_admin_submit';
  return system_settings_form($form);
}

function type_callback($form, &$form_state) {
  array_push($form['marker-type-list'], $form_state['value']['marker-type']);
  return array(
      $form['marker-type'],
      $form['marker-type-submit'],
      $form['marker-type-list']
  );
}

/**
 * CALLBACK : Ajouter une catégorie de marqueur
 */
function marker_category_add_callback($form, &$form_state) {
  // On récupère la clé et le nom de la catégorie
  $key = $form_state['values']['marker-category-add'];
  $marker_name = $form['marker-category-add']['#options'][$key];

  // On récupère les catégories existantes
  $food_truck_form_marker_categories = variable_get('food_truck_form_marker_categories', array());
  // Si on ajoute une catégorie qui n'existe pas déjà
  if (!array_key_exists($key, $food_truck_form_marker_categories)) {
    // On sauvegarde les catégories
    $food_truck_form_marker_categories[$key] = $marker_name;
    variable_set('food_truck_form_marker_categories', $food_truck_form_marker_categories);
    drupal_set_message(t('La catégorie de marqueur à été ajouté'));
    $form['marker-category-remove']['#options'] = $food_truck_form_marker_categories;
  } else {
    drupal_set_message(t('Cette catégorie de marqueur à déjà été ajouté !'), 'warning');
  }
  return array(
      $form['marker-category'],
      $form['marker-category-add'],
      $form['marker-category-add-submit'],
      $form['marker-category-remove'],
      $form['marker-category-remove-submit']
  ); // return array_merge(get_return_callback($form), generate_marker_types_management_form($food_truck_form_marker_categories));
}

```

# Answer
> 0 votes
The solution was using différent '#name' in my buttons ;) coworker found the solutions :D

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


# Question
Title: Drupal 7 stopped working 500 internal Server error
For some reasons, my site stopped responding today, Error

> The www.mysite.com page isn’t working
>
> www.mysite.com is currently unable to handle this request. HTTP ERROR 500

I understand there are many reasons for 500 error and it hard to know what exactly happend, I had a look into server log and notice this error

> \[Wed May 11 10:31:27 2016\] \[warn\] \[client x.y.z\] mod\_fcgid: stderr: PHP Parse error: syntax error, unexpected 'return' (T\_RETURN) in /var/www/vhosts/mysite.com/httpdocs/pro/includes/common.inc on line 5106.

Looking into common.inc

```
function drupal_json_encode($var) {
  // The PHP version cannot change within a request.
  static $php530;

  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }

  if ($php530) {
    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}

```

Line 5106 = return json\_encode($var, JSON\_HEX\_TAG | JSON\_HEX\_APOS | JSON\_HEX\_AMP | JSON\_HEX\_QUOT);

# Answer
> 1 votes
For some reason under PHP selector in Plesk dom and gd was disabled. after enabling those two the site return back to normal.

---
Tags: 7, debugging
---


# Question
Title: Can I add a field collection to a block?
I have made a field collection, exported as a Feature and now I'd like to add it to a block. Does anyone have any suggestions? I have added fields to blocks through the form API, but that doesn't seem to apply here.

I would like to add this field collection through code, rather then finding a module.

I've looked at hook\_block\_configure to add the form there, but I don't know if I can add a type that isn't listed in Form API reference.

# Answer
> 3 votes
How about doing it through Views.

You can create a block view, add your field collection to the view, then use the view as a block.

# Answer
> 2 votes
With the default Block system you can't add fields to Blocks.

You can use the Bean module, which converts Blocks into Entities. Then you will be able to add fields to it.

# Answer
> 1 votes
You really need to have a look at the Bean to answer this question. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it. It also shows how the Bean module transforms Drupal blocks into fieldable entities.

---
Tags: 7, forms, blocks, entities
---