title: Behat drupal 8 configuration

text:
# Question
Title: Behat drupal 8 configuration
I have the following set up. I vagrant machine with d8 site setup. The files are common. I have replicated the DB in my laptop outside the host so I can run the behat tests faster. The DB is a dump of the one in the vagrant host.

Behat for host:

```
default:
  suites:
  default:
    contexts:
      - FeatureContext:
        - "/vagrant/images/behat"
        - 813
        - 1855
      - Drupal\DrupalExtension\Context\DrupalContext
      - Drupal\DrupalExtension\Context\MinkContext
      - Drupal\DrupalExtension\Context\MessageContext
      - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      selenium2: ~
      base_url: http://mysite.dev  # Replace with your site's URL
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/vagrant/drupal'

```

Behat for local:

```
default:
  suites:
    default:
      contexts:
        - FeatureContext:
          - "/vagrant/images/behat"
          - 813
          - 1855
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
  extensions:
    Behat\MinkExtension:
      selenium2:
        browser: chrome
      base_url: http://mysite.dev  # Replace with your site's URL
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/home/user/Projects/myproject/vagrant/drupal'

```

When I run the following scenario on the vagrant I can log in while in my local machine it fails to log in.

```
 @node
 Scenario: Create a node
   Given I am logged in as a user with the "administrator" role
   When I am viewing an "article" content with the title "My article"
   Then I should see the heading "My article"

```

How can I resolve this?

# Answer
The login step creates a user via the Drupal API, and logs in by manually submitting the form.

When you run from within the Vagrant machine, the process presumably has access to bootstrap Drupal, and create users. When you're running from your local machine, I think only 'blackbox' tests (eg, ones that don't require API access) will work.

One potential workaround for this would be to specify in your local behat file:

```
api_driver: drush
drush:
  alias: 'vagrant'

```

and then ensure your local machine had a drush alias `@vagrant` setup so that you could access your vagrant Drupal instance from your local machine.
> 1 votes

---
Tags: 8, virtual-machine, testing
---


# Question
Title: 404 Not found : Could not find the controller. Services module
I have installed services module and enabled `Resource-> node`. Now i am using postman to test default services. My configuration details: endpoint is "apis". Server is "REST". localhost url `http://drupaltest.localhost.com`. Also as per given in README file, i have downloaded spyc.php file and placed into servers/rest\_server/lib/.

So when i am calling api `http://drupaltest.localhost.com/apis/node` its showing me result. when i am calling `http://drupaltest.localhost.com/apis/node/retrieve`, i am getting error: `404 Not found : Node retrieve could not be found`. And for `http://drupaltest.localhost.com/apis/node/create error: 404 Not found : Could not find the controller`.

Is there i am missing any configuration or any permission issue?

# Answer
> 1 votes
This may not have been part of your issue, as I also think a node id should be where you wrote `retrieve`. But regarding `spyc.php`, I noticed that this file should be placed at `sites/all/libraries/spyc/spyc.php` or you will get an error message on your status page.

---
Tags: services
---


# Question
Title: How to create a hook for a module in a theme?
I am trying to alter some data that is being passed from the `Language Switcher` module.

Here is a code snippet from the module.

```
if (isset($links->links)) {
  $build = array(
    '#theme' => 'links__language_block',
    '#links' => $links->links,
    '#attributes' => array(
      'class' => array(
        "language-switcher-{$links->method_id}",
      ),
    ),
    '#set_active_class' => TRUE,
  );
}

```

So `'#theme' => 'links__language_block',` as I could guess means that I have to create the function called

```
function mytheme_links__language_block(&$variables) {
    var_dump("HELLO");
    exit;
}

```

But it is not called. I have no idea what is the problem ?

The only hook is called - `function mytheme_preprocess_page(&$variables)`

Please suggest what can be wrong and why my hook function is not called.

# Answer
I think this style of theme hook is deprecated in Drupal 8. From the API docs:

> Theme functions are deprecated in Drupal 8.0.x and will be removed before Drupal 9.0.x. Use Twig templates instead.

So since there doesn't exist a theme function `theme_links()`, the functions `MYTHEME_links` and `MYTHEME_links__language_block` would not be called.

You can still customize this output by adding a `links--language-block.html.twig` file to your theme.

You can also utilize preprocess functions (`MYTHEME_preprocess_links()`).
> 3 votes

# Answer
Anytime you add functions and template files to your theme, you should clear the cache so the functions and templates are picked up by Drupal.
> 1 votes

---
Tags: 8, hooks, theming
---


# Question
Title: Create a link to the fist item of a specific view block
I have different view blocks on my front page and they contain number of contents such as images, articles, news etc.

I've managed to get the block list and the block object for each item in that list but how do I fetch the nodes of a view block and generate a link to it programmatically?

```
$blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $theme->getname(), 'region' => 'content']);
$block_list = array_keys($blocks);

$firstblock = $block_list[0]; // views_block__latest_image_galleries_block_1
// fetch the node list and create the link for first node for $firstblock here.

```

# Answer
Since this is a view block, you might be better of directly accessing the view:

```
$results = views_get_view_result('my_view', 'block1')

```

Where `block1` is the Views display ID. Leave it blank to utilize the default display.

Then

```
$node = $results[0];
$url = $node->toUrl()->toString();
$link = \Drupal::l('My link', $node->toUrl());

```
> 0 votes

---
Tags: views, 8, blocks
---


# Question
Title: How to add a “Last Modified at” field in footer area?
I'm fairly new to Drupal and in my research I've seen this question asked many times over the years but I have yet to see one relevant to Drupal 8 (if it's out there, please direct me!). Specifically, I'd like to add a small bit of text in the footer that displays the M/D/Y of when the content of THAT page was most recently modified. How can this be done?

Thank you!

# Answer
> 3 votes
You can add a View in views, create a block display, give it a contextual filter of node id from current URL, then output the Changed field and select a date format. You can change the label to "Last modified on" and you're done. Then just place that block in the right region.

Sorry I don't have code or pics, posted from mobile.

Edit:

You can add a last modified date in the footer area of `page.html.twig`:

```
{% if node %}
  <p>Last modified at {{ node.changed.value|format_date('custom', 'm/d/Y') }}</p>
{% endif %}

```

This will work also, first is a no-code solution. Example, perhaps your requirement changes and you need to also show the time next to the date. That is just a simple update to the View, no twig edit + git + deploy + etc needed. Some prefer one way over the other.

Also, and I am going out on a limb here - you should know that `node.changed` only contains the last modified time on *that node*. If you changed other things on the page, like menu links in the header, or added new blocks, that date value won't change, because they are not part of the node object being viewed.

---
Tags: 8, theming
---


# Question
Title: Is there way for create custom "add userpoints transaction" form
Good day to everyone!

I have view which show user list, current userpoints, and email. I want set some link, which will lead to add transaction form where name will already fill. Is there way to add userpoints transaction for specific user except standard form?

# Answer
### Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to **Grant user points**, to the user specified as a parameter for this Rules Component.

For an example of a Rules Action to grant user points, refer to the rule included in the answer to "How to grant User Points to viewing user when user has viewed content?".

### Step 2

Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

### Tutorial

To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
> 1 votes

---
Tags: 7, views, userpoints
---


# Question
Title: How to Trigger Existing, Non-Form Ajax from JavaScript Event
I'm trying to figure out AJAX in Drupal 8.

I have a custom module that works, using AJAX to change the content of a div when a link is clicked.

The API says:

> Many different events can trigger Ajax responses, including:
>
> Clicking a button Pressing a key Moving the mouse

How do I trigger the same process that Drupal's AJAX does when a function is called from a JavaScript object's event firing instead?

JavaScript Object

```
function calledOnSomeEvent(e) {
  String data = e.target.data;
  // do something to call AJAX with the data
}

```

The AJAX backend works with this route:

myModule.routing.yml

```
myModule.myRoute:
  path: '/nojs/myFunction/{myParameter}'
  defaults:
    _controller: '\Drupal\myModule\MyController::myFunctionCallback'
    _title: 'myFunction'
  requirements:
    _permission: 'access content'

```

HTML

```
<a href="nojs/myFunction/testData" class="use-ajax">Click for testData!</a>

```

My understanding is that Drupal injects some sort of event when that link is clicked, or the URL is just changed, and the controller is only activated when that URL is changed.

JavaScript

```
(function($, Drupal) {

  Drupal.AjaxCommands.prototype.myFunction = function(ajax, response, status){

    $('#targetDiv').html(response.data);
  }

})(jQuery, Drupal);

```

I omitted PHP code for the controller, which creates a command. The command renders the output to Drupal.AjaxCommands.prototype.myFunction, which updates the div.

Is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

I think there might be a way for JavaScript interact with Drupal's AJAX handler to call the same function that clicking the link changed with "use-ajax" does, since that's being handled in some way...

Any insight would be appreciated.

Thanks!

# Answer
If you don't want to ajaxify a link by adding the class `use-ajax` you can trigger an Ajax request programmatically:

```
Drupal.ajax({url: endpoint}).execute();

```

This creates an Ajax object with the endpoint as url and executes it. The endpoint has to be a controller returning an AjaxResponse.

You find more options in the comments of `Drupal.ajax` in ajax.js:

```
/**
   * Provides Ajax page updating via jQuery $.ajax.
   *
   * This function is designed to improve developer experience by wrapping the
   * initialization of {@link Drupal.Ajax} objects and storing all created
   * objects in the {@link Drupal.ajax.instances} array.
   *
   * @example
   * Drupal.behaviors.myCustomAJAXStuff = {
   *   attach: function (context, settings) {
   *
   *     var ajaxSettings = {
   *       url: 'my/url/path',
   *       // If the old version of Drupal.ajax() needs to be used those
   *       // properties can be added
   *       base: 'myBase',
   *       element: $(context).find('.someElement')
   *     };
   *
   *     var myAjaxObject = Drupal.ajax(ajaxSettings);
   *
   *     // Declare a new Ajax command specifically for this Ajax object.
   *     myAjaxObject.commands.insert = function (ajax, response, status) {
   *       $('#my-wrapper').append(response.data);
   *       alert('New content was appended to #my-wrapper');
   *     };
   *
   *     // This command will remove this Ajax object from the page.
   *     myAjaxObject.commands.destroyObject = function (ajax, response, status) {
   *       Drupal.ajax.instances[this.instanceIndex] = null;
   *     };
   *
   *     // Programmatically trigger the Ajax request.
   *     myAjaxObject.execute();
   *   }
   * };
   *
   * @param {object} settings
   *   The settings object passed to {@link Drupal.Ajax} constructor.
   * @param {string} [settings.base]
   *   Base is passed to {@link Drupal.Ajax} constructor as the 'base'
   *   parameter.
   * @param {HTMLElement} [settings.element]
   *   Element parameter of {@link Drupal.Ajax} constructor, element on which
   *   event listeners will be bound.
   *
   * @return {Drupal.Ajax}
   *   The created Ajax object.
   *
   * @see Drupal.AjaxCommands
   */
  Drupal.ajax = function (settings) {

```

---

Your second question, is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

You can use a normal non drupal `$.ajax()`, then you have no restrictions for the format. The controller can return JSON (which Drupal uses for it's own ajax) or any other format. It's then your job to process the returned data in javascript.
> 18 votes

---
Tags: 8, javascript, routes, ajax
---


title: Drupal Array to string conversion hook

text:
# Question
Title: Drupal Array to string conversion hook
I am trying to change the links of the Language Switcher module. I am using the following code, but it doesn't work.

```
function mytheme_links__language_block(&$variables) {
  // Change variables
  return $variables;
}

```

When it gets executed, I get the following error:

> Notice: Array to string conversion in Drupal\Core\Render\Markup::create() (line 38 of core/lib/Drupal/Component/Render/MarkupTrait.php).

What is wrong? How could I return altered variables?

# Answer
The problem is solved by just using another hook

```
function mytheme_preprocess_links__language_block(&$variables)
{
    $variables['links']['en']['link']['#title'] = "ENG";
}

```

Thanks
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How can I have multiple caches of the same page with different query arguments?
Using Drupal 8, I have a page (a node) that has two different renderings depending on a passed in query parameter. This is to support a regular page view in a browser and also an embedded version of the page without the header, footer, etc. Example:

https://www.domain.com/my-page
https://www.domain.com/my-page?version=embedded\_view

I've implemented this by using THEME\_theme\_suggestions\_page\_alter() in my .theme file to suggest a different page template to use depending on the query parameter. (Perhaps there's a better way.)

When viewed on a site with caching enabled, both of the URLs return the same rendering of the page. How do I get different cached versions for the two URLs?

# Answer
> 7 votes
You have to add a cache context for the query parameter `version` to the page:

```
function THEME_preprocess_page(&$variables) {

  $variables['#cache']['contexts'][] = 'url.query_args:version';

}

```

The context will then be used to vary the cached pages by this query argument.

---
Tags: 8, caching
---


title: How can I retrieve the product ID?

text:
# Question
Title: How can I retrieve the product ID?
I am trying to retrieve the product IDs. I can find a product SKU by looking on the product page and using `commerce_product_load_by_sku()` to load it.

How can I find the actual ID? I would like to use it in `commerce_cart_product_add_by_id()`.

# Answer
According to the docs I found here `commerce_product_load_by_sku($sku)` will return a `$product` object and one of the properties is `product_id`.

```
$product = commerce_product_load_by_sku($sku);
drupal_set_message($product->product_id);

```

The product object looks something like this:

```
[product_id] => 5
[sku] => EX151
[type] => class
[language] => und
[title] => Example Product
[uid] => 1
[status] => 1
[created] => 1316634672
[changed] => 1316639451
[data] =>
[commerce_price] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [amount] => 12500
                        [currency_code] => USD
                        [data] => Array
                            (
                                [components] => Array
                                    (
                                    )

                            )

                    )

            )

    )

```
> 6 votes

# Answer
If you do not need the id to be retrieved in a function but just for a quick check, do

1. Install module commerce\_backoffice, if it is not already part of your Drupal Commerce install.
2. In views, find the view `Commerce Backoffice: All Product variations`. View this view.
3. Hover over a product title. See the product\_id as the last part of the corresponding status message in your browser, ie. `example.com/admin/commerce/products/1`.
4. You may want to alter the view by adding a column showing the product\_id directly.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How can I edit metadata and custom fields for an embedded image using Media Module in a WYSIWYG in D7
I need the ability to edit custom fields (Caption, Credit) on an image that has been placed in a WYSIWYG. I'm using the latest dev version of the media module and WYSIWYG + CKeditor. I see the fields fine when I add the image, but when I click the media button to edit the image, the custom fields are not accessible.

Adding an image works, but only if you upload a new image.

Editing does not show the fields though.

This seemingly was solved a long time ago... but doesn't seem to be part of the latest dev branch. https://www.drupal.org/node/835516#comment-7537339

Any direction on how to get the custom file fields to display and be editable with D7?

# Answer
> 1 votes
After a tremendous amount of research and trial & error, I was finally able to figure this out. The "trick" is to make sure you click the "override in WYSIWYG" checkbox on the file field at `/admin/structure/file-types/manage/image/fields/field_caption`

---
Tags: 7, media, wysiwyg
---


# Question
Title: Gettting errors after install drupal-8.2.6.nl.po
I add Language Dutch and import drupal-8.2.6.nl.po

This error is showed on every page: sourcetext 'The file could not be created'

What should I do? 1. Uninstall dutch language? 2. reinstall dutch language? 3. change language settings?

# Answer
(copying from my comment)

Sounds like your public file system is not writable, which is necessary to generate translation files for JS. When you get an error like this, always check the status report page.
> 1 votes

---
Tags: 8, i18n-l10n
---


# Question
Title: tableselect does not work for me somehow 1
```
Array
(
    [table] => Array
        (
            [#type] => tableselect
            [#header] => Array
                (
                    [field_name] => FIELD NAME
                    [field_type] => FIELD TYPE
                    [no_of_values] => NO OF VALUES
                    [display_fields] => DISPLAY FIELDS
                    [field_label] => FIELD LABEL
                    [required] => Required
                    [product_type] => Product Type
                )

            [#options] => Array
                (

            [field_colour_pro] => Array
                        (
                            [field_name] => field_colour_pro
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => color
                            [required] => 0
                            [product_type] => shirt
                        )

                    [field_description] => Array
                        (
                            [field_name] => field_description
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => description
                            [required] => 0
                            [product_type] => test_pro_v
                        )

                )

            [#multiple] => 1
        )

```

---

```
$header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  foreach(commerce_product_types() as $product_type => $product_type_array){
    $field_info = field_info_instances('commerce_product',$product_type);
    foreach($field_info as $machine_name =>$field_details){
      $rows[$machine_name] = array(
        'field_name' => $machine_name,
        'field_type' => $field_details['type'],
        'no_of_values' => $field_details['cardinality'],
        'display_fields'=>1,
        'field_label' => $field_details['label'],
        'required' => $field_details['required'],
        'product_type'=> $product_type,
      );

    }
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

//  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

return $form;

```

---

I tried to get the tableselect form #type into operation it does not work and gives empty row even when each row has values,I would like to help me find any silly mistake which I am making out here

Here is image of how the table select looks which is empty

# Answer
I copied your code from and commented the variables and/or functions you're using since I don't know what they are for and just replaced a simple array to loop through.

```
/**
 * Implements hook_menu().
 */
function leomod_menu() {
  $items['leoo'] = array(
    'title' => 'asd',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leomod_asd_form'),
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Form.
 */
function leomod_asd_form($form, &$form_state) {
  $header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  $tests = array('1', '2', '3');
  //foreach(commerce_product_types() as $product_type => $product_type_array){
  foreach($tests as $test) {
    // $field_info = field_info_instances('commerce_product',$product_type);
    //foreach($field_info as $machine_name =>$field_details){
      $rows[$test] = array(
        'field_name' => $test,
        'field_type' => $test,
        'no_of_values' => $test,
        'display_fields'=> $test,
        'field_label' => $test,
        'required' => $test,
        'product_type'=> $test,
      );
    //}
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

  //  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

```

Since your table structure is working, I suspect there is something wrong with these lines:

```
foreach(commerce_product_types() as $product_type => $product_type_array) {

```

and

```
$field_info = field_info_instances('commerce_product',$product_type);
foreach($field_info as $machine_name =>$field_details) {

```

Also make sure you:

1. Flushed caches
2. Show all errors while developing since you're dealing with functions there that may return some errors that aren't displayed
3. Check the variables and functions if they return anything by using print\_r() or Devel module's dsm().
> 2 votes

# Answer
Check that the function (presumably buildForm()) implements "FormStateInterface". Drupal will render a table w/o children if not done from within such a function. See: tableselect form doesn't work.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Load an AJAX submission enabled webform using another AJAX call
I am using Javascript/AJAX to call a path defined in a custom module which loads existing node content for display. i.e. you are at:

```
/custom/path

```

and it makes an AJAX request to /custom/content with arguments to load the content for the page (placed in #main-content). Content may be a page, video or other custom Content Types.

Custom navigation elements on the page cause further AJAX requests to /custom/content with different arguments to replace the content.

This has worked well until the need to incorporate webform's into the mix. Due to the non-refreshing nature of the page the webform needs to be loaded, displayed and submitted using AJAX.

I have setup hook\_form\_alter to add the necessary `$form['actions']['submit']['#ajax']` to webforms and they work properly when called directly. The form submits via AJAX. However, when they are loaded via AJAX this does not work. They submit as per normal and navigate away from my desired wrapper page.

I have ensured Drupal.attachBehaviours is being called post AJAX load. I suspect my problem is in the loading/rendering of the webform in the module, but have not been able to successfully piece it together. The module serving /custom/content basically does the following:

```
$node = node_load($node_id);
$output = drupal_render(node_view($task, 'full', NULL));
echo $output;

```

It displays the webform perfectly (like other content) - it just doesn't implement the `#ajax` submission part. I've tried all manner of more specific form buulding for when `$node-type = webform` but no success.

# Answer
> 0 votes
Try to create ajax links with this module Ajaxify Drupal with JQuery Ajax.

It will load all ajax behaviour of loaded content(if loaded content contains ajax enabled form then that also)

> Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.

# Answer
> 0 votes
You need to generate the JavaScript settings that Ajaxify the form, and pass them back with your response. You can do that like this:

```
$node = node_load($node_id);
$output = drupal_render(node_view($task, 'full', NULL));
$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
  $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ';
  $settings .= drupal_json_encode(call_user_func_array('array_merge_recursive', $scripts['settings']['data']));
  $settings .= ');</script>';
}

echo $output . $settings;

```

---
Tags: 7, ajax, webforms
---


# Question
Title: How to set "Entity has Field" when the Rules Event is unrelated to the entity?
In Rules, I am trying to update/calculate a field in the User's account upon completion of a commerce payment.

The condition data selector obviously only wants to populate commerce related fields, since my Event is "After saving new payment".

How can I define my custom field in the Rules Conditions?

My attempts to set the user or current-user entity has field are unsuccessful. But I know this must be simple.

# Answer
> 0 votes
Here are the steps to get this to work (whatever your existing Rule looks like ...):

1. Assume your current rule has some actions (= `SomeRulesActions`).
2. Create a new Rules Component like so:

* Use parameters related to the user (= say `ParmUser`) and payment (= say `ParmPayment`).
    * Add the Rules Conditions related to your custom field, which you should have available via the `ParmUser`.
    * Add Rules conditions identical to `SomeRulesActions`, using `ParmUser` and/or `ParmPayment`.
    * QA-test your Rules Component using the "Execute" link in front of it (in the Rues UI).
3. Update your existing rule like so:

* Delete all Rules Actions corresponding to `SomeRulesActions` (their equivalents are now included in the Rules Component you created in the previous step.
    * Add a Rules Action to execute the Rules Component you created in the previous step.

***Easy, no?***

An alternative solution where you don't need an extra Rules Component, is to rework your Rules logic by using the Conditional Rules module. If you wonder how to do that, use this link.

Ps: I'm assuming this is about D7.

---
Tags: 8, entities, rules
---


# Question
Title: How to clear a field using jquery after Ajax form reload
I have a custom module with a custom form with two fields: field A (select), field B (datepicker). When the user picks field B, it launches an Ajax call to validate field B. All works well so far, except for one issue: if user decides to change field A **after** the Ajax call, it should clear field B.

My problem is I can't get jQuery to detect that field A was changed after the Ajax is called. I can see field A's id changes from 'foo' to 'foo--2' and I've tried the below code with both '#foo' and '#foo--2' but neither works. jQuery works only the first time the form displays, but not after ajax fires. IOW the user can change field A's selection but jQuery doesn't detect that change, I can't even get the alert to trigger. Any ideas what I might be doing wrong here?

```
$('#foo--2').change(function(){
    alert ('change detected');
    'input#bar-datepicker-popup-1'.val('');
});

```

# Answer
Try this, it should work. Instead of *$(document).on* you can also use any outer static element.

```
$(document).on('change', '#foo--2', function(){
    alert ('change detected');
    'input#bar-datepicker-popup-1'.val('');
});

```
> 0 votes

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


# Question
Title: How to suppress composer autoload when installed as an unused dependecy?
I'm running a D7 site with the composer module installed as an unused dependency of the OpenLayers Module. The issue I'm having is that my watch dog log is filled with `RuntimeException: Autoloader not found: /var/www/html/phisigmarho.org/sites/all/vendor/autoload.php in composer_manager_register_autoloader() (line 173 of /var/www/html/phisigmarho.org/sites/all/modules/composer_manager/composer_manager.module).` and has caused at least one `/home/phislub9/public_html/error_log [24-Feb-2017 09:57:30 America/New_York] PHP Fatal error: Class ‘SensioLabs\Security\SecurityChecker’ not found in /home/phislub9/public_html/sites/all/modules/composer_manager/composer_manager_sa/composer_manager_sa.module on line 83`

Part of my issue is that the site is on a shared server that I don't think I can install composer on, so I'm kind of stuck letting the errors build up. I didn't think it was a problem till hitting the fatal error, and it's bad practice to let the script run and take up server resources. So is there some way to work around this? I don't use composer for anything, so I would happily get rid of it but it's a dependency. Can a dependent unused module be suppressed in some way?

# Answer
> 0 votes
I doubt composer manager is an unused dependency. It would make very little sense to list that module as a dependency and not using it. Are you sure there are no packages listed on `yoursite.com/admin/config/system/composer-manager`?

It is very likely that the module that defines the dependency requires some composer packages to function properly. Even if you managed to suppress the composer manager module, the main module would not have access to the package that composer was supposed to fetch, and likely will not work as expected. In that case you should consider two things:

1. Move to a host that gives you more privileges
2. Download the site to your own computer, install and run composer in the file directory configured on `/admin/config/system/composer-manager/settings` and re-upload the entire site, including the vendor directory.

If there are really really really no packages, you could try to change composer manager's `status` in the database `system` table to `0`. That disabled the module without checking for dependencies. It could however break a lot of other things, so have your backups and proceed with caution.

---
Tags: 7, javascript, composer
---


# Question
Title: Send data from controller to hook_form_alter()
I created a module for searching movies in different external databases. I use the Drupal node add page to handle the insertion of the movie. Now I need to know a way to send the data from my custom controller to the /node/add/movies\_movie page.

In the controller I use the following code to send data to the module page.

```
if ($system === "IMDB") {
    $database = new ImdbDatabase;
    $movie = $database->getDataById($id);

    $tempstore = \Drupal::service('user.private_tempstore')->get('movies');
    $tempstore->set("newMovie", $movie);
}

$option = [
    'guid' => $guid,
];

$url = Url::fromUri('internal:/node/add/movies_movie');

return $this->redirect(
    $url->getRouteName(),
    $url->getRouteParameters(),
    $url->getOptions(),
    302
);

```

My hook gets the value using the private tempstore service:

```
function movies_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    if($form_id === 'node_movies_movie_form')
    {
        //$movie = null;

        $storage = $form_state->getStorage();

        $tempstore = \Drupal::service('user.private_tempstore')->get('movies');
        $movie = $tempstore->get('newMovie');

```

I use `hook_form_alter()`to place the objects inside the add form. How can I send data from my controller to `hook_form_alter()` to place the custom values on the form?

To better understand my problem I will explain my situation in normal English without any technical terms.

The site contains a page to search to movies using a search bar. It will show the result of all the movies in a table with an add button after each movie. When pressing on a add button it will get all the data from the movie and will automaticly place the received movie data, in the movie insertion form. On the movie insertion form can be user change all the values and save it.

# Answer
I think you should not load the data in your controller but in your hook\_form\_alter. Redirect the user to a path containing a query parameter in Url, so that the url may look like "http://www.yoursite.com/node/add/movies\_movie?guid=123" and change the guid paramter to the value of the movie.

Then in your hook\_form\_alter:

```
$request = \Drupal::request();
$guid = $request->query->get('guid');

if ($system === "IMDB" && $guid) {
    $database = new ImdbDatabase;
    $movie = $database->getDataById($guid);

    // fill in the values of the movie into the form fields
}

```
> 3 votes

---
Tags: 8
---


# Question
Title: views_get_view_result in template.php? I want global variables using view results
I can't seem to get this to work..

```
function mytheme_preprocess(&$variables) {
    global $user;
    // Classes of logged in User
    $view_result = views_get_view_result(
        'profile_page_flagged_pages',
        'panel_pane_1',
        $user->uid
    );
    // Create array
    $class_array = [];
    foreach($view_result as $item_class) {
        $class_array[] = $item_class->nid;
    }
    // Count Classes
    $class_count = sizeof($class_array);
    $variables['classes'] = $class_count;
}

```

If I set string values, it's fine. But trying the view gives a 500 error. This code works fine in a tpl file.

# Answer
The theme\_preprocess() function is jused to preprocess EVERY SINGLE template. What you do by now: for EVERY SINGLE template you run a view (I am not sure if it gets chached during to a single page request - so it may be that you run the view a hundred times during one page request). This may hit your servers capabilities.

1.) It is bad practice to run any views in the theme layer. Please assure that on the theme level no data alteration or processing is done any more no matter if done in a preprocess function in template.php or - even worst - in a tpl-file.

2.) Please consider a better place where to add this information by views. Where exactly do you want to add the classes? Which element?
> 0 votes

---
Tags: views, theming
---


# Question
Title: The Mobile theme module conflicts with the default cache
I am using the Mobile theme module in order to load a specific theme in the mobile devices. when I enable caching, the module does not work properly.

More specific, when a page is first visited from a a mobile device for the first time, it will always come up with the mobile theme, even when it is not visited from a mobile device. When a page is visited from a desktop device for the first time, it will always come up with desktop theme even for mobile devices.

# Answer
> 1 votes
I don't think there's a straightforward solution to this in Drupal7 but there are some workarounds available:

1. Use JavaScript to detect and do the switch
2. This issue happens because D7 uses page URL as page's cache id (CID). To distinguish different devices for same page, you'll need to alter the CID somehow so it looks something like CID\_phone, CID\_tablet and CID\_desktop. I used mobile\_detect module before and know there are some patches on this. Do keep in mind there's a side effect that this approach will triple the amount of CIDs in you database table.
3. If you use Varnish you can try something like this

---
Tags: 7, caching
---


# Question
Title: How to fix entity property X doesn't support writing, when setting content type field values?
I've got a D7 content type with a few fields; nothing particularly special. I want to be able to programattically change the values of those fields from time to time, and so wrote a function like so:

```
function set_field_value($field_name, $node, $value) {
    $wrapper = entity_metadata_wrapper('node', $node->nid);
    $wrapper->$field_name = $value;
    $wrapper->save();
}

```

This worked in a few test cases (like changing the title of a blog node), but when I try it on content type fields, I get an error like:

> EntityMetadataWrapperException: Entity property field\_project\_video\_status\_yt doesn't support writing. in EntityStructureWrapper-\>setProperty() (line 497 of ...)

What I'm doing wrong?

# Answer
**Short Answer**: It is not possible to write to that field type using entity metadata wrappers. You may want to raise the issue with the maintainers of the module that provide that field type.

**Long Answer**: The Entity Metadata Wrapper you are using is provided by the Entity Module. This module extends Drupal's entities in various ways. One of the things it offers is to extend the information about fields, by offering it's own hook, hook\_entity\_property\_info. This hook allows, amongst other things, to define a `setter callback`. This is the function that is used by the entity meta data wrapper to set the value of a field or property.

The error you are seeing implies that this function is missing for the field type you are trying to access.

The Entity module itself actually provides a default function for fields that do not define their own `setter callback`. What this means is that :

* Either the module that creates the field you're using implements `hook_entity_property_info` and does not define a `setter callback`; or
* Another module explicitely removes the `setter callback` from the field type you are using.

Either way, you cannot use entity\_metadata\_wrapper for that field type until the issue is resolved. You should raise it with the people who maintain the module providing that field type.
> 5 votes

# Answer
I unfortunately don't have enough reputation to simply comment after Alice perfect answer. I just wanted to add this:

I thought the setter callback default value was set to "entity\_property\_verbatim\_set" so I didn't bother adding this to my properties. It turns out, you still need it to avoid that error.

Thanks Alice!
> 1 votes

---
Tags: 7, entities
---


# Question
Title: How to create a rule that loops the line items of a completed order and do a data comparison on a custom field that's on a product?
I'm trying to create a rule that triggers on the event 'Completing the checkout process' that will then loop through the line items of the order. For each line item I'd like to do a Data comparison on a custom field that's on a commerce product.

This is the rule I created:

```
"LABEL" : "User needs approval for anything over 500",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "entity_has_field" : {
      "entity" : [ "site:current-user:profile-educator" ],
      "field" : "field_borrow_level"
    }
  },
  { "AND" : [
      { "data_is" : {
          "data" : [ "site:current-user:profile-educator:field-borrow-level" ],
          "value" : "need_approval_greater_than_amount"
        }
      }
    ]
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : []
    }
  }
]

```

And this is the component that I was trying to run through the loop:

```
"LABEL" : "Check price of each line item",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_price" ],
"USES VARIABLES" : {
  "current_line_item" : { "label" : "Current Line Item", "type" : "commerce_line_item" },
  "current_product" : { "label" : "Current Product", "type" : "commerce_product" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "current-product" ], "field" : "field_purchase_cost" } },
  { "AND" : [
      { "commerce_price_compare_price" : {
          "first_price" : [ "current-product:field-purchase-cost" ],
          "operator" : "\u003E=",
          "second_price" : { "value" : { "amount" : 50000, "currency_code" : "USD" } }
        }
      }
    ]
  }
],
"DO" : [
  { "drupal_message" : { "message" : "You need School Administrator approval to check out any item valued over $500." } }
]

```

For some more context: This site is a library for special education teachers to be able to check out software and hardware for their use in the classroom. Which means that the price for each item is zero since the site is loaning out items at no cost to the teachers. The hang up in this case is that there are three different ‘borrow levels’ for a teacher. The ‘borrow levels’ are: 1. You can check out any item. 2. You can check out any item up to a $500 value. If an item is above $500 you need approval from your school administrator before the order is approved. 3. You need approval from your school administrator to check out anything.

My question here pertains to users with a ‘borrow level’ of 2. Since the products all have a price of zero we added a custom field to the commerce product that has the replacement cost of an item. So, when an order is placed and the user is borrow level 2 I need to look at each item in that order and determine if the replacement cost is over $500. If nothing is over $500, then the order can be flagged as approved. If there’s one or more items that have a replacement cost of $500 or more we need to send an email to that teacher’s school administrator telling them they need to log in and approve or deny the request the teacher has made.

# Answer
> 0 votes
### First things first ...:

* Your "AND" (in your rule, and in your component) appear to be redundant. If you doubt/wonder about that, have a look at my answer to the question "Which is the difference of combining rules with AND or just leave them follow one each other?". So I'll ignore those already.
* The `list_item` in your Rule (within the loop) is a variable name you get out-of-the-Rules-box. But to improve readability of your Rule, I suggest to rename that to something like `current_line_item` (and description like "Current line item").
* While building (developing) your Rule (and component), I find it a handy facility to start with a rules action like "Display a Message" (which you can find within the "System" group). And for the actual message to be shown, already include tokens that may be interesting to know more about. Typically some "id" and some "description".
* With the above Rule refinements, do some first unit testing, so that at least you get 1 Drupal message for each line item (produced via that Rules Action in your loop).

### Remaining refinement(s):

* Do some research/experiments to see how, starting from your `current_line_item` (my suggested new name for `list_item`!!!) you can find your way to the product the line item is related to.
* You should be especially interested in something that smells, sounds and looks like the "ID" of the product the line item is about. If you think you found it, add that token to your message being displayed (to be sure you have what we should be interested in).
* Assuming you found the product ID somehow, ADD a subsequent Rules action to perform a "fetch entity by ID", to actually fetch the product, with ID ... you guessed it ... the token you found in the previous step.
* From then on, you have everything you need (I think) to add an extra Rules Action to simply perform your Rules Component, passing it the corresponding parameters.
* In the end, when everything works as you want, you may want to remove or refine that "Show a message" Rules Action from before.

**PS 1**: The above is based on the assumption that I don't know "Drupal Commerce" at all ... hm, hm.

**PS 2**: I'm assuming this is about D7, though it will probably also work in a similar way if some day the question is about D8.

---
Tags: commerce, rules
---


title: Unit testing on windows

text:
# Question
Title: Unit testing on windows
I hope this question is not very naive, the problem is that in Drupal 8 there are several unit tests written for modules and I want to test them. But since I am on windows os I am not able to figure out by myself how to run them.Any ideas?

# Answer
Drupal test runner (simpletest) has a few issues on Windows, including the inability to work with contributed database drivers (SQL Server).

As of today, exactly 3 patches are needed for this #2294731, #2748883, #2605284 (can't post the links due to not having reputation here...).

If you want to see a working example, this post explains how to run the Drupal test suite on AppVeyor that is a Windows based Continuous Integration Service.

http://www.drupalonwindows.com/en/blog/continuous-integration-and-testing-drupal-appveyor

There you will find an example cmd/powershell script with all commands needed to setup drupal and run the test suite (on windows) including commands to automatically apply the mentioned patches.
> 1 votes

# Answer
If you have a working development environment set up in Windows you should be able to download Drupal and any contributed projects that you want to test. You can also run tests without having to install the PHPUnit framework on your computer.

### Run a test via Drupal UI

To run tests using the Drupal interface, enable the *Testing* module and go to the configuration page (admin/config/development/testing). Unfortunately as of this writing there is an active issue with running PHPUnit tests this way on Windows1. Fortunately you can also run PHPUnit tests from the command line (see below).

### Run a PHPUnit test from the command line in Windows

1. Open a command line tool (preferably Git Bash shell2)
2. Navigate to the root of your Drupal project (the path will depend on your environment):

```
$ cd c:/wamp/www/myproject

```
3. Run a test. The following runs a PHPUnit test belonging to the core Views module:

```
$ php vendor/phpunit/phpunit/phpunit -c core core/modules/views/tests/src/Unit/Plugin/argument_default/RawTest.php

```

The first path string points to the copy of PHPUnit that comes packaged with Drupal (Drupal also provides a symlink, but it won't work with Windows). The second path string points to the file that contains the test class. `-c core` tells PHPUnit to read the configuration file located in the `core/` folder.

Type `--verbose` or `--debug` after the first path string to get more detailed output.

To access PHPUnit help:

```
$ php vendor/phpunit/phpunit/phpunit --help

```

---

1 Issue #2294731: Simpletest fails to run PHPUnit on Windows and in extracted tarballs of Drupal

2 Git Bash shell is packaged with Git for Windows

### UPDATES

Path to PhpUnit executable has changed from `core/vendor/phpunit/phpunit/phpunit` to `vendor/phpunit/phpunit/phpunit`. (2015-10-29)
> 0 votes

---
Tags: testing
---


title: How to configure XHProf on windows?

text:
# Question
Title: How to configure XHProf on windows?
With the help of Lorenzo Alberton tutorial, i get XHProf installed for drupal 6 on linux server. Now i need to get it installed on windows but i found that XHProf cant be installed on windows. Additionally, at drupal.org XHProf, is available for drupal 7 onwards. If anyone has installed XHProf for drupal 6 on windows then please share.

# Answer
> 7 votes
The only ***easy*** way I know of doing this on windows is with quickstart. You will need virtual box to run it, but it has xhprof & xdebug installed and pre-configured, along with many other goodies (editors, drush commands for quick setups of new projects, etc.

There is a video here explaining the procedure, and plenty of docs on the project page

Supports drupal 6 & 7. Great stuff, I have been using this every day for a good while now.

Hope that helps, good-luck!

# Answer
> 9 votes
I just finally installed the `XHProf` profiler under `Windows7 x64 - PHP 5.3.x`. Assuming that you have a functional PHP environment, this checklist should work for you too:

* Download the pre-compiled XHProf 0.10.3 - PHP 5.3 VC9 NTS binary.
* Paste the downloaded `dll` file to PHP extensions directory.
*(You can find the directory path in `extension_dir` directive of `php.ini` file.)*
* Append `extension=php_xhprof.dll` directive to the `php.ini`.
* Restart the web server and search`phpinfo()` output for `XHProf`. found? done!
* You might also want to use `XHGui` fork instead of the built-in UI.

# Answer
> 3 votes
See and follow this issue queue http://drupal.org/node/1011108. It does contain a link to download XHProf compiled as a .dll for Windows.

As for installation, see http://drupal.org/node/1421598.

# Answer
> 2 votes
Please, know that the XHProf extension is **abandoned**.

There is an open source (and free) alternative that is maintained and will work in Windows and Linux called Tideways.

This extension (Tideways) is a FORK of XHprof so it produces compatible output and is able to work with all XHprof compatible tools.

All details explained here:

http://www.drupalonwindows.com/en/blog/profiling-drupal-xhprof-uprofiler-tideways-php7-linux-and-windows

Download and enable the Tideways PHP like any other extension. Updated windows binaries to be found here (https://ci.appveyor.com/project/tideways/php-profiler-extension/history

After that my recommendation is to use the Tideways cloud service, or if you are bankrupt, use any do-it-yourself XHProf compatible tools such as XHGui.

---
Tags: debugging
---


# Question
Title: Print user uploaded logo in twig template
How can I print a user uploaded logo (via the theme appearance UI) in a twig template?

For example, in `block--system-branding-block.html.twig` we can use

```
Available variables:
- site_logo: Logo for site as defined in Appearance or theme settings.

  <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />

```

What do I need to do to make that variable (or a custom variable) available to another twig template, like `menu.html.twig`?

I have found many solutions, but all them involved hardcoding the logo file name or location, both of which are obviously not user friendly.

# Answer
All of you need to do is to **Add New Regions to your Theme** like `logo_region` and then print the site logo on desired twig template with below code:

```
{% if logo_region %}
  <div class="my-style">
    {{ page.logo_region }}
  </div>
{% endif %}

```

And finally enable/place your site brand in created region (logo\_region) on **Block layout** page:`admin/structure/block`
> 2 votes

---
Tags: 8, theming
---


title: Drush 8.1.2 is not working on Windows

text:
# Question
Title: Drush 8.1.2 is not working on Windows
I have installed Drush 8.1.2 on Windows 7, but it doesn't work. Few command are working, but few are not working.

* `drush uli 1` works
* `drush dl <project name>` works
* `drush en <project name>` doesn't work
* `drush cc all` doesn't work

Running `drush en "module name"`, I get the following:

> Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. The drush command 'en fieldupdate' could not be executed.
> Drush was not able to start (bootstrap) the Drupal database.
> Hint: This may occur when Drush is trying to:
>
> * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
> * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.
>
> Drush was attempting to connect to:
> Drupal version : 7.34
> Site URI : http://default
> Database driver : mysql
> Database hostname : localhost
> Database port :
> Database username : root
> Database name : staticpages
> PHP configuration : C:\xampp\php\php.ini
> PHP OS : WINNT
> Drush script : C:\Users\ins237\AppData\Roaming\Composer \vendor\drush\drush\drush
> Drush version : 8.1.2
> Drush temp directory : C:/Users/ins237/AppData/Local/Temp
> Drush configuration :
> Drush alias files :
> Drupal root : C:\xampp\htdocs\cms-staticpages
> Drupal Settings File : sites/default/settings.php
> Site path : sites/default

# Answer
> 1 votes
Looks like your database cannot be contaced, run `drush status` to make sure of that. If that's the issue, then you should update your settings.php files with the correct ip, I guess 127.0.0.1 for your xampp stack.

Not an answer to your question, but running PHP/Drupal on Windows is just asking for problems. You should look into Vagrant or Docker to run your Drupal sites on Windows, that will save you a lot of pain in the long run AND will make it easier to deploy your sites later on.

# Answer
> 0 votes
You should take a look at the \**Drupal Console project.\*

Drupal Console is abstracted on top of Symfony and such an abstraction provides better cross-platform compatibility.

In this post you can find example commands to completely setup a Drupal installation from console on Windows (without Linux bash, real Command line or Powershell scripts):

http://www.drupalonwindows.com/en/blog/continuous-integration-and-testing-drupal-appveyor

The sample commands there include:

* Setting up a code base from scratch using Composer
* Installing the website from the command line using "drupal install" command.
* Enabling/downloading modules using composer and the "drupal module:install" command.
* Running drupal tests from the console

> Not an answer to your question, but running PHP/Drupal on Windows is just asking for problems.

It depends on your budget.

If you are doing brochureware/low budget, you are better off not even setting up an environment at all and looking a Platform.sh, Acquia, Pantheon, etc.

Indeed, Wordress is a much better product for such scenarios (low budget/quickies).

---
Tags: drush
---


title: How do I access field data in Twig?

text:
# Question
Title: How do I access field data in Twig?
I have a list field for a custom block type that looks like this:

```
left|Align left
right|Align right

```

I can access the key in Twig by doing something like this:

```
{% block content %}
  {{ content.field_align }}  {# outputs 'right' #}
{% endblock %}

```

However, if I do a simple comparison, it outputs `FALSE`.

```
{{ kint(content.field_align == 'right') }}

```

The following code returns `TRUE`.

```
{{ kint(content.field_align['#items'].getValue()|first.value == 'right') }}

```

Is there a shorter version for getting the "real" string so I can use Twigs string filters and keep it tidy?

# Answer
`content` contains the render arrays based on the configured formatters.

If you want to access the actual values, you want to access them through the entity object. Usually, that is available already to your template, for example `node`. For your case, it is a bit special because the block\_content is rendered in the block content without its own template, so you have to make it available yourself in a `yourtheme_preprocess_block($variables)` like this:

```
if (isset($variables['elements']['content']['#block_content'])) {
  $variables['block_content'] = $variables['elements']['content']['#block_content'];
}

```

Then, you can access a field value with `block_content.field_name.property`. So in your case, `block_content.field_align.value`. The property is `value` for most field types, for references, you can either use `target_id` for the ID or `entity` for the referenced entity object. Yes, you can directly access fields on that, but make sure to always check that a reference exists otherwise you can end up with fatal errors or exceptions. To access the label of a term reference for example, you can access it as `block_content.field_tags.entity.name.value`.

If you don't specify the field delta, it defaults to the first. If you want to access a different delta, you can use `entity.field_name.1.value`and so on. You can also loop over them.

This all maps directly to PHP, you can also do `$block_content->field_tags->entity->name->value` in preprocess and other places where you have the block\_content.
> 16 votes

# Answer
Here's an alternative, template only way which allows you to render a render array and check its value (allows checking the variable as if you were printing it, because printing in Drupal 8 Twig automatically renders variables that are render arrays):

```
{{ kint(content.field_align|render == 'right') }}

```

Or another option to save the extra render if you're printing the variable later:

```
{% set field_align = content.field_align|render %}
{{ kint(field_align == 'right') }}

{{ field_align }}

```
> 6 votes

# Answer
You can use **Twig Field Value** module in this case. It allows to get partial data from field render arrays. For ex. content.field\_name|field\_value -get value of field. You can use it in IF statement
> 2 votes

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


# Question
Title: How to set custom user view mode for comments
How do I control which view mode of a user account appears on different pages?

I have a Compact user view mode with two fields I want to appear in forum posts and comments. I then have a more complete user view mode I would like to have appear on the users home page and eventually i would like a different view mode for article bylines.

I cannot, for the life of me though, figure out how to actually have any of these display.

I want to modify the layout of user.html.twig for the user home pages to have additional headings and information. But then it gets used wherever the user entity appears. Am I suppose to create specific twig templates for every user appearance or is there some more sensible way to control the fields that appear?

I tried accessing specific user entity fields and styling them in templates such as `node--forum.html.twig` but I can only seem to access the complete user entity with `{{ author_picture }}` \- why is it named that if it is the entire entity? or the user name with `{{ author_name }}`

How do I do this?

# Answer
The variables `{{ author_picture }}` and `{{ author_name }}` are prepared in preprocess in the hook template\_preprocess\_node(). You can modify these variables or add your own in a custom preprocess hook.

Or you can make the field `uid` configurable in UI by modifying the field definition in the node entity:

**mymodule.module**

```
function mymodule_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->id() == 'node') {
    if (isset($fields['uid'])) {
      $fields['uid']->setDisplayConfigurable('view', TRUE);
    }
  }
}

```

and you'll find the *Authored by* field in the *Manage Display* page, where you can configure how the referenced user entity is formatted (which view mode is used).

A third and IMHO perferable option is to use the module Display Suite.
> 1 votes

---
Tags: theming, 8
---


# Question
Title: Looking for Acquia Dev Desktop database settings
I am using Acquia Dev Desktop to create local Drupal installations. I am also using Bluehost as a service. Unfortunately, Bluehost uses table prefixes for Drupal tables.

So, if I import something locally from BlueHost, I need to set a table prefix in the `settings.php`:

```
array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'port' => 3306,
  'prefix' => 'myprefix_',
  'collation' => 'utf8_general_ci',
);

```

Unfortunately, I can't find the proper database settings for the local Acquia MySql database. Acquia does not create a `setting.php` file on fresh systems too.

Does anyone know those settings? Thanks.

# Answer
> 3 votes
After digging this issue in details, it turns out that the answer to my question is:

```
  $databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'TheDBNameIChoose',
    'username' => 'drupaluser',
    'password' => '',
    'host' => '127.0.0.1',
    'port' => 33066 );

```

In fact, Acquia Dev Desktop does automatically generate a `setting.php` file in the Public file system path (see Home \> Administration \> Configuration \> Media)

# Answer
> 11 votes
In the case of Windows 8, Acquia Dev Desktop 2 generates the settings file in this location:

```
C:\Users\\[user]\\.acquia\DevDesktop\DrupalSettings\loc_Testing_local.inc

```

# Answer
> 6 votes
If you want to know where Acquia Dev Desktop save settings go to your `settings.php` and paste:

```
die($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']);

```

Or as @Cameron mentioned in comment it’s better use `drush` if it is installed:

**So**

```
drush php-eval 'echo $_SERVER["DEVDESKTOP_DRUPAL_SETTINGS_DIR"]'

```

Then you can find where Acquia saved thie file

As example in Windows 8 in:

```
C:\Users\[user]\.acquia\DevDesktop\DrupalSettings\loc_Testing_local.inc

```

And in Mac or (Linux) in:

```
/Users/[yourusername]/.acquia/DevDesktop/DrupalSettings

```

# Answer
> 2 votes
acquia creates this:

```
///////////////////////////////////////////////////////////////////////
//             Don't edit anything below this line!                  //
// This section is autogenerated by Acquia Dev Desktop Control Panel //
///////////////////////////////////////////////////////////////////////
//<@@ADCP_CONF@@>
$base_url = 'http://testing.pt:8082';

//D6 DB config
$db_url = 'mysqli://drupaluser@127.0.0.1:33066/acquiaperfumearte';

//D7 DB config
if( !isset($databases) )
      $databases = array();
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'acquiaperfumearte',
    'username' => 'drupaluser',
    'password' => '',
    'host' => '127.0.0.1',
    'port' => 33066 );
//</@@ADCP_CONF@@>

```

# Answer
> 1 votes
If I understand you right you're looking for the "standard" `settings.php` file to drop into a fresh local installation of Acquia?

If so you can just copy `sites/default/default.settings.php` to `sites/default/settings.php`, copy the database information from the `settings.php` file in your remote installation and tweak the database array to use your local MySQL server.

If you can't find the default settings file, just grab a copy of Drupal and use the one from there. Acquia is essentially a Drupal core with some extra contributed modules and a different install profile so they're interchangeable.

Sorry if I've mis-understood.

# Answer
> 0 votes
I wrestled with this myself. All the videos, instructions, etc say modify that part of the settings.php but when I looked in sites/default/settings.php all I found was a bunch of "\*" and lots of directions. In that code there was the

if( !isset($databases) ) $databases = array(); $databases\['default'\]\['default'\] = array( 'driver' =\> 'mysql', 'database' =\> 'databasename', 'username' =\> 'drupaluser', 'password' =\> '', 'host' =\> '127.0.0.1', 'port' =\> 33066 );

I think there is a line for "prefix" as well.

What I found was that in the sites/devdesktop/site-name/sites/ directory is a shortcut (I think that is what the little arrow means) which includes a file called "settings.php". THIS settings.php had the non-astericked code lines defining database and user as highlighted in every video tutorial and directions that I read.

After modifying this settings.php, i was able to get my site (partly) working. The other part is dealing with the .htaccess file(s) of which I have not completely fixed.

Wanted to share this as it may help someone / prevent someone from searching for the proper settings.php using aquia devdesktop.

Certainly a bit of a pain - but it seems that acquia is adding their own customization to the core drupal setup so to make it very easy for you to use THEIR cloud services, and certainly made if very difficult for me to figure out what needed to be changed for my site to Godaddy.

# Answer
> 0 votes
`$ cat ~/.acquia/DevDesktop/DrupalSettings/cld_environment_mysitename.inc`

Look for a .acquia directory in your home directory. It contains credentials for each site in files prefixed with cld\_ within subdirectory .acquia/DevDesktop/DrupalSettings

Note that this directory is typically hidden, so you'll need to show hidden files in your home directory. One approach is to use a Terminal emulator to read the contents; files are short.

---
Tags: 7, database, configuration
---


title: How do I make a withdrawal?

text:
# Question
Title: How do I make a withdrawal?
I'm implementing a site where users pay for submissions and reviewers get paid. Drupal Commerce with Commerce Credits allows me to buy credits using Paypal and to pay on site with credits for submitting content.

Reviewers receive credits for performing the review, when they reach a certain amount I want them to offer the possibility to withdraw credits through Paypal.

I had a look at modules like Commerce Funds (broken) and Commerce-Marketplace (withdrawal not implemented yet) and Paypal Adaptive Payments (not public anymore), did I miss anything?

Is there anything I can do to automatize this process with rules? I could transfer credits to a withdrawal user account and manually make the transaction with Paypal. Any hints how to automatize this process and trigger a Paypal payment to users credit card?

# Answer
> 2 votes
I suppose this can be done, but it won't be easy. There will be quite some components and you will have to write some code. Disclaimer is that I have not tested anything of this code, but I hope this to be useful to you.

This example is based on the `commerce_funds_withdraw_action()` on line 932 of the Commerce Funds Withdraw Module, part of Commerce Funds.

Most important is this part, which performs the actual transfer using PayPal Mass Pay (Read the integration guide for details about PayPal business accounts and contacting customer support to enable the feature.):

```
$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {
  $withdraw->status = 'Transfered';
  $amount_paypal = $withdraw->amount;
  $withdraw->amount = commerce_currency_decimal_to_amount($withdraw->amount, $withdraw->currency_code);
  commerce_funds_withdraw_save($withdraw);
  $amount = array(
    'amount' => $amount_paypal,
    'currency_code' => $withdraw->currency_code,
    'reference' => $withdraw->uid,
  );
  commerce_funds_debit(user_load($withdraw->uid), $amount);
  drupal_set_message(t('Money were successfully transferred to @user_email.', array('@user_email' => $user->mail)), 'status');
}

```

If we remove all commerce funds transaction tracking, we are left with:

```
$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {

  // Deduct credits from the account here, or do it in Rules later.

  drupal_set_message(t('Money was successfully transferred'), 'status');
}

```

The actual communication with the API is handled by `commerce_paypal_api_request()`, a function of the Commerce PayPal module, which requires 2 parameters;

* `$payment_method`: The payment method instance array associated with this API request.
* `$nvp`: The set of name-value pairs describing the transaction to submit. (See MassPay API Using NVP of the API documentation.)

Since there is no offical payment method to use, we create a custom payment method option:

```
$payment_method = array(
  'settings' => array(
    // Fill these to match the data configured with PayPal
    'server' => '',
    'api_username' => '',
    'api_password' => '',
    'api_signature' => '',
    'log' => array(
      'request' => FALSE, // Log outgoing request TRUE/FALSE.
      'response' => FALSE, // Log response from PayPal TRUE/FALSE.
    ),
  ),
);

```

And the NVP:

```
$nvp = array(
  'METHOD' => 'MassPay',
  'EMAILSUBJECT' => 'Withdraw',
  'CURRENCYCODE' => $currency_code,
  'RECEIVERTYPE' => 'EmailAddress',
  'L_EMAIL0' => $receiver_email,
  'L_AMT0' =>  $amount,
);

```

Now for getting this all together in a custom module and a Rules actions:

Create a `rules_paypal_deposit` folder for your module, with the following files:

rules\_paypal\_deposit.info:

```
name = Rules PayPal Deposit
description = Deposit funds to a paypal account using rules.
core = 7.x
dependencies[] = rules
dependencies[] = commerce_paypal

```

rules\_paypal\_deposit.module:

```
<?php
/*
 * This function performs the actual transfer
 */
function rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code) {
  $payment_method = array(
    'settings' => array(
      // Fill these to match the data configured with PayPal
      'server' => '',
      'api_username' => '',
      'api_password' => '',
      'api_signature' => '',
      'log' => array(
        'request' => FALSE, // Log outgoing request TRUE/FALSE.
        'response' => FALSE, // Log response from PayPal TRUE/FALSE.
      ),
    ),
  );

  $nvp = array(
    'METHOD' => 'MassPay',
    'EMAILSUBJECT' => 'Withdraw',
    'CURRENCYCODE' => $currency_code,
    'RECEIVERTYPE' => 'EmailAddress',
    'L_EMAIL0' => $receiver_email,
    'L_AMT0' =>  $amount,
  );

  $response = commerce_paypal_api_request($payment_method, $nvp);
  if($response['ACK'] == 'Success') {

    // Deduct credits from the account here, or do it in Rules later.

    drupal_set_message(t('Money was successfully transferred'), 'status');
  }
}

```

rules\_paypal\_deposit.rules.inc:

```
<?php
/**
 * Implement hook_rules_action_info()
 */
function rules_paypal_deposit_rules_action_info() {
  $actions = array(
    'rules_paypal_deposit_actions_deposit' => array(
      'label' => t('Transfer funds to a PayPal account'),
      'group' => t('Rules PayPal Deposit'),
      'parameter' => array(
        'receiver_email' => array(
          'type' => 'text',
          'label' => t('E-mail to transfer to.'),
        ),
        'amount' => array(
          'type' => 'decimal',
          'label' => t('Amount to transfer (format: 12.34)'),
        ),
        'currency_code' => array(
          'type' => 'text',
          'label' => t('3 Letter currency of the transfer, see <a href="@url">the PayPal documentation</a>', array('@url' => url('https://developer.paypal.com/docs/classic/mass-pay/integration-guide/currency_codes/'))),
        ),
      ),
    ),
  );
  return $actions;
}

/**
 * The action for rules_paypal_deposit_actions_deposit
 */
function rules_paypal_deposit_actions_deposit($receiver_email, $amount, $currency_code) {
  rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code)
}

```

You can choose to add the PayPal API settings `server`, `api_username`, `api_password` and `api_signature` as Rules parameters as well and add the parameters to `rules_paypal_deposit_actions_deposit()` and `rules_paypal_deposit_do_deposit()`. Or just define them in the code.

---

I really hope this is of use to you. It was written in a bit of spare time because I thought it was a nice puzzle. Do not get mad if it doesn't work ;)

Obviously this needs proper testing on the PayPal API sandbox first.

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


title: Using #states visible

text:
# Question
Title: Using #states visible
I am trying to make field\_format visible after two select list fields have a specific values selected. I thought be not using 'or' 'xor' that both are required but its not working. this is doing the same thing as using 'or',

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form') {
    $form['field_format']['#states'] = array(
      'visible' => array(
          array(':input[name="field_item_type[und]"]' => array('value' =>     'tv_show')),
          array(':input[name="field_extra[und]"]' => array('value' =>     'bike')),
      ),
    );
  }
}

```

# Answer
Here is some example code. Maybe your selector is incorrect?

```
$form['main']['elem1'] = array(
  '#type' => 'select',
  '#title' => t('1'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);
$form['main']['elem2'] = array(
  '#type' => 'select',
  '#title' => t('2'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);

$form['main']['elem3'] = array(
  '#type' => 'textfield',
  '#value' => t('3'),
  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="elem1"]' => array('value' => 'A')),
      // XOR.
      array(':input[name="elem2"]' => array('value' => 'A')),
    ),
  ),
);
$form['main']['elem4'] = array(
  '#type' => 'textfield',
  '#value' => t('4'),
);
$form['main']['elem5'] = array(
  '#type' => 'textfield',
  '#value' => t('5'),
  '#states' => array(
    'visible' => array(
      ':input[name="elem1"]' => array('value' => 'A'),
      ':input[name="elem2"]' => array('value' => 'A'),
    ),
  ),
);

```

And then the alter function.

```
function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'af_aam_aam_form') {
    $form['main']['elem4']['#states'] = array(
      'visible' => array(
        array(':input[name="elem1"]' => array('value' => 'A')),
        // OR.
        array(':input[name="elem2"]' => array('value' => 'A')),
      ),
    );
  }
}

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: Getting hook_form_FORM_ID_alter to work with #ajax callback
**Note:** There is some information here that may be extraneous, because I started with a broader question. I still think the context might help so I'm leaving the detail in. Feel free to skip to The Code and The Question though, and come back for the detail.

### The Detail

I have a node form that has a boolean field, and a multivalue field collection field that contains a multivalue field collection field, that contains a boolean field. Since that makes little sense, let me try to diagram it. (There are of course other fields, but these are the relevant ones)

`field_mr_home_leave - boolean - single value
field_mr_fc_itineraries - field collection - unlimited values
 |--- field_mr_fc_legs - field collection - unlimited values
 |--- field_mr_fc_leg_home_leave - boolean - single value`

I'm sorry the names here are a little confusing, please note one of the home\_leave fields has fc\_leg in the prefix. The home leave field deeper in the hierarchy is the ones) I want to be dependent on the value of the home\_leave field at the top level.

Because conditional fields does not give me the option of making sub fields of a field collection dependent on the value of a field in the parent form (if it does, please tell me how), I want to write code in my custom module to alter the form so that when the value of `field_mr_home_leave` is set to 1, `field_mr_fc_leg_home_leave` is visible, and when `field_mr_home_leave` is set to 0 `field_mr_fc_leg_home_leave` is invisible.

In terms of the form, if the parent boolean is set to Yes (1), I want to see any boolean fields in the sub sub field collection. If it is set to No (0) they should not show up.

### The Code

The form has an id of `mission_request_node_form` and my module is called `missions`. Here is the code I have so far:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  $form['field_mr_home_leave'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'missions_hide_home_leave_toggle',
    'wrapper' => 'itinerary-section',
    'effect' => 'slide',
  );
  $form['field_mr_fc_itineraries']['#prefix'] = '<div id="itinerary-section">';
  $form['field_mr_fc_itineraries']['#suffix'] = '</div>';
  if ((!empty($form_state['values']['field_mr_home_leave']) && $form_state['values']['field_mr_home_leave'] == 1) || (empty($form_state['values']['field_mr_home_leave']) && $form['field_mr_home_leave'][LANGUAGE_NONE]['#default_value'] == 1)) {
    $home_leave_toggle_access = true;
  } else {
    $home_leave_toggle_access = false;
  }
  foreach ($form['field_mr_fc_itineraries'][LANGUAGE_NONE] as $key => &$itinerary) {
    if (is_integer($key)) {
      foreach ($itinerary['field_mr_fc_legs'][LANGUAGE_NONE] as $key => &$leg) {
        if (is_integer($key)) {
          $leg['field_mr_fc_leg_home_leave']['#access'] = $home_leave_toggle_access;
        }
      }
    }
  }
  $form_state['rebuild'] = TRUE;

}

function missions_hide_home_leave_toggle($form, $form_state) {
  dpm('testing');
  return $form['field_mr_fc_itineraries'];
}

```

I'm adding the #ajax array to the parent boolean field and then testing to see what the value of the field is. I then set the #access value of any sub booleans present. This works on first run, the parent boolean defaults to 0 and so the initial sub boolean field is hidden. Unfortunately, then I change the value of the parent boolean, the ajax spinner triggers, but with a breakpoint set in my IDE in the callback function I never see any evidence that the callback is called. What can I do to get the change to trigger the callback.

### What else I've tried

I thought maybe, since the subfield is not a required field, perhaps I could just hide it using the `#states` attribute. This worked great until the moment I added another leg to the itinerary, at which point the subfield showed up on each leg, and I had to toggle the value of field\_mr\_home\_leave to get the fields to be hidden again.

Here's the code for that:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  foreach ($form['field_mr_fc_itineraries'][LANGUAGE_NONE] as $key => &$itinerary) {
    if (is_integer($key)) {
      foreach ($itinerary['field_mr_fc_legs'][LANGUAGE_NONE] as $key => &$leg) {
        if (is_integer($key)) {
          $leg['field_mr_fc_leg_home_leave']['#states'] = array(
            'visible' => array(
              ':input[name="field_mr_home_leave[und]"]' => array('value' => '1'),
            ),
          );
        }
      }
    }
  }
}

```

I tried deleting dependencies on the same field in conditional fields, then disabled conditional fields entirely to no avail.

I've tracked this down to `form_get_cache()` failing to return a cached form. I note that nothing is being cached for this form.

### Newest Update

I probably need to rewrite this question to be more concise, but here is what I've found: The cache\_form table is never written to. I've simplified this as far as I can. I started with a clean drupal install on Acquia Dev Desktop, I installed my module, and created a content type that just contains the field and subfield at the same level so I don't have field collections or anything else to worry about.

Here is my latest code:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  $form['field_mr_home_leave'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'missions_hide_home_leave_toggle',
    'wrapper' => 'itinerary-section',
    'effect' => 'slide',
  );
  $form['field_mr_fc_leg_home_leave']['#prefix'] = '<div id="itinerary-section">';
  $form['field_mr_fc_leg_home_leave']['#suffix'] = '</div>';
  if ((!empty($form_state['values']['field_mr_home_leave']) && $form_state['values']['field_mr_home_leave'] == 1) || (empty($form_state['values']['field_mr_home_leave']) && $form['field_mr_home_leave'][LANGUAGE_NONE]['#default_value'] == 1)) {
    $home_leave_toggle_access = true;
  } else {
    $home_leave_toggle_access = false;
  }
  dpm($form);
  $form['field_mr_fc_leg_home_leave']['#access'] = !$home_leave_toggle_access;
  $form_state['rebuild'] = TRUE;

}

function missions_hide_home_leave_toggle($form, $form_state) {
  return $form['field_mr_fc_leg_home_leave'];
}

```

When I click the checkbox on field\_mr\_home\_leave I see the ajax spinner go, and I see a request to /system/ajax go out. Nothing but headers come back. The log shows `Invalid form POST data.` which is an error that means it couldn't find a cached form. Am I missing a step to make sure the form gets cached? Is #access the wrong thing to manipulate?

# Answer
> 1 votes
With thanks to @jaypan for trying to help me figure this out. I finally have a solution! Googling for the error message I was getting `Invalid form POST data` led me to lots of other issues people were having, but not the one I was having. My problem was very simple! I should not have been setting `$form_state['rebuild']` to `TRUE`.

Doing that caused `form_set_cache()` to never be called, and therefore for drupal to quietly (with a watchdog entry) bail out of the ajax call and not return a response beyond the headers.

After ajax started working I was able to determine that the variable I was using to check the value of the field was wrong too, and I was not checking for cases such as the add another item buttons where some other portion of the form was being submitted. Now that I've fixed that, it all works. Here is the working code:

```
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function missions_form_mission_request_node_form_alter(&$form, &$form_state, $form_id)
{
  $form['field_mr_home_leave'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'missions_hide_home_leave_toggle',
    'wrapper' => 'itinerary-section',
  );
  $form['field_mr_fc_itineraries']['#prefix'] = '<div id="itinerary-section">';
  $form['field_mr_fc_itineraries']['#suffix'] = '</div>';
  if ((!empty($form_state['values']['field_mr_home_leave']) && $form_state['values']['field_mr_home_leave'][LANGUAGE_NONE][0]['value'] == 1) || (empty($form_state['values']['field_mr_home_leave']) && $form['field_mr_home_leave'][LANGUAGE_NONE]['#default_value'] == 1) || (!empty($form_state['complete form']['field_mr_home_leave']['und']['#value']) && $form_state['complete form']['field_mr_home_leave']['und']['#value'] == 1)) {
    $home_leave_toggle_access = true;
  } else {
    $home_leave_toggle_access = false;
  }
  foreach ($form['field_mr_fc_itineraries'][LANGUAGE_NONE] as $key => &$itinerary) {
    if (is_integer($key)) {
      foreach ($itinerary['field_mr_fc_legs'][LANGUAGE_NONE] as $key => &$leg) {
        if (is_integer($key)) {
          $leg['field_mr_fc_leg_home_leave']['#access'] = $home_leave_toggle_access;
        }
      }
    }
  }

}

function missions_hide_home_leave_toggle($form, $form_state) {
  return $form['field_mr_fc_itineraries'];
}

```

I hope this helps someone else not spend 3 days trying to debug this. :(

---
Tags: 7, ajax
---


# Question
Title: How do I avoid the error "out of memory"?
I'm currently working with Drupal 7, and I've the following modules installed, all updated to their respective last version:

* Views - 7.x-3.0-beta3
* CTools - 7.x-1.0-alpha4
* Panels - 7.x-3.0-alpha3
* Rules, ACL, Advanced forum, Forum Access, User Points, BUEditor

I keep getting "PHP Fatal Error: Out of memory." My server's limit is at its maximum allowed by my provider (32 MB). Those errors appears mostly when interacting with the modules page, but it's also appearing for any user who tries renewing his password, or editing nodes.

Thus, would you have any advice on how to lower the memory usage?

P.S.: I've noticed most of those errors include views and views plugins .inc files. But it also concerns .inc files from the core modules and system... I could copy some there if you want me to.

# Answer
> 6 votes
There's really not much you can do in this case. Drupal 7 requires fair bit of memory and so do Views, Panels, etc.

If upgrading to a hosting plan where you have at least 128MB is not an option I would at least make sure the following modules are kept disabled:

* Update Manager
* Database Logging
* Field UI
* Views UI
* Panels In-Place Editor
* Any other "UI" module

Do your development locally and use version control & Features to update your production box.

# Answer
> 4 votes
As listed in Drupal's System Requirements, Drupal Core itself needs 32M to run. Adding any contributed modules without increasing memory is a surefire way to encounter this error.

If your server's maximum is only 32M, it's time to get new hosting.

# Answer
> 2 votes
As mentioned, the bottom line is you realistically need 128M. Another point of note is that if you have the image suite working, that frequently reminds us (in Drupal 6 at least) that at least 96M is required in certain circumstances.

32M is just not going to cut it.

# Answer
> 0 votes
I think using the Views module is your biggest problem.

Rewrite all pages that use views with custom queries, remove the views module and whilst we are about it also remove Rules (again, move all logic to code) and your memory usage will drop right down.

Also just writing template files and using preprocess hooks will remove the need for Panels saving yet more memory.

These are not easy or quick steps to take and require an intimate knowledge of Drupal, MySql and PHP however if performance is the number one priority this is the best solution (and will run on 32M of memory).

---
Tags: performance
---


# Question
Title: Alternatives to Commerce Coupon / Discount
I need to add coupon codes for a e-com shop built using Drupal Commerce, and have been playing with Commerce Coupon and Commerce Discount modules, but I can't seem to fix the problem of coupons being removed during checkout. This has been reported many times (see issues below), with various supposed fixes but I've tried everything and nothing works.

So, is there any alternative for this kind of functionality?

I really only need discounts on full orders (instead of products) but do need both percentage and fixed price options.

Alternatively if anyone has a real fix for the issue please let me know!

Issues for reference:

https://www.drupal.org/node/2619448

https://www.drupal.org/node/2328357

https://www.drupal.org/node/2464525

# Answer
> 0 votes
Both of those modules have caused me headaches, however I know of no alternative.

In order to fix the bug you need to ideally step through Commerce Coupon and Commerce Discount's implementation of `commerce_cart_order_refresh` and `commerce_cart_line_item_refresh`.

Line items kept getting deleted for me when they didn't have a properly formatted price.

By implementing my own `commerce_cart_line_item_refresh` I was able to fix any problems with line items before their code ran.

If I was to do a discount / coupon system again and the spec was not too complex I would be tempted to write something from scratch as both of those modules are suffering from a bit of bloat.

---
Tags: 7, commerce
---


# Question
Title: Fatal error: Call to undefined function entity_view_mode_prepare() /sites/all/modules/field_collection/field_collection.entity.inc on line 600
I get this error as I was doing my work. How do I fix this fatal error?

> Fatal error: Call to undefined function entity\_view\_mode\_prepare() in .sites/all/modules/field\_collection/field\_collection.entity.inc on line 600

# Answer
> 1 votes
This error has been removed in latest drupal 7 versions. Please upgrade your drupal core version to the latest.

OR
Temporary solution: Copy and paste the below function in includes/common.inc file

```
function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}

// To ensure hooks are never run after field_attach_prepare_view() only
// process items without the entity_view_prepared flag.
$entities_by_view_mode = array();
foreach ($entities as $id => $entity) {
$entity_view_mode = $view_mode;
if (empty($entity->entity_view_prepared)) {

  // Allow modules to change the view mode.
  $context = array(
    'entity_type' => $entity_type,
    'entity' => $entity,
    'langcode' => $langcode,
  );
drupal_alter('entity_view_mode', $entity_view_mode, $context);
}

$entities_by_view_mode[$entity_view_mode][$id] = $entity;
}

return $entities_by_view_mode;
}

```

---
Tags: entities
---


# Question
Title: Custom widget not rendered within field group
I wrote a custom module that adds a widget. This widget consists of multiple textfields and an ajax button that sends that information to an external service and gets in return and identifier that is stored locally.

However, it is not possible to render this widget within a group. (Using the field group module) When adding it to a content type it will never be rendered within a group (as a fieldset, a tab, div or whatever), but instead before or after it.

My custom fields within the widget are bundled together by:

```
$form['fieldset']['field_name1']
$form['fieldset']['field_name2']

```

But even when they are not put together as a fieldset, it doesn't work.

How come?

Here is a code snipped of the definition of the fieldset:

```
$form['b2share_fieldset'] = array(
  '#type'  => 'fieldset',
  '#title'  => t('Publish data on B2Share'),
  '#collapsible'  => TRUE,
  '#collapsed' => FALSE,
  '#tree'  => TRUE,
);

$form['b2share_fieldset']['database_field_name'] = array(
   '#type'  => 'hidden',
   '#default_value'  => $b2share_fieldname,
);

```

The complete module can be found here.

I want to emphasize that my widget works fine. It's just always displayed outside the fieldgroup even when it is placed within the fieldgroup. Declaring it as a container as described here doesn't work either.

I also tried the patch provided here, but without success.

Also when I remove the fieldgroup and just leave the fields in there, they are always rendered outside the parent element.There aren't any status or error messages either.

I actually want to publish this as a contributed module, so I'd appreciate any help as I want to get rid of this bug, before I do that.

The problem is also described here.

# Answer
> 0 votes
OK. I finally found the problem based on the example code here. The problem was that I constantly used "form" instead of element. Once I had replaced that the rendering was correct.

`$form['b2share_fieldset']`

instead of `$element['b2share_fieldset']`

However, the huge downside is that now I don't know how to access the field information as $form\_state isn't working anymore.

EDIT: After applying some minor changes in the code I can confirm that this approach works. The fully functional code can be seen on github.

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


# Question
Title: Restrict media files to other users once uploaded
I'm using Media Entity Browser to let users add new or existing media files in a content type.

I have two groups. Business-A uploaded an image in a content. Business-A can re-use the image in writing other contents but Business-B should not be able to add it as an existing media for their own article.

I want that *only* a group can get access to its uploaded media. Because when I upload images using media browser, in default, all files get public accessed.

How can I restrict uploaded media files be added by other users.

# Answer
> 1 votes
Okey, it seems that view filter criteria is not the proper way to achieve this goal.

Contextual filter did the trick.

I added:

1. Contextual filter of Media: Publisher ID
2. Under WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide default value
3. Type: User ID from logged in user

Thanks to @mccrodp for helping out.

# Answer
> 1 votes
If you have Groups on your site with grouped access permissions, I would recommend using the Group module for less complex group permissions like this and OG for configuring more involved group permissions.

Using the Group module you will be able to section off the media and other content like this.

**EDIT:** I suggest you configure Group functionality / permissions directly on the File / media entity, rather than just the nodes they are added / used from. Failing that, I believe you will have to (clone and) override the view that the media entity browser uses and do some filtering based on group(s) of the media file author.

Then try using the user id of the author initially using static values to test your view. If the UI of the view does not provide what you are looking for, you might need to write your own Views Access Plugin. Here is one I wrote for Message Private module: InboxPermission.php. You could do similar.

---
Tags: 8
---


title: Show field from a join table on Views

text:
# Question
Title: Show field from a join table on Views
Let's consider a views on an entity named :"Person" . "Person" has a field named "id" (the primary key) "PersonTag" has a field named "person\_id" (this field is referencing the id of "PersonTag" entity.

My issue is that I want to display in this views the fields of "PersonTag". First idea was to try to implement a join with Person using hook\_views\_query\_alter() . That was the main purpose of this question. Well now I'm having the join on my query, but can't figure out how to display the fields (of the join table) in my views.

So after some searches, I realised that I should use hook\_views\_data() as it explained in this question.

In documentation of hook\_views\_data() it's mentionned that:

> To provide views data for an entity, instead of implementing this hook, create a class implementing \Drupal\views\EntityViewsDataInterface and reference this in the "views" annotation in the entity class.

Since I'm having this class already created, I tried to implement my join in there. Here are the code implemented:

```
 class PersonViewsData extends EntityViewsData implements       EntityViewsDataInterface {

/**
 * {@inheritdoc}
 */
public function getViewsData() {
$data = parent::getViewsData();

$data['person']['table']['base'] = array(
  'field' => 'id',
  'title' => $this->t('Person'),
  'help' => $this->t('The Person ID.'),
);

 $data['person']['table']['join'] = array(

'person_tag' => array(
  'left_field' => 'person_id',
  'field' => 'id',
  ),
);

$data['person']['id'] = array(
'title' => t('Example '),
'help' => t('Example'),
'relationship' => array(
  // Views name of the table to join to for the relationship.
  'base' => 'person_tag_field_data',
  // Database field name in the other table to join on.
  'base field' => 'person_id',
  // ID of relationship handler plugin to use.
  'id' => 'standard',
  // Default label for relationship in the UI.
  'label' => t('Example '),
 ),
 );
return $data;
 }
 }

```

This code doesn't work, I don't see any field appearing in my view.

Would help me to figure out the solution?

# Answer
> 0 votes
The solution is pretty simple. Here is the code:

```
 class PersonViewsData extends EntityViewsData implements EntityViewsDataInterface {

  /**
   * {@inheritdoc}
   */
   public function getViewsData() {
   $data = parent::getViewsData();

   $data['person']['table']['base'] = array(
   'field' => 'id',
   'title' => $this->t('Person'),
    'help' => $this->t('The Person ID.'),
   );

 $data['person']['id'] = array(
'title' => t('Medecin tag test'),
'help' => t('Medecin tag test '),
'relationship' => array(
   // Views name of the table to join to for the relationship.
  'base' => 'person_tag_field_data',
  // Database field name in the other table to join on.
  'base field' => 'person_id',

  'id' => 'standard',
  // Default label for relationship in the UI.
  'label' => t('Test field'),
   ),
 );

 return $data;
 }
  }

```

Then you go in UI of the view: Advanced-\> Relation -\> add a new relation. You can see your new relationship there. After selecting it, go to "Add field ", you can then, find you new field that you can add to your view.

NB: There is no need to use hook\_views\_query\_alter as mentionned in the question above.

---
Tags: 8, views
---