# Question
Title: Routes node.add.CONTENT_TYPE are no longer available starting from Drupal 8.4 in hook_menu_links_discovered_alter()?
If you implement the `hook_menu_links_discovered_alter()` hook in Drupal 8.3 you have access to change the links with a code like this:

```
/**
 * Implements hook_menu_links_discovered_alter().
 */
function onlyone_menu_links_discovered_alter(&$links) {
    $links['node.add.article']['title'] = t('New name');
}

```

This code comes from the issue Improve the Add content page for the Allow a content type only once (Only One) module. But starting from Drupal 8.4 the same code gives an error like this:

> Notice: Undefined index: node.add.article in onlyone\_menu\_links\_discovered\_alter()

I searched inside the Drupal change records but I don't find anything talking about this change.

Now in Drupal 8.4 how you can change a link title?

# Answer
> 5 votes
There are several things I notice here:

1. An undefined index error shouldn't result just from this code - you're not referencing the array index; just setting it. Does the actual code have a more complex expression which references `$links['node.add.article']`?
2. This is not quite correct for this hook (and the linked issue is for 7.x, so it can't be compared). The hook documentation says that the menu item must be an associative array - it should be altered with `$links['node.add.page']['title'] = '...';`
3. The array key is not guaranteed to be fixed:

> Since the machine name may be arbitrary, you should never write code that assumes it is identical to the route name.

Therefore you should probably iterate and identify the menu link by the route name instead.

4. From what I can tell, core doesn't (and never did) define menu links for the `node.add.{type}` routes. The links on the `/node/add` page are dynamically generated, and don't actually show up in any menu.

So it doesn't seem to be possible to alter the links on the `/node/add` page by altering the menu. As you can see from the function below, these links are actually generated in a template preprocessor:

```
function template_preprocess_node_add_list(&$variables) {
  $variables['types'] = [];
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $type) {
      $variables['types'][$type->id()] = [
        'type' => $type->id(),
        'add_link' => \Drupal::l($type->label(), new Url('node.add', ['node_type' => $type->id()])),
        'description' => [
          '#markup' => $type->getDescription(),
        ],
      ];
    }
  }
}

```

The only way to modify the link text would be to replace the links in another preprocess function.

Edit: This other answer actually explains how to do that in detail: How to modify the link titles shown in /node/add page?

---
Tags: 8, routes
---


# Question
Title: Bootstrap site, not mobile friendly anymore
I made a website with Ubercart and Bootstrap. It was all running fine until a while ago. For some reason the website stopped being mobile friendly. When on mobiles it would show the desktop version and the navigation bar would not become the three bars button for example. Weird thing is when resizing the browser window on the computer it works as expected, but when trying it in developer tools it just doesn't care and remains as desktop version, on mobiles as well. I'm pulling my hair at this point. I have tried disabling a ton of modules but nothing changed. If you can look at the website and go into developer tools and check if there is some sort of an error or something that could help.

# Answer
> 3 votes
In your page's `<head>`, somehow the viewport got removed.

```
<meta name="viewport" content="width=device-width, initial-scale=1.0">

```

Without this, Bootstrap in general and `@media` in bootstrap.css don't know what width the screen is initially.

This should generally be auto-generated or put into `html.tpl.php`.

---
Tags: 7, theming, bootstrap-theme
---


# Question
Title: format spec. field from views_embed_view
My problem is that when using views\_embed\_view, i need to format spec. field for vacillation, i mean i don't know the syntax to access the spec field while rendering.

e.g use foreach , if field-name, then .....do some thing. search around the API doc. and google, no luck. OR should i use other API ? i don't know

below are my code put in tpl file. work fine, just don't how to formatting the fields

```
  $arg1 = $dept_id;
    print views_embed_view('staff_rec',$display_id = 'default',$arg1 );

```

please advise,

thanks billy

# Answer
> 0 votes
I think I know what you're trying to do.. You need to use a view tpl for the entire view.

Click `Theme: Information` in your view. You'll need to get the tpl file for `Style output`.

You can find the tpl files in your `modules/views/theme` folder. Then you copy it into your theme folder and rename it to a file name in your Information pane like below.

Here is a basic example tpl I'm using for one of my views. It let's me loop each row and access each field and build the html from there. This will work with `views_embed_view()`.

```
views-view-unformatted--homework-pane.tpl.php

<?php
    $arr_rows = $view->style_plugin->rendered_fields;
    foreach($arr_rows as $key=>$arr_row):
        if (isset($arr_row['field_due_date'])) {
            $date_print = t('Due') . ": " .$arr_row['field_due_date'];
        } else {
            $date_print = t('Posted') . ": " .$arr_row['created'];
        }
?>
<div class="todo-tasklist-item todo-tasklist-item-border-green">
    <div class="todo-tasklist-item-title"> <a class="use-ajax" href="/content-load/nojs/<?php print $arr_row['nid']; ?>"><?php print $arr_row['title']; ?></a> </div>
    <div class="todo-tasklist-controls pull-left">
        <span class="todo-tasklist-date"><?php print $date_print; ?> </span>
    </div>
</div>
<?php
    endforeach;
?>

```

---
Tags: views
---


# Question
Title: Searching for module filtering to Core compatibility 8.x, turned out it is only for 7.x
Searching for module "Serial field" filtering to Core compatibility 8.x, it is listed, but going into the details turned out it is only for 7.x. How should I avoid listing in 8.x if it is not really available? Is there anywhere information when it will be available? Is it possible to get a notification when it is released for 8.x?

# Answer
Select both "Core compatibility: 8.x" and "Stability: Has a supported stable release".

The combination will filter out modules like Serial Field, which has a stable version for D7 but only a -dev version for D8.

Unfortunately, this will also hide modules with only pre-releases (even -rc) for D8, some of which are in fact quite stable in practice.

There is no way to determine how far along a "non-stable" module is without actually going to the project page and looking at the releases/issue queue. There will usually be a message like this (this is the one for Serial):

> This module has a pre-release version for Drupal 8. To find out more, follow this issue or download below.

You can subscribe to these issues to get email updates when someone comments on it, and thus get alerted about development progress.
> 0 votes

---
Tags: 8
---


# Question
Title: Do not request a billing address during checkout
By default, Commerce 2 requests credit card info + address info (name, address, and company name) for all orders. I want to have users enter their credit card information but I don't want to collect their name, address, or company name. Stripe does not require name/address info so I don't want to require it, either.

As my payment gateway, I am using Commerce Stripe, but this applies to all payment gateways, such as Commerce PayPal, and the **Manual** (no credit card) payment gateway.

**So, how can I safely remove the address form from the checkout page?**

I first tried to hack Commerce directly (bad practice, just trying to see how it worked) but I broke the module.

As I looked around, it appeared that the billing info is deeply wired into the Commerce code. Is there a way to decouple it? Not all stores (those that sell digital products, etc.) need their customers' physical addresses.

On the checkout "Payment information" screen, I want to remove all of the fields from "Country" down to "Postal code":

# Answer
> 0 votes
Actually, according to this thread on drupal.org, the fact that you can hide the billing form and Commerce Stripe still works is an anomaly; usually, this should cause Commerce to crash.

At this time, Commerce 2 requires a billing address.

There is a experimental patch and a discussion of why Commerce requires a billing address on drupal.org.

# Answer
> 4 votes
It is quite hard to do indeed. One way to do this is by setting a dummy billing address and hide the address form.

You will need to do the following:

1. In a custom module, add a CommerceCheckoutPane plugin. The plugin class should extend \Drupal\commerce\_payment\Plugin\Commerce\CheckoutPane\PaymentInformation.
2. Override the `buildPaneForm()` method, in there:

* Set an `#after_build` callback. In this callback, make each address field non-required. The reason that you need an `#after_build` callback is that else address fields won't be available.
    * On the commerce\_profile\_select element, set an `#element_validate` callback. In this callback, set the address values. The reason that you need an `#element_validate` is because a general form validation callback is called too late in the validation process to set the address in time. This is because the address element has a constraint and the address is validated against this constraint after `#element_validate` and before a general form validate. Should you try to set the address in a general form validation callback, then you'll get address field required errors because of the constraint.

    You can set the `#element_validate` callback as well in the `#after_build` callback, which I've done in the code example below.
3. To hide the address form, you'll need to set `#access` to `FALSE` for the address form. This needs to happen in the `#after_build` callback as well, because earlier the address form isn't available yet.
4. On the checkout flow settings, disable the default Payment information pane (and enable the custom Payment information pane if not yet enabled).
5. To hide the dummy billing address on the 'Review' step, copy the template commerce-payment-method--credit-card.html.twig (and/or commerce-payment-method.html.twig if you are using a non-credit card payment method) to your theme and remove the line `{{ payment_method.billing_profile }}` from it.

Code example (file name: `mymodule/src/Plugin/Commerce/CheckoutPane/PaymentInformation.php`):

```
namespace Drupal\custom_commerce\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentInformation as PaymentInformationBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the payment information pane.
 *
 * @CommerceCheckoutPane(
 *   id = "custom_commerce_payment_information",
 *   label = @Translation("Custom Payment information"),
 *   display_label = @Translation("Payment information"),
 *   default_step = "order_information",
 *   wrapper_element = "fieldset",
 * )
 */
class PaymentInformation extends PaymentInformationBase {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form = parent::buildPaneForm($pane_form, $form_state, $complete_form);

    // Add an after build callback in order to make modifications on the address form.
    $pane_form['#after_build'][] = [$this, 'paneFormAfterBuild'];

    return $pane_form;
  }

  /**
   * After build callback for the pane form.
   */
  public function paneFormAfterBuild(array $pane_form, FormStateInterface $form_state) {
    // Get billing form element. Where it is located depends on the payment method that is chosen.
    if (isset($pane_form['add_payment_method']['billing_information'])) {
      $billing_form = &$pane_form['add_payment_method']['billing_information'];
    }
    elseif (isset($pane_form['billing_information'])) {
      $billing_form = &$pane_form['billing_information'];
    }
    else {
      // No billing information found.
      return $pane_form;
    }

    // Get the address form element.
    $address_form = &$billing_form['address']['widget']['0']['address'];

    // Add element validation callback to autofill the address.
    $billing_form['#element_validate'] = array_merge(
      [[$this, 'profileSelectValidate']],
      \Drupal::service('element_info')->getInfoProperty('commerce_profile_select', '#element_validate', [])
    );

    // Set all address fields to non-required.
    foreach (Element::children($address_form) as $key) {
      $address_form[$key]['#required'] = FALSE;
    }

    // Hide the address form.
    $address_form['#access'] = FALSE;

    return $pane_form;
  }

  /**
   * Element validation callback for the profile select element.
   */
  public function profileSelectValidate(array &$element, FormStateInterface $form_state) {
    // Set dummy address.
    $address = [
      'given_name' => 'A',
      'family_name' => 'A',
      'address_line1' => 'Dummy street',
      'postal_code' => '1234 AB',
      'locality' => 'Dummy city',
      'country_code' => 'NL',
    ];
    $form_state->setValue($element['address']['widget'][0]['address']['#parents'], $address);
  }

}

```

# Answer
> 3 votes
## TL:DR;

Go to `admin/config/people/profiles/types/manage/customer/form-display` and disable the form elements you want to hide (config applies to entire site)

## Explanation

It should be fairly easy to do this, though let me just say up front that I haven't tested this myself.

What you are seeing as the address, is the "billing profile" (both the order and the payment method has a billing profile IIRC. DC has not created the billing profile themselves (unlike in Drupal 7) but are instead using the profile module.

When DC renders the "billing profile" or "billing information" it respects the global settings made for the profile type it uses (customer). This means you can configure how the form should appear, including disabling all elements. This can be done at `admin/config/people/profiles/types/manage/customer/form-display`. This also means that you can add additional fields to the profile, if you wanted to collect more information without touching DC itself.

*Disclaimer - I have not tested this myself but having messed with Commerce quite a lot I'm pretty confident that this will work.*

---
Tags: 8, commerce, payment-gateways
---


title: phpunit query database

text:
# Question
Title: phpunit query database
How do I query the database when using PHPunit? This is my current attempt.

```
 /**
   * Testing to see if table is installed
   */
  public function testTableTest() {
   $connection = $this->getMock('Drupal\Tests\Core\Database\Stub\StubPDO');
    //-- What do I do next to query the database

    $query = $connection->query("SHOW TABLES LIKE {does_my_table_exist}");

    $expected = 'does_my_table_exist';
    $result = $query;
    $this->assertEquals($expected, $result);
  }

```

# Answer
> 3 votes
When you're using mocks in unit tests (see https://stackoverflow.com/questions/2665812/what-is-mocking), you yourself specify all the interaction that happens with the mocked object. In the simplest example, you can just specify exactly what the mock expects to receive, and what it will return:

```
$connection = $this->getMock('\Drupal\Core\Database\Connection', []);
$connection->method('query')
  ->with('SHOW TABLES LIKE {does_my_table_exist}') // expect this query
  ->willReturn(
    $this->getMock('\Drupal\Core\Database\StatementInterface')
      ->method('rowCount') // expect the ->rowCount() to be called.
      ->willReturn(1) // pretend that there is exactly one result.
  );

$result = $connection->query('SHOW TABLES LIKE {does_my_table_exist}')->rowCount();
$this->assertEquals(1, $result); // PASS
$result = $connection->query('SHOW TABLES'); // FAIL; unexpected argument.

```

Note that you shouldn't normally be mocking the StubPDO class; it's only for Drupal's internal DB driver tests. When your code interacts with the database, it does so via the `database` (`\Drupal::database()`) service, which you can replace with a mock of `\Drupal\Core\Database\Connection`.

Edit: A good example of a core unit test that mocks the database and actually simulates interaction is `core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php`. An excerpt of the `setUp()` function:

```
$this->statement = $this->getMockBuilder('Drupal\Core\Database\Driver\sqlite\Statement')
  ->disableOriginalConstructor()
  ->getMock();

$this->statement->expects($this->any())
  ->method('fetchObject')
  ->will($this->returnCallback([$this, 'fetchObjectCallback']));

$this->select = $this->getMockBuilder('Drupal\Core\Database\Query\Select')
  ->disableOriginalConstructor()
  ->getMock();

$this->select->expects($this->any())
  ->method('fields')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('condition')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('execute')
  ->will($this->returnValue($this->statement));

$this->database = $this->getMockBuilder('Drupal\Core\Database\Connection')
  ->disableOriginalConstructor()
  ->getMock();

$this->database->expects($this->once())
  ->method('select')
  ->will($this->returnValue($this->select));

```

---
Tags: database, testing
---


# Question
Title: How to keep a specific module on -dev version (with patches) on a Drupal8 site managed by composer?
I'm trying to manage a Drupal 8 site entirely with composer. However, I need a -dev version of one module (search\_api\_solr) with a patch. How do I tell composer to just leave this module on the dev version for the time being and not touch it during update ?

Relevant part of my composer.json looks like this

```
"require": {
        "composer/installers": "^1.0.21",
        "drupal-composer/drupal-scaffold": "dev-master",
        "drupal/admin_toolbar": "^1.18",
        "drupal/bootstrap": "^3.2",
        "drupal/coffee": "^1.0@beta",
        "drupal/config_tools": "^1.0@alpha",
        "drupal/console": "~1.0",
        "drupal/core": "~8.2",
        "drupal/delete_all": "^1.0@alpha",
        "drupal/devel": "^1.0@RC",
        "drupal/facets": "^1.0@alpha",
        "drupal/imce": "^1.5",
        "drupal/masquerade": "^2.0@beta",
        "drupal/migrate_manifest": "^1.4",
        "drupal/migrate_plus": "^3.0@beta",
        "drupal/migrate_tools": "^3.0@beta",
        "drupal/migrate_upgrade": "^2.0",
        "drupal/pathauto": "^1.0@RC",
        "drupal/search_api": "1.0@beta",
        "drupal/search_api_sorts": "^1.0@alpha",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/search_api_solr": "8.x-1.x-dev"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,

```

I've specified the search\_api\_solr version according to this advice. However, when I run composer update I get:

Your requirements could not be resolved to an installable set of packages. The requested package drupal/search\_api\_solr 8.x-1.x-dev exists as drupal/search\_api\_solr\[...\] but these are rejected by your constraint.

EDIT: Meanwhile I have worked around this by removing the drupal/search\_api\_solr requirement completely from the composer.json, explicitly listing solarium/solarium instead and installing the patched version of search\_api\_solr-8.x-1.x-dev manually into the modules/unstable directory. Now composer update works as it shold without overwriting the patch.

# Answer
> 2 votes
Firstly, the `8.x-` is not part of the composer version; the correct version is `1.x-dev` or `dev-1.x`.

However, `composer require drupal/search_api_solr:1.x-dev` always updates to the latest revision on the dev branch. If you want to stay on a specific commit and prevent updates entirely, use something like `composer require drupal/search_api_solr:1.x-dev#46e16862`.

---
Tags: search, composer
---


# Question
Title: Avoiding entity-type errors on module installation
I created a logger service that uses a config entity for configuration: https://drupal.org/project/dblog\_persistent

Unfortunately, it appears that this module is not installable on a new site, because Drupal attempts to instantiate the logger service before actually installing the config entity type it depends on - the result is a PluginNotFoundException.

There has to be some way to prevent services from being instantiated until the module is installed, or not?

This is the class and constructor definition:

```
<?php

namespace Drupal\dblog_persistent\Logger;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\dblog\Logger\DbLog;
use Drupal\dblog_persistent\DbLogPersistentStorageInterface;

/**
 * Class DbLogPersistent
 *
 * @package Drupal\dblog_persistent\Logger
 */
class DbLogPersistent extends DbLog {

  /**
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $channelStorage;

  /**
   * @var \Drupal\dblog_persistent\DbLogPersistentStorageInterface
   */
  private $storage;

  /**
   * @var \Drupal\dblog_persistent\Entity\ChannelInterface[]
   */
  private $channels;

  public function __construct(Connection $connection,
                              LogMessageParserInterface $parser,
                              EntityTypeManagerInterface $manager,
                              DbLogPersistentStorageInterface $storage) {
    parent::__construct($connection, $parser);
    // The following causes an error on installation:
    $this->channelStorage = $manager->getStorage('dblog_persistent_channel');
    $this->storage = $storage;
  }

```

And the service definition:

```
services:
  dblog_persistent.storage:
    class: Drupal\dblog_persistent\DbLogPersistentStorage
    arguments:
      - '@database'
  logger.dblog_persistent:
    class: Drupal\dblog_persistent\Logger\DbLogPersistent
    arguments:
      - '@database'
      - '@logger.log_message_parser'
      - '@entity_type.manager'
      - '@dblog_persistent.storage'
    tags:
      - { name: logger }

```

As a hack, I could surround every function in the logger with `if`s that ensure it doesn't run unless installation is complete, but that's pretty dirty. Is there at least some kind of null entity storage that the constructor could fall back on, to minimize the amount of defensive programming?

# Answer
> 1 votes
I've revised my approach here several times, but so far the cleanest solution in my opinion is:

Store the entity\_type.manager service, not the storage. When the storage is used, place the whole chain `$this->manager->getStorage()->loadMultiple()` into a try/catch.

This avoids having to handle the special case in two places: Once in the constructor (when acquiring the storage might fail), and again in the loading function (when the storage might not exist, because it failed in the constructor).

```
<?php

namespace Drupal\dblog_persistent\Logger;

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\dblog\Logger\DbLog;
use Drupal\dblog_persistent\DbLogPersistentStorageInterface;

/**
 * Class DbLogPersistent
 *
 * @package Drupal\dblog_persistent\Logger
 */
class DbLogPersistent extends DbLog {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $manager;

  /**
   * @var \Drupal\dblog_persistent\DbLogPersistentStorageInterface
   */
  protected $storage;

  /**
   * @var \Drupal\dblog_persistent\Entity\ChannelInterface[]
   */
  private $channels;

  public function __construct(Connection $connection,
                              LogMessageParserInterface $parser,
                              EntityTypeManagerInterface $manager,
                              DbLogPersistentStorageInterface $storage) {
    parent::__construct($connection, $parser);
    $this->manager = $manager;
    $this->storage = $storage;
  }

  protected function getChannels() {
    if ($this->channels === NULL) {
      try {
        $this->channels = $this->manager
          ->getStorage('dblog_persistent_channel')
          ->loadMultiple();
      }
      catch (PluginNotFoundException $e) {
        $this->channels = [];
      }
    }
    return $this->channels;
  }
}

```

---
Tags: 8, installation, dependency-injection
---


# Question
Title: Is cache_form table making a site faster by any way?
Drupal Commerce refuses to flush the cache\_form table when cron tasks run. I know it is most likely a known bug and it has tens of solutions. (I will probably just set cron task to flush it somewhere in the midnight every day.)

Does it speed up Drupal in any way?

It is part of a cache obviously, but I did not noticed any better performance whether the table size. More or less I experience slowdown, but it might be related to something else.

# Answer
> 1 votes
The cache\_form table holds forms that have been loaded by the system for your visitors. Eg, if a person went to a form before the form has expired, it exists in the form\_cache by default.

Sometimes forms can bypass the form\_cache if they are required to be rebuilt on every page request, such as with Ajax requested forms, or external services.

If you have a Shopping Cart driven application the cache\_form may contain stuff added to your visitors cart -- which they have not purchased yet (I'm not sure if commerce stores cart entries in a separate table), but in general be wary of clearing the form cache because some of your visitors state may be lost.

Expired forms should be cleared by the system on cron run.

---
Tags: caching
---


# Question
Title: Get tag(term) name for multiple nodes without a performance hit
I want to get a list of nodes and return them as JSON along with their tags (names included). After a lot of research, I've only come up with this solution:

I have an array of Nodes (`\Drupal\Core\Entity\EntityInterface`) loaded with `Node::loadMultiple()`.

Iterating over the array of nodes, and getting their tags using `$node->field_tags` (or whatever the machine name of the tags is) which yields an array of `\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem`

Getting all the terms of the node using `Term::loadMultiple()` and then iterating over them and getting the name using `$term->name[0]->value`.

The problem is that there's an extra database read for every node, and I guess that the underlying query for this read is a JOIN :|.

**Question:** Is there an efficient way to load the tag (term) names along with `target_id`, `target_type`, `target_uuid`, etc? If no, is the current loop on each node the way to go???

**More Info:**

* I'm paginating the results
* The client can set the number of results per page, but there's a 50 nodes per page limit

Thanks

**P.S.**: I have two more types of tags so I have to do this two more times. Bright side is, the other two tags are 1to1.

# Answer
> 3 votes
If you're already looping over an array of nodes, have you considered collecting the term IDs before loading them in one query? That should save a lot of the overhead of running multiple queries:

```
$map = [];
$tids = [];

// Collect IDs for each node:
/** @var \Drupal\node\Entity\NodeInterface[] $nodes */
foreach ($nodes as $nid => $node) {
  /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $item */
  foreach ($node->field_tags as $item) {
    $tid = $item->target_id;
    $map[$nid][$tid] = $tid;
    $tids[$tid] = $tid;
  }
}

// Load terms and collect their labels:
$term_labels = [];
/** @var \Drupal\taxonomy\Entity\TermInterface $term */
foreach (Term::loadMultiple($tids) as $tid => $term) {
  $term_labels[$tid] = $term->label();
}

// Assign the term labels to each node.
foreach ($map as $nid => $node_tids) {
  foreach ($node_tids as $tid) {
    $map[$nid][$tid] = $term_labels[$tid];
  }
}

```

---
Tags: 8, taxonomy-terms, database
---


# Question
Title: View of all users and their relationship(s) with the current one
I've been trying to create a view of all users, showing their relationship to the current one. I can't figure out a way to display all of them. By adding the Contextual filters User UID or Requester user, the views results are restricted only to users having a relationship (with the current one), therefore not showing the ones not having one...

I have also been trying to use the Relationship "Requester user is current user", but without success.

Here an example of the expected result: https://i.stack.imgur.com/kifyJ.png

Am I missing something? thanks in advance for your help

# Answer
A contextual filter does not limit the results, it only adds additional input to the view based on certain situations.

It may be a problem with the relationship.

Please check that **Require this relationship** is not ticked. If it is then by its description "Enable to hide items that do not contain this relationship".

If you just add the relationship but not require it, a field taken from the relationship will only display as a blank space in your rendered view.

Hope this helps. I had the same problem before.

---

Update 2014/06/20

I'm assuming the view displays users.

**Contextual Filters**

* add User:Uid -- When the filter value is NOT in the url, provide a default value -- User ID from logged in user.

This filter will set it to display based on the current user.

**Relationships**

* User relationships: Requester user -\> use the contextual filter on this

You'll have to play around with this as I'm not sure.

**Sort Criteria**

* UID ascending

**Fields**

* UID: (this will display all the user IDs) (check first after adding this that ALL users are displayed.)
* Relationship Type
* UID: (use the relationship)

Try adding the first field first then adding all the contextual filter, relationship stuff. It has to display ALL the users.
> 0 votes

# Answer
Here is the way to have a list of users relationships in this screen capture

Just in RELATIONSHIPS edit : User relatinoship:Requestee user

add

When the filter value is not in the url \> provide default value \> user ID from logged in user

idem for CONTEXTUAL FILTERS and selected you relationship by the name you gave it.

After you can do more wih add a path for your page like user/%/mypagename and add to user menu tab
> 0 votes

---
Tags: views, users
---


# Question
Title: How to add a notification when a relation or friends publish new content?
I want like Facebook notification add icon when a user relationships or flag friends ( User Relationships or Flag Friend module) published some new content.

I followed this good tutorial who is the closest to do that : How to allow users to manage their own Message Stack messages?. It works perfectly, but only for the current user and not relationships or friends. I also found How to implement Facebook style Notifications for Organic Group posts?.

I would use not only for the current user but for user relationships like a Facebook notification. I tried many ways: using Rules, Views or custom development (the most closest with hook\_node\_insert and user\_relationships\_load } but without success.

The problem is you need to notify individually each of the friends, so that they can manage there own notifications. If not each time a friend removes a notification, it's removed for ALL friends.

I add a custom field of user that is fill by one each time a new content is publish with a custom module this is working but I not find a way to JOIN the QUERY with the relationship table or friends tables.

```
function my_module_node_insert($node){
if($node->type == 'mytype'){
db_update('field_data_field_my_field_name')
->expression('field_my_field_name_value', 'field_my_field_name_value +
:amount', array(':amount' => 1))
->execute();
//or you also can use regular query
//db_query("UPDATE {field_data_field_my_field_name} SET
//field_my_field_name_value = field_my_field_name_value + 1");
}
}

```

Here is the screen of the views of list "all friends" default views of Flag friends module

# Answer
> 2 votes
When it comes to Facebook type notifications, the Message module is indeed very useful. I'll give an example below of using one view's results `view_with_users` in another view's contextual filter `my_messages_view`.

For this to work, in your main messages view, you have to go into your contextual filter's settings (probably Message Author or something), then scroll to the bottom and click `Allow multiple values`. Instead of the usual `Provide default: Current User`, we will send all the friends to the view with a module.

Note: In the below example, I've sent the current user's uid to the additional view as an example, but your screenshot doesn't have that contextual filter so it's either not needed, or you may need to tweak the friends view to work programmatically.

```
custom_views_args.module

<?php

function custom_views_args_views_pre_view(&$view, &$display_id, &$args){
    global $user;
    // Target our Messages view
    if($view->name == 'my_messages_view') {
        // Get users from our friends view
        $friends = views_get_view_result('view_with_users', 'view_display_name', $user->uid);
        // Add each uid to array
        $friends_array = [];
            foreach($friends as $friend){
            $friends_array[] = $friend->uid;
        }
        // Add current user's uid to array as well
        $friends_array[] = $user->uid;
        // Create + separated Contextual Filter
        $messages_con_filter = implode("+", $friends_array);

        // Send the filter to the Messages view
        // $args[0] is the first filter in the list in the view
        $args[0] = $messages_con_filter;

    }
}

```

See this thread for more info about Facebook-style notification. There may be other useful threads but I happened to answer that one. OP's question should give you some useful pointers. My answer there is quite specific but might give you ideas on how to make messages "seen".

Pierre wrote this in the comments above.

> for each of those friends such notification can be marked as read by each friend individually

If you use a non-global Flag for "seen", then it will do the above.

---
Tags: views, rules
---


# Question
Title: I'd like to add a second "Save" button that saves the node as usual, but I can use a module to alter the node
EDIT: Answered below.

Bit of a weird one. I'd like a second Save button that saves a node but that I could target with some php.

`Save` `Save Progress` `Cancel`

My use-case isn't as simple as using Autosave and I don't want to start installing WorkBench or any other module for a small feature.

I could have a taxonomy field above the save where users can choose, but really, I'd prefer a second Save button for UI reasons. I could also use jQuery and have psuedo-buttons that click the appropriate term and then the save button, but I'd rather do it programmatically.

Thanks.

# Answer
I had to do this with a validate handler instead of a submit handler. I'm not sure of the implications of that but it works.

```
<?php

function custom_assignment_save_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "assignment_node_form") {
        $form['secondsubmit'] = array(
        '#type' => 'submit',
        '#value' => t('Save Progress'),
        '#weight' => 100,
        '#validate' => array('node_form_validate', 'custom_assignment_save_form_validate'),
        '#submit' => array('node_form_submit'),
      );
    }
}
function custom_assignment_save_form_validate($form, &$form_state) {
    form_set_value($form['field_boolean'], array(LANGUAGE_NONE => array(0 => array('value' => 1))), $form_state);
}

```

This simply changes a hidden boolean value when the `Save Progress` submit button is used.
> 2 votes

# Answer
You can add a custom submit handler and then your own callback to do whatever you want.

The basic approach is:

1. Using `hook_form_alter()` to target the relevant form, add another submit button that calls your callback function.
2. Write the callback function to do whatever you want to do.

Here's an example:

```
function my_module_form_alter(&$form, $form_state, $form_id) {
  $form['#submit'][] = "my_module_form_submit_handler";
}

function my_module_form_submit_handler($form, &$form_state) {
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}

```
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Why is it better to use event subscribers rather than hooks
In drupal 8, we now have the ability to use event subscribers. What's the reason for this? Is it to work with the new cache API better?

Recently I had a task of needing to extract data from a node when it was viewed, but `hook_node_view()` is cached (like nearly everything) in Drupal 8. So I ended up using an event subscriber. Why is using event subscribers a better solution? Is it just that it's more object orientated?

# Answer
You can see this from two perspectives. First of someone who is looking for a way to communicate with Drupal and so is using the hooks and events that exist. The second one is that of a developer who designs these APIs.

Drupal is in the middle of both, on the one side Drupal is a consumer of the Symfony API, almost every piece of code is placed in Symfony events, and on the other side Drupal provides APIs, in form of legacy hooks or custom Symfony events and other methods like plugins.

You probably didn't use one of the Drupal APIs, more likely a Symfony kernel event, `KernelEvents::REQUEST`. Then you are in the same position as a Drupal developer and this is not a question about hooks or events, because Symfony doesn't provide hooks.

Even if you were using one of the Drupal APIs, you wouldn't have much choice. You would have to select what is provided to you. Only if you design an API in your module to interact with other modules, then you can choose between an event or a hook.
> 6 votes

---
Tags: 8, event-subscribers
---


# Question
Title: Access fields in views-view Twig template
I'm trying to loop through `rows` in a `views-view` template, but I can't seem to `kint` or `dump` anything out to help me in doing so.

I've tried following various other answers, such as:

Again, without any success.

Usually I'd create a `views-view-fields` template, and access my fields via `fields.title.content` for example. I need to loop through them via the `views-view` template, as I'm needing to do some checks, taking into account values of some of the previous row's fields.

**How can I access a rows fields when looping through `rows` in my `views-view` template?**

# Answer
In your case you should be using views-view-fields.html.twig instead of views-view-unformatted.html.twig file.

Views fields template will iterate on all rows of result. Your views-view-fields.html.twig should contain below code -

```
<div>
  <a class="view-row" href="{{variable-to-print-path }}">
   <img src="{{ image-path }}">
   <h3>{{ fields.title.content</h3>
  </a>
</div>

```

You can check the fields array by using kint function like - {{ kint(fields) }}

Check for image path and anchor path variable from output of kint function.

If you want to do this in views-view-unformatted.html.twig, then you can access the field values like below -

```
{% for row in rows %}
  {% set photo = file_url(row['content']['#row']._entity.field_page_photo.entity.fileuri) %}
  <li><img src={{ photo }} class="img-responsive img-circle"></li>
{% endfor %}

```
> 1 votes

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


title: Dynamic dependent form select inputs

text:
# Question
Title: Dynamic dependent form select inputs
I'm building a custom dependent dropdown form with 2 select inputs.

I've managed to build the form inputs and update them accordingly, but I'm not able to get the dependent select's value in the submit hook.

I think this happens because I changed (via `AjaxResponse()/ReplaceCommand`) the `$form` in the AJAX callback, and as such, the second input values aren't updated in the `$form_state`.

My problem is that I have no simple way of knowing which options will be available either in the first-level select nor in the dependent select, since they come from a 3rd-party API.

Is there any way I can trigger the update of the `#options` in the dependent select, **without** having to render the nested dropdown and changing the `$form` so that the nested values are available in the `submit` hook?

Or, alternatively, is there anyway I can update the `$form_state` so that it knows the newly added `#options` of the second select?

# Answer
With @4k4's help I managed to find the root cause of my issue and fix it.

I was wrongfully assuming that the `$form` elements could be somehow modified in an AJAX call to produce my desired effect.

While it is true that the elements could be modified and re-rendered in an AJAX response, that is not the correct way to alter a form after an AJAX call.

The 2 main things to know are:

* forms are **rebuilt** everytime an AJAX call is made (when it is declared in the `#ajax` array of the form element triggering the call)
* the AJAX function being called should (ideally) only return the element suffering modifications. It **cannot** modify the `$form` in any way, otherwise those modification will either be lost when it is rebuilt, or trigger the `An illegal choice has been detected. Please contact the site administrator.` message.

This being said, the general flow for this should be:

* create the `buildForm` function with code that builds both your select elements. Wrap in a conditional clause code that tests if the parent select was already changed or not. This will be used to determine if the nested select should be populated or not;
* set an `#ajax` property in the parent select element of the form, referring a callback to be used;
* define the callback to return only the element which needs to change in the form, ie, the nested select;
* when Drupal tries to rebuild the form, your parent select will already have a value that can be used in the above mentioned test-clause to allow for population of the nested callback.

@4k4's suggested documentation was difficult for me to find, but clear enough to follow trough once found - link here. (Even though it is for Drupal 7, in Drupal 8 it functioned exactly the same way).
> 2 votes

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


# Question
Title: Select address functionality during checkout for Drupal Commerce 2.x
I am using Drupal Commerce 2.x for my e-commerce website. I have installed the Address module which provides functionality for storing, validating and displaying international postal addresses. I've added the field for the address in the user registration form through which I can accept multiple addresses from the user. As per the default checkout flow, the user has to mention his address manually while entering shipping details. So, is there any mechanism where the user can select the address previously set by him? Or I have to rely on customisation to achieve this functionality?

# Answer
> 2 votes
There is a patch in progress to add this feature.

To apply the patch to the most recent version of Commerce (2.1 as of this writing), based on this comment, you can add this to your `composer.json`:

```
"drupal/commerce": {
      "reverse profileSelect change to allow PR 760": "https://www.drupal.org/files/issues/2844920-reverse-profileSelect-temp-fix.patch",
      "reuse profiles": "https://patch-diff.githubusercontent.com/raw/drupalcommerce/commerce/pull/760.diff",
      "reuse profiles enhanced": "https://github.com/fliegen/commerce/commit/57c11175d279fe55db9454b4274608195211aeb8.diff",
      "checkbox same as billing": "https://www.drupal.org/files/issues/checkbox-same-as-billing-2852207-69.patch",
  }
  "drupal/commerce_shipping": {
      "profile select enhancement": "https://github.com/fliegen/commerce_shipping/commit/797b5ef351851d60b2cb6c1a55837501c2a036a5.diff",
      "profile in shipping method widget fix": "https://www.drupal.org/files/issues/profile-reuse-enhanced-2908683-1.patch",
      "auto-recalculate shipping": "https://www.drupal.org/files/issues/commerce_shipping-autorecalculate-2849756-35.patch"
  }

```

You don't need to add the `checkbox same as billing` and `commerce_shipping` part if you are not collecting a shipping address.

---
Tags: 8, commerce, entities
---


title: Change name to menu link dinamically

text:
# Question
Title: Change name to menu link dinamically
I have a menu:

```
Parent-1
 - Child-1-1
 - Child-1-2
 - Child-1-3
 - another_child
Parent-2
 - Child-2-1
 - Child-2-2
 - another_child

```

I needed change the name of Parent-2 item (Parent-2 text is unique), I did it with `hook_link_alter()` hook:

```
/**
 * Implements hook_link_alter().
 */
function MY_MODULE_link_alter(&$variables) {
  if ($variables['text'] == 'Parent-2') {
     $variables['text'] = t('New name');
  }
}

```

I need too to change the names of all child of Parent-2 dynamically. I can't do it with hook\_link\_alter() hook because in my example there is two elements(another\_child) with the same name. Those changes must not be saved in database.

How can I do this?

# Answer
I can do it implementing `hook_preprocess_HOOK` hook, specifically `hook_preprocess_superfish`:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_NAME_preprocess_superfish(&$variables) {
  if ($variables['id'] == 'superfish-main-menu') {
    $menu = ($variables['element']['#tree']);
    // ...
  }
}

```
> -1 votes

---
Tags: 8
---


title: Non-blocking asynchronous HTTP requests

text:
# Question
Title: Non-blocking asynchronous HTTP requests
I need to send asynchronous and non-blocking POST HTTP requests from a Drupal service.

Using Drupal 7, I used HTTP Parallel Request which worked fine.

But this module is not available on Drupal 8. And it seems that the default D8 HTTP Client, Guzzle, doesn't allow to do this : https://stackoverflow.com/questions/35956516/send-asynchronous-request-without-waiting-the-response-using-guzzle.

Is there some way I can achieve that with Drupal 8 ?

**Edit**: If I don't find how to do it with Drupal mechanisms, I will go with this fsockopen...

# Answer
> 2 votes
I ended up implementing a custom function on the base of this post :

```
private function async( $method, $url, $params = array() ){
    // Get URL parts
    $url_parts = parse_url( $url );

    // If needed, append params to query url
    if( $method === 'GET' ){
        $url .= '?' . http_build_query( $params );
    }

    // Open socket
    $port = isset( $url_parts['port'] ) ? $url_parts['port'] : 80;
    $fp = fsockopen( $url_parts['host'], $port, $errno, $errstr, 30 );

    // Build HTTP request
    $request = $method." ".$url." HTTP/1.1\r\n";
    $request.= "Host: ".$url_parts['host'].":".$port."\r\n";
    $request.= "Connection: Close\r\n";
    if( $method === 'POST' || $method === 'DELETE' ){
        $post_string = Json::encode( $params );
        $request.= "Content-Type: application/json; charset=utf-8\r\n";
        $request.= "Content-Length: ".strlen( $post_string )."\r\n";
        $request.= "\r\n";
        if( isset($post_string) ){
            $request.= $post_string;
        }
    } else {
        $request.= "\r\n";
    }

    // Send request and immediately close the pointer
    fwrite($fp, $request);
    fclose($fp);
}

```

---
Tags: 8
---


# Question
Title: Webform Custom-Field Module and validation
I am currently working on a Webform that is used to enter some rather complex finance information (think tables with sums and other weird checks).

Since the styling has to be rather specific for this form I decided to create a custom Module that provides a new Webform-Component using the Webform Module Hooks.

That means that I created the HTML and WebForm Structure of the form using the `_webform_render_component` hook by providing a custom `#process` function that expands the initial component array to include a bunch of textfields and some custom themes.

```
function _webform_render_ff_promotion($component, $value = NULL, $filter = TRUE) {
  $element = array(
    '#weight' => $component['weight'],
    '#pre_render' => array('webform_ff_promotion_form_prerender'),
    '#webform_component' => $component,
    '#theme' => 'webform_display_ff_promotion_form',
    '#process' => array('webform_process_ff_promotion_form_expand'),
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  );
  return $element;
}

```

And the custom process expansion:

```
function webform_process_ff_promotion_form_expand($element) {
  $element['general_group'] = array(
    '#type' => 'fieldset',
    '#theme' => 'ff_general_group_fieldset'
  );
  $element['general_group']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => true
  );
....
}

```

So far that works well and I have the form set up to look and behave as I need it to (saving etc works). Only problem now is validation - I cannot specify any other validations rather than required through the form\_api.

I am trying to do this with the Webform Validation Module following this guide. This works and I could now write a really huge list of `if (is_numeric(...))` checks to see if the user did only enter numeric values to my textfields - but it feels kind of pointless.

So the main question here being - is there a best practice for custom components that rely on standard components internally (The whole custom component consists of just a bunch of `'#type' => 'textfield'` elements) to validate without writing a completely custom validator for it?

The Webform Validation Module feels like the wrong tool as it allows the validations to be done by the user in the admin. I'd rather just add more attributes like the `'#required'` in the FormAPI and have them be checked.

Any help would be greatly appreciated - thanks!

Version Info:

* Drupal 7.34
* Webform: 7.x-4.6
* Webform-Validation: 7.x-1.9

# Answer
It looks like the hook `_webform_action_set_component` might be used for validation: "Setting the form element allows form validation functions to see the value that webform has set for the given component."

http://www.rit.edu/drupal/api/drupal/sites!all!modules!webform!webform.api.php/function/\_webform\_action\_set\_component/7.41
> 0 votes

# Answer
If you just need to make sure the values are numeric, try Elements module. It adds advanced form elements like HTML5 number. Then you can use `'#type' => 'numberfield'` instead of `'#type' => 'textfield'`.

Another option is to add a standard validator that suits your needs. For example, you can use `'#element_validate' => array('element_validate_number')` to validate your numeric fields.
> 0 votes

---
Tags: webforms, forms
---


# Question
Title: Drush enable module | not working | Drupal 7 on WAMP with PostgreSQL
Based on Drush on windows - Command pm-enable needs a higher bootstrap level to run, i have the following question.

I have the same problem found here https://drupal.org/comment/8533097 except I am using Postgresql and this solution did not work for me.

My Drupal installation is at: C:\SiteData\WebDev\gitproject (aka DrupalRoot). I successfully ran `drush status` in "\[DrupalRoot\]\sites\site1.example.com, but when I try to enable a module using `drush en ccl` and 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 ccl' 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.26
> Site URI : http://site1.example.com
> Database driver : pgsql
> Database username : user
> Database name : site1dev
> Default theme : garland
> Administration theme : garland
> PHP executable : php
> PHP configuration : "C:\Program Files (x86)\Drush\Php\php.ini"
> PHP OS : WINNT
> Drush version : 6.0
> Drush configuration :
> Drush alias files :
> Drupal root : c:/SiteData/WebDev/gitproject
> Site path : sites/site1.example.com
> File directory path : sites/site1.example.com/files

My settings.php file looks like this.

```
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site1dev',
      'username' => 'user',
      'password' => 'secretpw',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'pgsql',
      'prefix' => 'dev_',
    ),
  ),
);

if (php_sapi_name() == 'cli') {
  $db_url = 'pgsql://user:secretpw@127.0.0.1/site1dev';
 }
 else {
   $db_url = 'pgsql://user:secretpw@localhost/site1dev';
 }

```

I have used both the "Drush Command Prompt" and "MINGW32" git command line tool and both work for "drush status" or "drush dl " but not for "drush en "

One last comment. looking at the settings.php file permissions in MINGW32 they show the unix permissions of -rw-r--r--.. Tried changing this in using chmod but doesn't work on a windows file (not even sure that makes a difference).

# Answer
> 2 votes
I'm not on Windows or using postgres today, but I can suggest how to debug:

What you've got right now is that your cli environment seems to be failing to connect to the database correctly. Checking your database-level access from drush, using verbose (-v) debug (-d) feedback may provide clues.

For instance, given your current failure, I would run

```
  drush -v -d sql-cli

```
* that will, among other things, show you the exact database connection command being attempted that is failing.

You can then copy that yourself, run it again, and see what variations of that command will and will not work. One of the more common issues seems to already be covered (the difference between 'localhost' and '127.0.0.1' depending on installation and version issues. There may be other issues such as 'cannot locate postgres.exe in the current $PATH' or whatever.

This is not an answer to the question, but a suggestion on how to get clueful when a (any) drush command just doesn't work. You can also use the -vd flags on your 'en' command, though I don't know how conclusive the feedback you get there will be.

# Answer
> 0 votes
Navigate to http://site1.example.com using cd /sites/site1.example.com and run your drush commands. I had similar problems in the past. The settings.php file in /sites/default/ was not being used and the database entries inside that file were wrong. Everything worked as desired when ran the drush commands within the site folder containing the settings.php file with the correct database credentials.

# Answer
> -1 votes
Add mysql to global path. Worked for me.

---
Tags: drush, database
---


# Question
Title: Link to a custom entity settings page does not appear at /admin/structure
I have several custom entities as part of a module. When I visit /admin/structure, one of the entities is not listed in the groups of setting, or in the lists. However, if I manually type, `/admin/structure/{entity}/settings/fields`, I can manage the fields, form and display. However, the "Settings" tab is missing.

Similarly, I can manually type `/admin/structure/{module}/{entity}` to see the entity list, but the link is missing. The entity list is missing the button to add a new entity because the entire #block-seven-local-actions div is missing. Manually typing `/admin/structure/{module}/{entity}/add` brings up the correct form, and the form works.

It appears the routes are present, but something is preventing some of the links from being displayed. There are no errors in the recent log messages.

# Answer
Please revise your file:

> yourmodule.links.menu.yml.

and verify if exists the parameter

> parent

A complete example

```
  yourmodule.admin_content:
  title: Content
  description: 'Find and manage content.'
  route_name: system.admin_content
  parent: system.admin_structure
  weight: -10

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Same website but different logo for large screen and small device?
I would like to have two different logos on the same website. One for large screen and one for small screen ( mobile devices )

I am using D8

Thank You

# Answer
There are multiple ways to do this through CSS media queries. See example below.

```
.classname {
   @media all and (min-width: 768px) {
     background-image:url('image2.png');
   }
   @media all and (min-width: 320px) {
     background-image:url('image1.png');
   }
}

```

Helpful links

1. Responsive Images
2. Working with breakpoints

If you use the module and breakpoints from your theme you can probably just wrap the logo in a div class so you can control the padding or other CSS attributes. Just make sure to find the correct image styles per breakpoints and multipliers.
> 5 votes

---
Tags: theming, 8
---


# Question
Title: PDO Deadlocks Galore on the Semaphore table
I experience frequent deadlocks on the semaphore table that look like this:

> PDOException: SQLSTATE\[40001\]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {semaphore} WHERE (name = :db\_condition\_placeholder\_0) AND (value = :db\_condition\_placeholder\_1) AND (expire \<= :db\_condition\_placeholder\_2) ; Array ( \[:db\_condition\_placeholder\_0\] =\> variable\_init \[:db\_condition\_placeholder\_1\] =\> 298999494f343fc583c3e2.30542255 \[:db\_condition\_placeholder\_2\] =\> 1328824262.5293 ) in lock\_may\_be\_available() (line 181 of /var/www/drupal/includes/lock.inc).

This site sees fairly heavy traffic. Is the load the cause of this? Is this due to a faulty module? Is this something in Drupal core?

Most importantly, are there precautionary measures I can take to avoid this?

# Answer
It appears that once we implemented memcache the problem began to dissipate. It appears the database was writing very frequently to the cache tables, specifically the cache\_form table. These deadlocks would appear when there were just too many commands running on the box.
> 4 votes

# Answer
I had the same issue too. I realized that semaphore table is being used like a temporary table and works similar to how UNIX/LINUX runs semaphore commands.

I removed the primary and unique keys on the 'semaphore' table in the DB

1. Drupal Semaphore table is similar to a Unix kernel Semaphore working where when a process needs to lock the table/file to perform some operation on that table/file puts a lock on it by adding an entry in the semaphore table. These entries are then deleted as soon as the process is done or the data is updated on the table/file and lock is removed for the next operation (In a general sense, what is the purpose of the Drupal DB Semaphore Table)
2. Drupal 7 was initially built for **MyISAM** Engine running primarily so **InnoDB** was not even considered or even tested out (fully when released) when Drupal was upgraded to support **InnoDB**. This semaphore table DEADLOCK issue still exists in Drupal 8 (https://www.drupal.org/project/drupal/issues/1898204 & https://www.drupal.org/node/2077827 ) and probably won't go away (https://docs.acquia.com/article/fixing-database-deadlocks). This also happens only on a very high load on the DB server and very difficult to test or replicate as a single threaded PHP process is interacting with a multi-threaded MySQL process.
3. **PHP** is a single process single thread running on the OS but **MySQL** runs in parallel and multiple threaded so multiple processes can update and delete a table at the same time which is why a deadlock happens as multiple requests to lock and unlock at the same time can occur (https://www.drupal.org/project/drupal/issues/1898204#comment-11080601)
4. **MyISAM** works differently in which the entire table is locked and the data is updated before it releases the lock so a concurrent transaction cannot occur until the table is unlocked. **InnoDB** works differently in the sense that a record on the table is locked rather than the entire table (row-level) locking (https://dba.stackexchange.com/questions/1/what-are-the-main-differences-between-innodb-and-myisam)
5. The steps taken where as per guidelines list in this article https://groups.drupal.org/node/415883. Unfortunately I could not perform the steps to convert it to a Memory Table is not allowed for data consistency (as a MySQL Cluster) and try and avoid changing **PRIMARY and UNIQUE keys** for this table.
```
 mysql> ALTER TABLE semaphore ENGINE = MEMORY;
ERROR 1071 (42000): Specified key was too long; max key length is 1000 bytes
Warning (Code 1105): Percona-XtraDB-Cluster doesn't recommend changing storage engine of a table (pdc.semaphore) from transactional to non-transactional with pxc_strict_mode = PERMISSIVE
Error (Code 1071): Specified key was too long; max key length is 1000 bytes
```
As this table is updated and deleted and no data is maintained in this table, I am not worried about this table in regards to data or its working as at any given point of time this table may or may not have data in it. It is being used as "temporary table" way similar temporary tables and deletes/create/updates in the way it works. Since consistency is not present in this table and no data is of any value, this change is not significant enough to warrant a snapshot.

Now seeing that this option has been done on the DB level, it can be reverted also. The core PHP / Drupal code has not been modified.

Revert Option:

```
 mysql>
ALTER TABLE `semaphore`
  ADD PRIMARY KEY (`name`, `value`) USING BTREE,
  ADD UNIQUE KEY `name` (`name`) USING BTREE,
  ADD KEY `value` (`value`) USING BTREE,
  ADD KEY `expire` (`expire`) USING BTREE;

```

Also I have set in the configuration for MySQL (my.cnf) as below:

```
#optional
wsrep_retry_autocommit = 4
wsrep_slave_threads = 16
wsrep_log_conflicts = ON

```

which tell the DB to RETRY at least 4 times before failing and log all conflicts rather than give up and become deadlocked and lock the Server completely.

To prove that this solution is currently working and gives a warning. I checked the error logs and noticed the below: 2017-11-27T19:06:54.407016Z 802376 \[Warning\] WSREP: Percona-XtraDB-Cluster doesn't recommend use of DML command on a table (pdc.semaphore) without an explicit primary key with pxc\_strict\_mode = PERMISSIVE in the error log here:

```
2017-11-27T19:01:39.746506Z 800686 [Note] WSREP: Victim thread:
   THD: 800686, mode: local, state: executing, conflict: cert failure, seqno: 14306430
   SQL: UPDATE users SET access='1511809315'
WHERE  (uid = '24216')

*** Priority TRANSACTION:
TRANSACTION 17680573, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
MySQL thread id 13, OS thread handle 140297469130496, query id 50384064 System lock

*** Victim TRANSACTION:
TRANSACTION 17680570, ACTIVE (PREPARED) 0 sec rollback
mysql tables in use 1, locked 1
ROLLING BACK
MySQL thread id 800686, OS thread handle 140296930600704, query id 50384061  wsrep: initiating pre-commit for write set (14306430)
UPDATE users SET access='1511809315'
WHERE  (uid = '24216')
*** WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 2178 page no 678 n bits 112 index PRIMARY of table "users" trx id 17680570 lock_mode X locks rec but not gap
2017-11-27T19:01:39.746856Z 13 [Note] WSREP: --------- CONFLICT DETECTED --------
2017-11-27T19:01:39.746871Z 13 [Note] WSREP: cluster conflict due to high priority abort for threads:

2017-11-27T19:01:39.746884Z 13 [Note] WSREP: Winning thread:
   THD: 13, mode: applier, state: executing, conflict: no conflict, seqno: 14306429
   SQL: (null)

2017-11-27T19:01:39.746895Z 13 [Note] WSREP: Victim thread:
   THD: 800686, mode: local, state: executing, conflict: cert failure, seqno: -1
   SQL: UPDATE users SET access='1511809315'
WHERE  (uid = '24216')

2017-11-27T19:06:54.407016Z 802376 [Warning] WSREP: Percona-XtraDB-Cluster doesn't recommend use of DML command on a table (pdc.semaphore) without an explicit primary key with pxc_strict_mode = PERMISSIVE
2017-11-27T19:06:54.476663Z 802376 [Warning] WSREP: Percona-XtraDB-Cluster doesn't recommend use of DML command on a table (pdc.semaphore) without an explicit primary key with pxc_strict_mode = PERMISSIVE
2017-11-27T19:06:54.854750Z 802376 [Warning] WSREP: Percona-XtraDB-Cluster doesn't recommend use of DML command on a table (pdc.semaphore) without an explicit primary key with pxc_strict_mode = PERMISSIVE
2017-11-27T19:08:23.716164Z 802666 [Note] WSREP: --------- CONFLICT DETECTED --------
2017-11-27T19:08:23.716206Z 802666 [Note] WSREP: cluster conflict due to certification failure for threads:

2017-11-27T19:08:23.716220Z 802666 [Note] WSREP: Victim thread:
   THD: 802666, mode: local, state: executing, conflict: cert failure, seqno: 14316816
   SQL: UPDATE users SET access='1511809719'
WHERE  (uid = '52770')

```

Notice it tried doing this 3 times before reporting a "WSREP: --------- CONFLICT DETECTED" which helps in debugging and does not bring your server/nodes down.
> 3 votes

---
Tags: 7, database
---


# Question
Title: Set default form values after AJAX callback
OK I know this question has been asked multiple times from people in different ways but I haven't been able to pinpoint my exact use case or solution.

I have a registration form that I want to prefill the default values after the user selects an option from a select list. After they select an option, AJAX fires off to see if the user is in our CRM, and runs a series of code to look up information. I then want that found information to show in the various form fields on the page.

Couple key things to point out that I often find in other solutions that do not work for me:

* The user is NOT submitting. They are still doing work on the form, the first form field sets up their experience going forward.
* Setting the field info in $form\_state\['values'\] doesn't work. Nothing is set.
* Settings the field info $form\_state\['input'\] does work, but then if a user changes any of the values in the fields, that new change isn't set.

Here is a stripped down example of what is being done.

```
function ces_user_registration_form_commerce_checkout_form_registration_alter(&$form, &$form_state, $form_id) {
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            $form['registration_information'][$name][$subname]['register_for']['#ajax'] = array(
                'wrapper' => 'commerce-checkout-form-registration',
                'callback' => 'ces_user_registration_form_register_for_ajax_callback',
                'method' => 'replace'
            );
            // run our code for comparing user values with CRM
            // return object with CRM data
            // below are example static value settings that I have

            // This works after AJAX is called, but the field isn't visually filled in for the user,
            $form['registration_information'][$name][$subname]['field_first_name']['und'][0]['value']['#default_value'] = "travis";

            // This works after AJAX is called, but changes to the field are not saved or recognized so we save their old value
            $form_state['input']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";

        }
    }
}

```

and the callback

```
function ces_user_registration_form_register_for_ajax_callback($form, &$form_state) {
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            if(!empty($form_state['values']['registration_information'][$name][$subname]['register_for']) && $form_state['values']['registration_information'][$name][$subname]['register_for'] == 'registration_registrant_type_me' ){

                // I tried moving the CRM code down here instead, but no changes
                // run our code for comparing user values with CRM
                // return object with CRM data
                // below are example static value settings that I have tried

                // doesn't work
                $form['registration_information'][$name][$subname]['field_first_name']['und'][0]['value']['#default_value'] = "travis";

                // doesn't work
                $form_state['values']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";

                // doesn't work
                $form_state['input']['registration_information'][$name][$subname]['field_first_name']['und'][0]['value'] = "travis";
            }
        }
    }
    return $form
}

```

# Answer
> 2 votes
I finally found a way to do this, though it appears this isn't the best way to do it - but it works.

You can not set `#default_value` for a field if the field is set in `$form_state['input']['field_name']`.

So before I try to set the field to the newly generated value, if I put this before then I can reset the default value.

`unset($form_state['input']['registration_information'][$name][$subname]['field_name']);`

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


# Question
Title: How to send an email using Rules to everyone in an Organic Group based upon a date field?
I have an OG content type with a date field. When the date in the field comes up, I want to use Rules to send an email to everyone in the group using the other fields (title/body/og name) in the node.

(Edit) My OG is "Teams" and the OG Content node type is "Events" with the date field. So when field\_date in Events is within 24 hours Rules will send out an email to all the OG Members of Teams.

I'm having a hard time wrapping my head around triggering the event based upon the date field and then send the node information to all the different users in the different groups.

# Answer
> 2 votes
To do what you're asking for, I would *only* use the Rules module, and the Rules Scheduler (a submodule of it), as further explained below.

### Step 1 - Create a Rules Component

Create a Rules Component which looks like so (in Rules export format):

```
{ "rules_send_notification_to_og_members" : {
    "LABEL" : "Send notification to OG members",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules", "og" ],
    "USES VARIABLES" : { "current_node" : { "label" : "Current node", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "current-node" ],
          "type" : { "value" : { "book" : "book" } }
        }
      }
    ],
    "DO" : [
      { "og_get_members" : {
          "USING" : { "group_content" : [ "current-node" ] },
          "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "group_member" : "Current group member" },
          "DO" : [
            { "mail" : {
                "to" : [ "group-member:mail" ],
                "subject" : "Friendly reminder about some post in group",
                "message" : "Hello [group-member:name],\r\n\r\nThere is a reminder about a post with title [current-node:title] (located at [current-node:url]) which belongs to one of the groups you are subscribed to.\r\n\r\nSome more details about this node:\r\n\r\n- Price: [current-node:field-book-price]\r\n- Release Date: [current-node:field-book-release-date]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Some details about the above Rules Component:

* Component Variables: only a "node" (of type "node"), of type "parameter", labeled "Current node", and machine name `current_node`.
* Rules Condition: use whatever extra condition you need/want, but actually you may not need any at all. As a sample, I just used "Content is of type" (with actual type = `book`).
* Rules Actions:
    + **`Get group members from group audience`**, for `current_node`, and store the result in a list with machine name `group_members`.
    + **`Perform a Rules Loop`**, for each item in the `group_members` list, whereas the item is named `group_member`. And for each iteration of this loop, send an eMail to the group member being processed, with all sorts of data about the node included in the eMail title and/or eMail body (use your own imagination to make it fit your needs).

### Step 2 - Create a Rules which schedules the Rules Component

Create a Rule which looks like so (in Rules export format):

```
{ "rules_remind_og_members_about_node_content" : {
    "LABEL" : "Remind OG members about node content",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "og", "rules", "rules_scheduler" ],
    "ON" : [ "node_insert", "node_update" ],
    "IF" : [
      { "og_entity_is_group_content" : { "entity" : [ "node" ] } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_book_release_date" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_notification_to_og_members",
          "task" : "Notify-OG-members-for-node-[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_notification_to_og_members",
          "date" : {
            "select" : "node:field-book-release-date",
            "date_offset" : { "value" : -259200 }
          },
          "identifier" : "Notify-OG-members-for-node-[node:nid]",
          "param_current_node" : [ "node" ]
        }
      }
    ]
  }
}

```

Some details about the above Rule:

* Rules Events (either of both):
    + After saving new content.
    + After updating existing content.
* Rules Conditions (all conditions must be true):
    + **`Entity group content`**, for entity = node.
    + **`Entity has field`** for field `field_book_release_date`, which is defined as a date field, and which you could consider as something like the release data of a book. Note: for nodes which don't have that field, or for which it is empty, this Rules Condition is false (so no Rules Actions will be performed).
* Rules Actions:
    + **`Delete scheduled task`**, with `Notify-OG-members-for-node-[node:nid]` as the "Task identifier", whereas the task refers to the Rules Component created in Step 1.
    + **`Schedule component evaluation`**, with `Notify-OG-members-for-node-[node:nid]` as the "Task identifier", whereas the task refers to the Rules Component created in Step 1. And the actual date to schedule the execution of this Rules Component, is the date indicated in the node's field `field_book_release_date`, but with an offset of `-3 days` (pick whatever value for this offset the fits your needs), so 3 days before the date indicated in that field, the Rules Component is executed.

To be complete: the first Rules Action (to delete the previously scheduled task with the very same Task identifier), is to ensure that the Rules Component is only executed once. The typical scenario is that first the node gets created (and the Rules Component is scheduled accordingly). But later on the node is updated. In that case, the request to execute the previously scheduled Rules Component is deleted, and a new request is scheduled again. And if the date itself was not updated, it will be scheduled for execution at the very same moment. But if the date was updated also, only the date of the most recent update will be taken into account. For this mechanism to work, it's important to use a unique Task Identifier, to be used in both Rules Actions. That's why I added the token `[node:nid]` to it (with a prefix like `Notify-OG-members-for-node-` so that it can be recognized by somebody looking at the currently scheduled Rules Components also).

### Bonus tip - Resolving potential access issues

By using the Rules Scheduler, in the end the Rules Component will be executed when cron is running (the very first time after the date/time the Rules Component was asked to be scheduled). But cron jobs always run with user Anonymous.

So the question that remains is: "How will the eMail content look like if you're processing a node for which an anonymous user has no access?". If you run in any such access issues, the easiest workaround I can think of is that you improve the Rules Component by adding additional variables (used as "Parameter"), and so that these variables contain the values of the relevant node's fields that you want to be able to refer to in the eMail to be created. Since the user who triggers the Rule from Step 2 (due to a create or update of a node) should have (read) access, for sure these values will be passed to the Rules Component at the time of scheduling the Rules Component.

PS: I'm assuming this question is about D7.

# Answer
> 1 votes
For this you should use VBO to provide a list of nodes to your rule. Here is an answer of mine that gives some detail for this.

When you get the list of nodes, you should be loop them, fetch the users for each, and send the email.

You should probably also add an `email sent` boolean field to the content type, set it to TRUE in the rule and then use that to filter out nodes in your view so emails don't get sent twice.

**More Detail:**

> For this, you probably need to use the latest Dev release which fixes an issue with VBO not supplying data to Rules.

**Views**

**View 1**: List of groups. You would add an extra filter here to get OG groups based on time.

**View 2**: List of users of a group. Note the contextual filter and the second image showing its settings.

**Rules**

**Rule**: This rule runs on Cron, grabs the Groups from View 1 and sends each group to a rule component.

```
{ "rules_test_og_2" : {
    "LABEL" : "Test OG",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "cron" : [] },
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "vbo_all_groups|block_1" },
          "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-list" ] },
          "ITEM" : { "current_group" : "Current Group" },
          "DO" : [ { "component_rules_og_helper" : { "node" : [ "current-group" ] } } ]
        }
      }
    ]
  }
}

```

Or in picture format.

**Rule Component**: This sends each group to View 2 and returns a list of users. The "body" condition and drupal message is to show how to use the group's fields in an email.

```
{ "rules_og_helper" : {
    "LABEL" : "OG Helper",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
    "IF" : [ { "entity_has_field" : { "entity" : [ "node" ], "field" : "body" } } ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "my_og_members_view|block_1", "args" : [ "node:nid" ] },
          "PROVIDE" : { "entity_list" : { "users_list" : "List of Users" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-list" ] },
          "ITEM" : { "current_user" : "Current User" },
          "DO" : [
            { "drupal_message" : { "message" : [ "current-user:mail" ] } },
            { "drupal_message" : { "message" : [ "node:body:value" ] } }
          ]
        }
      }
    ]
  }
}

```

Or in picture format.

I tested external cron with creating some nodes with user details and it worked fine. It looks complicated but is pretty easy, even with having to apply the patch.

What I haven't included here is an extra field on your content type that you would use as a filter in View 1 and change in your Rule so that emails only get sent once.

---
Tags: rules, organic-groups
---


# Question
Title: Remove required field in validation form
If I have a multiple field (ajax) required: FIELD\_A (N), and I want it not required if: FIELD\_B has a certain value. How can I do ? Any function in $ form\_state?

# Answer
Use states to style the input as required. This won't actually perform any validation but will add the required asterisk to the field when field B has a certain value.

```
$form['FIELD_A']['#states'] = [
  'required' => array(
    ':input[name="FIELD_B"]' => array('value' => 'foo'),
  ),
];

```

Then use custom validation to actually check FIELD\_A has the correct value depending on the value of FIELD\_B.
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to change the link text in Drupal 8 Views?
I have a simple problem that I can't seem to resolve despite everything I have tried. Googling for a answer has not turned up anything either. Here is my problem:

I have an entity A that references entity B. What I would like to do is be able to link to entity B's content (by that I mean click a link and be taken to the page the displays entity B's content). In Views you would use the "link to content" switch to accomplish this.

However here is the catch, I would like to use entity A's title as the link's text. I figured this would be an easy thing to do in Views, but no matter what I tried I can't do this.

I have tried rewriting the result in Views, but I can't find a reference to say that you want to link to entity B's url. Using the below substitution:

```
<a href="{{ entityB }}">{{ entityA_title }}</a>

```

you would get a link that looks like:

```
EntityB Title">EntityA Title

```

Where EntityB Title would link to Entity B's content and EntityA Title would link to a page that does not exist. It looks like you can't separate Entity B's title from its url - where I just want its url.

Is there a way to accomplish what I want to achieve? I figure this should be possible and straight forward to do, but apparently not.

Thanks.

# Answer
> 1 votes
Here's how I do this (just tested it, working):

1. Make sure you have a *relationship* to **Entity B** added to the view.
2. Potential gotcha: Make sure your **Title** *field* for **Entity A** is NOT a link already; you won't be able to use it as a title in a link rewrite if it is already a link. (If you want to rewrite a title that is already a link, you can add a second title, make the second one not a link, and then use that in your rewrite.)
3. Add a **Path** *field* that uses the **Entity B** *relationship*. Rewrite it like `<a href="{{ path }}">{{ entityA_title }}</a>`

---
Tags: views, 8
---


# Question
Title: Drupal Commerce - Database location of Shipping information
I am attempting to migrate the data located on the /admin/commerce/orders page of Drupal Commerce to a custom website that I have created. I am trying to use phpMyAdmin to locate and export any relevant database information in the Drupal database. I have found that the order id/email/timestamp are located in the commerce\_order table in the Drupal database. However, I can't find the location (table/table column) of the user's name and shipping information.

Does anyone have an idea of where I could find this information?

I am currently using Drupal 7.53 and Drupal Commerce 7.x-1.13.

# Answer
Drupal's entity data isn't really meant to be exported directly from the database. Is there no way for you to build a PHP script that uses the Drupal API to load and export these entities instead? Or an existing module like Patrick suggests?

Otherwise, you're going to need to pull information from a variety of tables. Shipping information is stored on an order's shipping customer profile. These are linked to the order via a customer profile reference field (whose table should be field\_data\_commerce\_customer\_shipping). From there you can find the customer profile ID you'll need to search for in the address field data, matching the profile ID against the entity\_id in the field\_data\_commerce\_customer\_address table.
> 0 votes

---
Tags: commerce
---


# Question
Title: Is it possible to get the field value of user reference autocomplete from username?
I am able to find the username. From the username I need to fill the user reference field.

Is there a way to get the user reference field value from username?

Example:

I have username: abc
I need Reference field value: Abc(201)

```
user_load_by_name('admin')

stdClass Object
(
    [uid] => 1
    [name] => admin
    [pass] => $S$DYk/jJiQjg07cciSAeU2EeP3XVMm/WhWHG19rA1iQf/FIqdOmY5p
    [mail] => test@gmail.com
    [theme] =>
    [signature] =>
    [signature_format] =>
    [created] => 1469189190
    [access] => 1511853833
    [login] => 1511853621
    [status] => 1
    [timezone] => Asia/Kolkata
    [language] =>
    [picture] =>
    [init] => test@gmail.com
    [data] =>
    [uuid] => 77ef7473-31cd-432e-ace6-26f1b075abb5
    [roles] => Array
        (
            [2] => authenticated user
            [3] => administrator
        )

    [rdf_mapping] => Array
        (
            [rdftype] => Array
                (
                    [0] => sioc:UserAccount
                )

            [name] => Array
                (
                    [predicates] => Array
                        (
                            [0] => foaf:name
                        )

                )

            [homepage] => Array
                (
                    [predicates] => Array
                        (
                            [0] => foaf:page
                        )

                    [type] => rel
                )

        )

)

```

# Answer
You can do this with user\_load\_by\_name($name).

Once you load the user object you should be able to access the reference field normally.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Translate with t() function from spanish as source
I have a Drupal 7 webpage already developed with all texts in Spanish, but now I want to add English language to the page. As all my texts are written in spanish, I would like to know what is the best/fast way to translate it to english. I tried with t() function, something like this t('Hola mundo') expecting to be manually translated by me with Drupal translation module (admin/config/regional/translate/translate) to 'Hello world'.

The Drupal 7 documentation says this: $string A string containing the English string to translate.

So my question is: is there any way to translate with t() from the default language (spanish)?

If it is not possible, how can I translate all the texts to english from spanish?

Thanks

# Answer
If you look at the API for `t()` \- https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7 \- you'll notice that it allows you do specify `$langcode` in the options array, however, that is a method to override the output language - not the input.

If you don't want to translate from English to Spanish, but the other way, there is a small quirk in Drupal localization framework. The *name* "English" in Drupal is reserved as the default index for languages, so you can't use that *name* for the target language. But please note that you don't *have* to use the index named "English" to hold English strings. You can use *anything* for that index. You can define new languages, and even invent them, so let us define a target language called "Ingles", and use that for English.

Now for each phrase you want to translate fro Spanish to English, you need to assign an index for lookup in the translation table. Let say you assign "¡Hola, mundo!" to be the index corresponding to the Spanish phrase "¡Hola, mundo!". On at least one page (it doesn't matter if it is Spanish, English or "Ingles, you must have `t("¡Hola, mundo!");` to get Drupal to pick this up. Now go to Drupal's translation interface and search for "¡Hola, mundo!". When you've found it, you can enter the correct strings for the Spanish original ("¡Hola, mundo!") into the field for "Spanish" and its translation into English ("Hello, world!") into the field for "Ingles". Do that with every phrase you want to translate from Spanish to English.

When done, you should be able to use `t("¡Hola, mundo!");` on a page with Spanish as its default language to make the user see "¡Hola, mundo!". To get the translation into English, you also use `t("¡Hola, mundo!");`, but make sure the page's default language is "Ingles" (not English). This is how you use `t()`-to translate from Spanish to "Ingles" (which is just an alias for "English" - we must use this alias since Drupal has reserved "English" to hold the default translation index).

However, you may find it a bit awkward to "invent" a new language called "Ingles". And there is a simpler way!

Instead of using "¡Hola, mundo!" as an index to "¡Hola, mundo!", you pick "Hello, world!" as your index. Otherwise, you proceed like before - to get this variable into Drupal's inserted into translation interface, you must on at least one page have `t("Hello, world");` (it doesn't matter if that page is Spanish, English or "Ingles).

Now, instead of "¡Hola, mundo!" showing up as am index in Drupal's translation interface, you'll see the index "Hello, world!". But just like before must enter the string "¡Hola, mundo!" as the Spanish original phrase, and for translation into "Ingles", you enter "Hello, world!".

However, now there it is also possible to get rid of the invented language "Ingles". It just so happens that if the default language for a page is English (not "Ingles"), `t();`will not look up the string in the table but just *return the index*. And since we're now using English phrases as index that index will be in English on pages where the default language is English. So we can stop using the the invented language "Ingles" and instead rely on getting the index back on English pages, while on Spanish pages, the index will be used for table lookup and we will get a Spanish string back.
> 1 votes

# Answer
Drupal does not translate anything for you. Drupal along with other modules simply provide functionality for you to easily manage your translations. Where you get these translations is entirely out of Drupal's hands. There are some modules that integrate 3rd party translation services such as Google translate, but most of these services are not very accurate.

Wrapping text in t() just allows Drupal to know that this is a translatable piece of text. Anything wrapped in t() will be accessible to modules so that you can supply the translation manually.

If you don't already have the internationalization modules installed, you should start there - but these will only help you manage your translations rather that translate for you. A good place to get started would be here and here.
> 0 votes

# Answer
You need a function that gets a string in default language (spanish) and returns it in the user's language (i.e. english). Right? Module `i18n` provides this function: `i18n_string_translate($name, $string, $options)`

More about it here:

https://www.drupal.org/node/1114010
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: How do I validate form elements in a modal without closing?
I'm using Drupal 8 and I have defined a custom entity type 'my\_entity\_type', with form handlers defined in the @ContentEntityType annotation:

```
 * @ContentEntityType(
 ...
 *   handlers = {
 *     "form" = {
 *       "add" = "Drupal\my_module\Form\MyEntityForm",
 *       "edit" = "Drupal\my_module\Form\MyEntityForm",
 *       "delete" = "Drupal\my_module\Form\MyEntityDeleteForm",
 ...

```

where:

* MyEntityForm extends ContentEntityForm
* MyEntityDeleteForm extends ContentEntityConfirmFormBase

These are routed in my\_module.routing.yml leveraging the \_entity\_form element:

```
_entity_form: my_entity_type.add

```

I am rendering the form from another form as a modal:

```
$form['add_my_entity_button'] = [
  '#type' => 'link',
  '#title' => t('Add NewEntity'),
  '#url' => Url::fromRoute(
    'my_module.add_entity',
    array(
      'node' => is_numeric($node) ? $node : NULL,
    )
  ),
  '#attributes' => [
    'class' => ['button', 'use-ajax'],
    'data-dialog-type' => 'modal',
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

```

All works as imagined. The '#required' type validator appears in the form in the modal.

# Goal

To add custom validation to this form's elements ('live' validation that does not close the modal). I recognize that this type of problem isn't novel, and I've done it often in non-modal forms. The methods I would usually leverage are:

* '#element\_validate' form element callback
* validateForm() type form callback

Both appear to require submission of the form, close the modal, and render the errors in a flat form display. I then combed through Core for ideas and embarked on a remarkably twisted yak-shaving journey:

1. **Adding validation via BaseFieldDefinition::addConstraint in the entity baseFieldDefinitions()** : This still submitted the form and led to a flat (non modal) form with errors correctly thrown. Once I solve this problem, I will likely leave this in to serve as a gatekeeper at the storage level.
2. **Extending the 'number' FieldType via Plugin, extending the widget, type or storage** : This seemed overly complex for something as simple as adding a validator. I bailed on this before getting too far, since I considered:
3. **Injecting a generic '#ajax' 'replace' callback to the element inside buildForm() in MyEntityForm** : I could NOT get ajax inserted in this manner to fire here.
4. **Injecting a generic '#ajax' 'replace' callback to the element in hook\_form\_alter** : I could NOT get ajax callbacks inserted in this manner to fire either.

# Questions

What have I missed? I feel this is simple. Is there something I've missed in Form that defines simple ajax validation?

Is there a standard way for validating form elements inside modals without closing the modal?

Can AJAX 'replace' callbacks be attached to forms defined and routed via the @ContentEntityType annotation? Is there a restriction here in the render pipeline?

# Answer
This is a excellent article which you can read for "fixing" your issue: http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Keep in mind this lines:

First, we wrap our form with a div

```
public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  // It is important this id
  $form['#prefix'] = '<div id="modal_example_form">';
  $form['#suffix'] = '</div>';

  // The status messages that will contain any form errors.
  $form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
  ];

  // more code

  $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit modal form'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      // Function to call when the users click on submit button.
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // more code
}

```

Second, we show the errors:

```
/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    // Remember the previous id ? Here it is
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}

```
> 3 votes

---
Tags: 8, forms
---


# Question
Title: How to get Responsive Image Styles to work with existing images?
We have existing images that never had an image style applied to them. As part of the cleanup, we are now using Responsive Image Module to do this per breakpoint. AFter creating the different image styles, we created the appropriate Responsive Image styles and applied them to the image fields through the View Modes. However, when we load the page after the Responsive image styles is applied, we get a 404 error for the image's URL. Looks like it did not create one.

How can we create the necessary images with the appropriate image styles such that we only need to modify/clear the images for that image style? We attempted to re upload the image and deleting it and adding it, but neither worked.

We even attempted the following Drush commands but they did not work. According to Drush Commands for image flush the images would be regenerated on the fly but that is not happening.

```
drush if --all
drush if max_650x650

```

Updated solution:

I simply changed themes and then switched back to my desired theme and it seemed to work. It was very odd, but effective. I did not have to make any other changes.

# Answer
You have cleared cache? This is when Drupal will generate the images based on any image style applied in the display settings.

"drush cc all" or "drush cr" depending on your version.

Unfortunately I have never used the Responsive Image Module so cannot say why you get a 404.
> 0 votes

# Answer
What web server are you using? If nginx you might want to look at your site config.

I have the following in my drupal nginx config:

```
  # Set up a rewrite.
  location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ ^/sites/.*/files/styles/ { # For Drupal >= 7
    try_files $uri @rewrite;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
    try_files $uri @rewrite;
    expires max;
    log_not_found off;
  }

```

Since you said you never used image styles before, I assumed you might be missing these in your configuration.
> 1 votes

---
Tags: 8, media, theming
---