# Question
Title: "View" with article shown according to detection/selection language
I would like to create a View (using the View module) to show my translated article separately according to the url path. Doing so, going to www.mysite.com/fr/blog should only show my article with the term "story" in french and going to www.mysite.com/en/blog should only show my article with the same term "story" in english.

* I added an Entity translation relationship
* I added an entity translation "language" set as "current user's language"

But none of my article are displayed on the views whatever the language path I use.

Here is my Views configuration:

Many thanks for your help!

# Answer
When 'FR' detected on Url default language of website will be changed So you have to Set it to `Default Site Language`
> 0 votes

# Answer
Use a contextual filter and set to use a url position if not provided. Use the 1st argument (the language selection) and provide a default value if need be.

EDIT:

Something like this:
> 0 votes

---
Tags: 7, views, i18n-l10n
---


title: How do I overwrite a lazy service?

text:
# Question
Title: How do I overwrite a lazy service?
I'm trying to have my D8 site use Memcache for the lock service backend instead of using MySQL which is the default.

In `core.services.yml` we have the lock defintions:

```
  lock:
    class: Drupal\Core\Lock\DatabaseLockBackend
    arguments: ['@database']
    tags:
      - { name: backend_overridable }
    lazy: true
  lock.persistent:
    class: Drupal\Core\Lock\PersistentDatabaseLockBackend
    arguments: ['@database']
    tags:
      - { name: backend_overridable }
    lazy: true

```

In my site's `default.services.yml` I have this:

```
services:
  # Replaces the default lock backend with a memcache implementation.
  lock:
    class: Drupal\Core\Lock\LockBackendInterface
    factory: ['@memcache.lock.factory', get]

```

But when I obtain the `lock` service via `\Drupal::service('lock');`, I get a class `Drupal\Core\ProxyClass\Lock\DatabaseLockBackend` returned instead of an instance of `Drupal\memcache\Lock\MemcacheLockBackend`. So my override did not work.

Unfortunately there's no documentation in the D8 memcache module for doing this, I'm just kind of winging it.

Perhaps it has something to do with the fact that the original service is lazy loaded?

# Answer
> 3 votes
default.services.yml is just basically just documentation/ an example, it's not actually loaded, at least not by default.

To load a services.yml file, it either needs to be named services.yml, or you need to explicitly added to the settings.php file, see example.settings.local.php and how it loads development services.

The redis module also provides implementations for those services, and it does so by providing a separate example.services.yml file that you can either include directly or copy and customize. That definitely works, I wrote and tested it.

# Answer
> 1 votes
The accepted answer is the best way to do this; this is an alternative.

### src/MyCustomModuleServiceProvider.php

```
namespace Drupal\my_custom_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class MyCustomModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = new Definition('Drupal\Core\Lock\LockBackendInterface');
    $definition->setFactory([new Reference('memcache.lock.factory'), 'get']);

    $container->setDefinition('lock', $definition);

    $definition = new Definition('Drupal\Core\Lock\LockBackendInterface');
    $definition->setFactory([new Reference('memcache.lock.factory'), 'getPersistent']);

    $container->setDefinition('lock.persistent', $definition);
  }

}

```

Note the naming of the class is special so that Drupal will automatically detect it: It is required to be a camel-case version of your module's machine name followed by *ServiceProvider*.

---
Tags: 8, caching
---


# Question
Title: Moving field content to new field collection fields automatically
I'm working on existing site which has small boxes with an image, title & text in them multiple times on a page. Currently it uses fields for each one so there'll be six image fields, six title fields, etc but I'd like to making them all one field in a field collection which can be added multiple times.

Creating the new field collection an appropriate fields is fine but what is the best way of moving the existing multiple field images, titles, etc to the field collection?

# Answer
* Create your Field collection,
* Add new fields to it
* Add field Collection Field To your content type
* Create a Custom module ( if you don't have)
* With Getting help of Batch Operation Docs, Create A Batch Operations on your desired content type
* On each epic load node, get your fields data,
* Add those values to field collection ( add an item at field collection programmatically)
* Check the Results
* remove old fields from the content type

**I Strongly Recommend befor write batch, try it on one node, I mean create a route ( I mean item with hook\_menu) then in call back try to achieve what you want, after success convert it to a batch operation or do it with VBO + Php Filter module(instead of batch processing)**
> 0 votes

---
Tags: 7, entities
---


title: How to get translated month labels

text:
# Question
Title: How to get translated month labels
I think, this labels and its translations are available, but I don't know where. I found nothing in the "Translate Interface" seach.

So here's my question: is there a way to get translated month labels more elegant as like `t('january')` ?

# Answer
Normally date labels (months, day, etc. in short and long version) should be translated automatically according to the language configured for Drupal interface (*admin/config/regional/settings*).

However, in case there might have been an issue somewhere, with Drush and the module Localization update enabled the following command forces the translation to be updated and it solved the issue in my case:

```
drush l10n-update

```
> 0 votes

# Answer
Based on GZBK's answer, I had to do following to get things right:

drush l10n-update-refresh

drush l10n-update
> 0 votes

# Answer
You can translate the month and weekname labels using the translation interface at http://example.com/admin/config/regional/translate/translate

The search is case sensitive.

To ensure that the month names or week day labels are available for translation, you can fashion a custom module such as suggested in this comment: https://drupal.org/comment/8251325#comment-8251325

Strings are only available for translation after the first time they are processed by the t() function in Drupal 7.
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Programmatically add new role to group member
Trying to update a group membership to add an additional role, but cannot find any help on how to do this.

I want to add the role of "manager" to all owners of "client" type groups, using the following code:

```
// Get the group owner
$owner = $group->getOwner();

// Get the membership details of the owner
$membership = $group->getMember($owner);

// Get the roles of the owner
$roles = $membership->getRoles();

// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
  // No, so add the manager role to the membership
  // >>> The following doesn't work, but I hope you get the idea <<<
  $manager = new GroupRole();
  $membership->addRole($manager);
  $membership->save();
}

```

Any help or advice with this problem appreciated.

I was using hook\_group\_user\_roles\_alter(), but this has been removed in the latest release (8.x-1.0-beta5), so now need to implement a db update function to set it permanently.

# Answer
> 4 votes
I was eventually able to find the correct process. The working code follows:

```
// Get the group owner
$owner = $group->getOwner();

// Get the membership details of the owner
$membership = $group->getMember($owner);

// Get the roles of the owner
$roles = $membership->getRoles();

// Check whether the owner has manager role
if (!isset($roles['client-manager'])) {
  // No, so add the manager role to the membership
  // Get the group_content entity
  $group_content = $membership->getGroupContent();
  // Set target group role
  $group_content->group_roles->target_id = 'client-manager';
  // Save updated entity
  $group_content->save();
}

```

Thanks for your help.

---
Tags: 8, group
---


title: Change URL of Node Title

text:
# Question
Title: Change URL of Node Title
Bit of an odd request. I want to somehow change/alias the URL of a node to an external website. We are importing a calendar of events from our booking vendor to show nicely on our page. In the end, the user must go to the booking vendor website to enroll though. While I want all the imported data to be able to be shown on our website (so we can show snippets in blocks, and so forth), I want the node link to go to the event on the booking website. Our import does include the booking URL for each event.

I tried using the rules module to overwite the node:url on import, but it obviously does not allow this. I assume I could work some wizardry in views, but I would need the URL to change for blocks, calendar views, list views, etc. Is there some way to make a node always redirect to an external URL based on the import I am using "Feeds import" with an iCal feed?

To make it harder, I also lack any code level access.

This is probably a hail mary, but I figured I would ask. Thanks!

# Answer
Ok so since you already have a url field:

* Set up a new rule where the event is `Content is viewed of type YourContentType`.
* Add a `Page redirect` action.
* For the destination use your field as a replacement pattern. So something like: `node:field-url`.

Just take note that you won't be able to view your content with this rule. But you can still access the edit page using the content management interface.

---

Just for your information, if you DO get access to the code:

You can use `hook_node_view` to create redirects. Since you already have the event URL in the node data you can use a `drupal_goto`.

Here's a snippet I found in a related question. I changed some things though.:

```
module_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && "Conditions") {
    // Change $node->url to what works.
    // Use the devel module and krumo() to check the contents of $node.
    drupal_goto($node->url);
  }
}

```

I've assumed you're using Drupal 7.
> 0 votes

---
Tags: rules, feeds
---


title: How do I create a computed field?

text:
# Question
Title: How do I create a computed field?
I'm creating a Webform in Drupal 8. On the form, I have two number fields; when a user populates them with values, a third field will display the value of the two field multiplied together.

How can I create that computed field?

P.S. If the user changes the values in either the fields, I need the value in the computed field to update on the fly.

# Answer
> 1 votes
There is a recipe for How to implement client-side calculations.

---
Tags: webforms
---


# Question
Title: How to query the last 5 nodes of multiple content types?
I want to query last 5 nodes of multiple content types, say, `typeA`, `typeB`, `typeC`, `typeD`.

It was originally only one content type, and I did it using EntityFieldQuery:

```
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'typeA')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 5);

$result = $query->execute();

```

But now I need to include 3 other content types to the list.

Is there any way to expend this query to include the last 5 nodes of the other 3 content types as well. So that the result will have 5 last nodes from all 4 content types, altogether 20 nodes.

Or should I do it with 4 individual queries?

# Answer
> 2 votes
I think the only thing you need is alter the second line of your EntityFieldQuery to this:

```
->entityCondition('bundle', array('typeA', 'typeB', 'typeC', 'typeD'), 'IN')

```

Haven't tested this particular though, but you can query multiple content types this way.

Cheers

EDIT: Maybe this can help you more: https://www.drupal.org/node/2048345

# Answer
> 1 votes
Try something like the following codes:

```
$types= array('type1','type2','type3');

foreach ($types as $type) {
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'typeA')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 5);
  $temp = $query->execute();

  if (isset($temp['node'])) {
    $result[$type]['nids'] = array_keys($temp['node']);
    $result[$type]['nodes'] = node_load_multiple($result[$type]['nids']);
  }
}

/// then you can load them by

```

# Answer
> 0 votes
I think as other have suggested using UNION is going to be the easiest way to do it with one query:

```
$nids = db_query("(SELECT nid FROM node WHERE type = 'typeA' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeB' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeC' ORDER BY changed LIMIT 0, 5)
UNION
(SELECT nid FROM node WHERE type = 'typeD' ORDER BY changed LIMIT 0, 5)")->fetchCol();
$nodes = node_load_multiple($nids);

```

I was playing with a way to do it using numbered rows but it doesn't get the latest nodes so I gave up, but here is the sql in case your interested in fixing it:

```
SELECT nid, title, type, changed
FROM (
    SELECT nid, title, type, changed,
    @num := if(@group = type, @num + 1, 1) as row_number,
    @group := type as dummy
    FROM   node
    WHERE type IN ('typeA', 'typeB', 'typeC', 'typeD')
    ORDER BY type, title
) AS x
WHERE  row_number <= 5
ORDER BY type

```

Also see this very relevant SO question MySQL:How to get n latest rows of a distinct type

# Answer
> -1 votes
the best way you can do it is to user db\_select(); I would do something like this:

Set the array with the content type machine names.

```
$arrayofnodetypes = array('page','post','poll');

```

here you select the table

```
$query = db_select('node','n');
$query->fields('n',array('nid','title','status','type')); // this are the fields your want to fetch
$query->condition('n.status','1','='); // node is published
$query->condition('n.type',$arrayofnodetypes,'IN'); // this is where you call the content types.
$query->orderBy('created','DESC');
$query->range(0,20);

$results = $query->execute()->fetchAll();

```

Then you have 2 options.

**the first:**
if you want to fetch all fields in the node, you need to manualy join the fields in the $query see the following resource if you want to learn more: https://www.drupal.org/node/1848348

**the second:** the $results variable will have the results of the query.

I would then foreach each result of the array.

like the folowing;

```
$nodes = array();
foreach($results as $item) {
  $nodes []= node_load($item->nid);
}

```

then the $nodes array will contain the results you need.

# Answer
> -1 votes
You could also use node\_load\_multiple.

```
$types = array('content_type_1', 'content_type_2', 'etc');
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', $type, 'IN');

$result = $query->execute()->fetchAll();

$nids = array();
foreach ($result as $row) {
  $nids[] = $row->nid;
}

$nodes = node_load_multiple($nids);

```

---
Tags: 7, nodes, database
---


title: How to get date field object value?

text:
# Question
Title: How to get date field object value?
datetime object is

```
[start_time] => Array
                (
                    [0] => Array
                        (
                            [value] => Drupal\Core\Datetime\DrupalDateTime Object
                                (
                                    [formatTranslationCache:protected] =>
                                    [inputTimeRaw:protected] =>
                                    [inputTimeAdjusted:protected] =>
                                    [inputTimeZoneRaw:protected] =>
                                    [inputTimeZoneAdjusted:protected] =>
                                    [inputFormatRaw:protected] =>
                                    [inputFormatAdjusted:protected] =>
                                    [langcode:protected] => en
                                    [errors:protected] => Array
                                        (
                                        )

                                    [dateTimeObject:protected] => DateTime Object
                                        (
                                            [date] => 2017-03-17 02:04:03.000000
                                            [timezone_type] => 3
                                            [timezone] => UTC
                                        )

                                    [stringTranslation:protected] =>
                                )

```

How to get **\[date\] =\> 2017-03-17 02:04:03.000000** ??????

I have tried using `print_r($ruleContentNew[0]['start_time'][0]['value']->getValue());die;` But it is giving me error.

# Answer
> 8 votes
> Try
>
> $node-\>get('start\_time')-\>getValue();

This actually gives you an array, if you inspect/dump the array, then you'll see that you can get the value like this.

`$node->get('start_time')->getValue()[0]['value'];`

Alternatively, you can simply use `$node->start_time->value;`

**Note:** I am using the default Date field from Core and assuming you're using a Node. Hence the `$node`, and also worth noting, usually your date machine name will be `field_something`. Which makes me believe that OPer is using some contrib or custom module.

If you're using some contrib module that allows you to have start and end times on your date field, probably will require a diff solution.

# Answer
> 3 votes
Try

```
$node->start_time->value;

```

or if it's multi value

```
$values = $node->get('start_time')->getValue();

```

---
Tags: 8, entities, datetime
---


# Question
Title: block to display nodes using entityQuery with pager
I am trying to figure out how to create a block that displays recent content using a pager that can fetch the next set of nodes here is what I have so far `/modules/example_module/example_module.info.yml`

```
name: Example Module block with pager
description: 'Example Module block with pager'
core: 8.x
type: module
dependencies:
- node
- block
type: module

```

`/modules/example_module/src/Plugin/Block/ExampleModuleBlock.php`

```
<?php
namespace Drupal\example_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Display all instances for 'ExampleModuleBlock' block plugin.
 *
 * @Block(
 *   id = "example_module_block",
 *   admin_label = @Translation("Example Module"),
 *   category = @Translation("Example Module"),
 * )
 */
class ExampleModuleBlock extends BlockBase {
  public function build() {
    $output = example_module_get_content();
    $out = [
      '#markup' => $output,
      ],
    ];
    return $out;
  }
}

```

and `/modules/example_module/example_module.module`

```
<?php

function example_module_get_content(){
  $out = "";
  $nids = example_module_query();
  foreach($nids as $nid){
    $node = \Drupal\node\Entity\Node::load($nid);
    $out .= "<div>" . $node->getTitle() . "</div>";
  }
  return $out;
}

function example_module_query() {
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->sort('created', 'DESC')
    ->pager(10);
  $nids = $query->execute();
  return $nids;
}

```

which creates a block that can be placed on a theme and displays the latest/recent 10 nodes on the drupal site.

Well I can probably devise a way to query the database and figure out a way to create a custom pager and probably use `$current_path = \Drupal::service('path.current')->getPath();` to get the pager PAGE but I was wondering if there is an obvious way that could greatly help and I don't have to reinvent the wheel

what is the deal with `pagers` are they of any help here ?

# Answer
> 4 votes
The first step is to include a pager in the query `$query->pager(10)`, which you have already done. Then you need a render element pager:

```
  $build['result'] => $out;
  $build['pager'] = [
    '#type' => 'pager',
  ];
  return $build;

```

If you have multiple pagers on the site, which is probably the case for a block placed on different pages, you have to connect query and pager with a pager id:

```
  $element = '123';

  $query->pager(10, $element);

  $build['pager'] = [
    '#type' => 'pager',
    '#element' => $element,
  ];

```

# Answer
> 0 votes
If you're trying to insert a block with list of nodes and pager then views will be your best bet. Drupal 8 comes pre installed with views so its just a matter of creating a view block and assign it to a region. Of course you can turn ajax on and attach a pager to it.

---
Tags: 8, entities, blocks
---


# Question
Title: Display Related Nodes by Taxonomy Terms in Block
There are numerous articles on how to display related nodes from taxonomy. In all these articles, it states to set contextual filter: Has Taxonomy Term & select option: Taxonomy Term ID from URL.

In my case, I do not have any taxonomy term in the node URL

I want to display nodes which have common terms when the term is NOT in the URL.

I have tried the approach in many articles that require the option: Taxonomy Term ID from URL & select "Load default filter from node page, that's good for related taxonomy blocks" and further to select the Vocabulary.

I have tried this approach, however, it does not show any related content, possibly as I do not have any terms in the URL?

Please advice.

# Answer
> 2 votes
Resolved it by using the following method:

Under Advanced → Contextual Filter: "Vocabulary Name" → Taxonomy Term ID from URL → Load default filter from node page, that's good for related taxonomy blocks → Select Limit terms by vocabulary → Select the appropriate Vocabulary → Under "Multiple-value handling" Select the appropriate option as per your requirement (either "Filter to items that share all terms" OR "Filter to items that share any term". That's it. It worked for me.

---
Tags: 7, taxonomy-terms, views
---


# Question
Title: internal server error after deleting thumbnails image-style
I have an internal server error on my drupal site only when I log in, when logged out everything is fine.

I was having problems with the default image-styles, they would not work (no thumbnail preview) so I created a new style (thumbnail2), deleted the default thumbnail style and replaced it with thumbnail2 style.

Any ideas how I recover from this?

So 2 problems:
1. get access to admin again
2. get default images styles to work

Server log:
Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "view.media.media\_page\_list" does not exist."

# Answer
After some googling I saw a similar error on Drupal.org

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

Check the last few comments. It might be related to Media Entity
> 0 votes

---
Tags: 8, media
---


# Question
Title: Passing Node ID/Title to Next Page Webform Field
I am new to drupal 8 and assisting my development team with design part. We are stuck in one place and not manage to move forward. We want to pass the node ID info to a webform filed which exist in another page. In the attached image I have explained what we want to achieve in **Drupal 8 Environment**, previously with PHP hack it was possible in drupal 7 but no idea how to achieve the same in drupal 8.

# Answer
> 0 votes
Assuming you want: The user will create a node. Upon submission a form will be displayed showing the node id pre-filled in a form. Make a module called example:

```
// example.module:
// we created a node type "product" (using UI). Saving this content
// will trigger the product form
/**
 * Implements hook_ENTITY_TYPE_insert().
 * @param \Drupal\node\NodeInterface
 */
function example_node_insert(NodeInterface $node) {
  if ($node->bundle() == 'product') {
    $nid = $node->id();
    $response = new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal\Core\Url::
    fromRoute('product.form', ['nid' => $nid])->toString());
    $response->send(); // When OO we will return the response object instead
  }
}

// example.routing.yml
product.form:
  path: '/form/product/{nid}'
  defaults:
    _form: '\Drupal\example\Form\ProductForm'
    _title: 'Product Form'
  requirements:
    _permission: 'access content'

// src/Form/ProductForm
<?php

namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class ProductForm extends FormBase {

  /**
   * @var NodeInterface
   */
  protected $node;

  public function getFormId() {
    return 'example_product_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $nid = null) {
    // if you need to load the node
    // $this->node = NodeInterface::load($nid);

    $form['node_id'] = [
      '#type' => 'textfield',
      '#title' => 'Node ID',
      '#value' => $nid,
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // TODO: Implement submitForm() method.
    // you can redirect back to the node
  }

}

```

When dealing with this issue please realize the node id is not available until you save the node.

# Answer
> 0 votes
Webform 8.x-5.x allows elements to be populated using query string parameters but you must enable this feature.

Another approach would be to set the element's default value to a `[current-page:query:?]` token like `[current-page:query:nid]`

# Answer
> 0 votes
Trying using the \[webform\_submission:node:title\] within the confirmation redirect URL's querystring parameter.

BTW, you must use an absolute URL. I just found this bug and created a issue on D.O. https://www.drupal.org/node/2864996

---
Tags: theming, webforms
---


# Question
Title: How do I create a route that is specific for a subdomain?
I'm looking to create a "subdomain" path to my custom controller running on a Drupal 8 site, with routing and hopefully without the need for an additional module.

The idea is to for example have a route like account.example.com or dev.example.com point to a custom controller I've made in my module. Or a path like api.example.com for external REST queries.

All the documentation describe just the traditional example.com/path methods, and googling resulted to nothing, but the domain module, which seems excessive and maybe for a different purpose even.

What I wish to achieve is not a separate installation sharing the content, but just a path to my controller that is domain-specific, like the i18n module is able to provide the language parameter as subdomain or path prefix.

# Answer
If you want to set a controller for subdomain you just create a subdomain and handle it by DNS and web server, then set your subdomain path as root path for the subdomain on your web server, I mean both main domain and subdomain will be the same. As you said, you can create a route/controller for them (because the code and modules are the same, so routes will be available on both).

If you don't want the subdomains available on your main domain, on your handler check the domain name; if a request comes from the main domain, don't return the result for it. (Redirecting it to the homepage could be an idea.)

**But** the power of Symfony shows itself to us: Instead of manually handling the domain and subdomain filtering on the route, use `host` in the route definition.

```
   host: "dev.example.com"

```

Take a look at How to Match a Route Based on the Host for further help about using that directive.
> 2 votes

---
Tags: routes
---


# Question
Title: How do I create content of the day/week/month?
I have a (growing) number of articles. I want to display one on the homepage as article of the week, although that week will probably be a day in the beginning and a month later on. I also want a specific editor be able to choose which of those articles will be the chosen one for a given time period. There will only be one chosen article for any given time. What is the best way to do this (preferably without programming)?

I first thought of creating a vocabulary (with a date field and an entity reference to an article field) for this where the editor can simply add days/weeks/months as they come and select from the articles. The bad part here is that the name field is required and I cannot ui wise set it to take the name from the actual date field.

Making it then a custom content type instead would probably work, but seems overkill.

Adding an article of the timeperiod date field to the article content type would also seem to encapsulate all the necessary information, but how do I expose this to the editor?

I want the editor to see a list of the coming say 20 months and assign to each an article on the same page (a single save operation from the editor's point of view). I also want the editor to be able to override that for specific shorter time periods.

I'm using Drupal 7.

# Answer
Using the Flag module seems like a no brainer to me to get this to work: introduce a global flag that is allowed to be used by your editors to flag relevant articles. Since Flags are *fieldable*, you could add extra field(s) to such flags to let the flagging user indicate an appropriate start date and end date.

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the flagged article(s) for which their flag fields (start / end dates) have appropriate values as compared to the current date.

This solution is "*without programming*" (as in your question) ...

Ps: I'm assuming this is about D7.
> 3 votes

---
Tags: views, nodes, taxonomy-terms, panels, datetime
---


# Question
Title: How to load the immediate parent link in a preprocess function?
I am using menu block to show a section of the navigation. I have a requirement to show the parent link at the top, but that would not gel with the menu configuration.

Therefore, I should be able to solve this by taking the first link in the list, and loading the parent. Then, I want to add that as a variable, and render it in my twig file above the loop that would output the entire link tree. However, I am coming up short on how to do this effectively.

So far, I have:

```
function mytheme_preprocess_block__menu_block(&$variables) {
  if ($variables['elements']['#id'] == 'left_navigation' && !empty($variables['elements']['content']['#items'])) {
    $children = $variables['elements']['content']['#items'];
    $top_child = key($children);

    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $menu_link_parents = $menu_link_manager->getParentIds($top_child);

    // the one we want should be the second one. the first one is the one in the main navigation across the top.
    $parent = end($menu_link_parents);
    $parent = str_replace('menu_link_content:', '' , $parent);
    $menu_content = current(\Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $parent)));

    $variables['top_parent'] = [
      'title' => $menu_content->getTitle(),
      'url' => $menu_content->getUrlObject()
    ];
  }
}

```

I am lost at the point I retrieve the parent. Is there a way to get the UUID instead of the dirty str\_replace? Also, how can I take that UUID, and create an object similar to menu items that would be rendered?

# Answer
> 1 votes
I think you can do it with the 'plugin.manager.menu.link' service:

```
$link = $this->menuActiveTrail->getActiveLink();

if(!empty($link->getParent())) {
  $parent_link = Drupal::service('plugin.manager.menu.link')->createInstance($link->getParent());
  $menu_item = MenuLinkContent::load($parent_link->getMetaData()['entity_id']);
}

```

This way you don't have to replace the prefix.

---
Tags: 8, navigation
---


# Question
Title: Not able to assign value to field using form_alter hook
I have a add entity form. On which I want show some fields pre-populated from other entity. I wrote form\_alter hook and pre populate fields.... But for one field it wont work. It populate the data in text box but when user change that data and click on save it saves pre populated data not the changed or updated one.

Scenario 1: "field\_summary\_introduction" this is a text area and code used to prepopulate data is $form\['field\_summary\_introduction'\]\['und'\]\[0\]\['#value'\] = $arrDefaultEntityData\['field\_summary\_introduction'\]\['und'\]\[0\]\['value'\];

This is working fine and if user update the data it stores updated data

Scenario 2: "field\_company\_subtitle" this is text field and following code is not working

```
$form['field_company_subtitle']['und'][0]['#value'] = $arrDefaultEntityData['field_company_subtitle']['und'][0]['value'];

```

Instead if I use following code then it prepopulate data

```
$form['field_company_subtitle']['und'][0]['value']['#value'] = $arrDefaultEntityData['field_company_subtitle']['und'][0]['value'];

```

But not able to store updated data it stores prepopulated data.... All fields in my form taking populated data to save in db. If user update the populated data it saves old populated data in database. Thanks in advance

# Answer
> 0 votes
You need to use `#default_value`:

```
$form['field_company_subtitle'][LANGUAGE_NONE][0]['value']['#default_value'] = ...

```

---
Tags: forms, hooks
---


# Question
Title: How to pass argument in service with dependency injection
In a custom module, I have a custom service that uses GuzzleHttp\Client service.

mymodule.services.yml:

```
services:
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@http_client']

```

The MyModuleCall is using dependency injection and start like:

```
namespace Drupal\mymodule;

use GuzzleHttp\Client;

class MyModuleCall {

  protected $client;

  public function __construct(Client $client) {
        $this->client  = $client;
  }

}

```

As explained in the GuzzleHttp documentation (http://docs.guzzlephp.org/en/latest/quickstart.html), we can pass an argument to the Client constructor to set the base\_uri.

Like so:

```
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://httpbin.org'
]);

```

How do we set the 'base\_uri' in the constructor when we use dependency injection to instantiate a class?

# Answer
> 3 votes
While it would not be possible to use the `http_client` service it is possible to use the factory service (or create your own factory service if you choose not to rely on core methods).

The `http_client_factory` service provides a `fromOptions` method.

The Symfony2 documentation has a section on using parameters:

> Use the parameters section of a config file to set parameters:

```
parameters:
  mymodule.http_client.config:
    base_uri: 'http://httpbin.org'

services:
  mymodule.http_client:
    factory: '@http_client_factory:fromOptions'
    arguments: ['%mymodule.http_client.config%']
  mymodule.mymodule_call:
    class: Drupal\mymodule\MyModuleCall
    arguments: ['@mymodule.http_client']

```

Now the MyModuleClass will use Guzzle with Drupal's default configuration and custom configuration.

Note: it is also possible to provide your own factory service for Guzzle and to use that directly. This would be useful if you need to use your own overridden Guzzle\Http\Client class (I do this in a contrib module). This would probably be necessary to inject custom configuration such as handler stack (OAuth1).

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


title: Add custom fields to image field

text:
# Question
Title: Add custom fields to image field
I have a case where I need to add three custom fields to each image in an image field to hold data. The content of these fields will not be displayed, but will only be indexed into Solr so they can be used in a custom image search. The logical place for these fields is in the same place that the Alt and Title fields are displayed (when enabled in the field settings), so that they can be entered in when the image is attached. Considering all the field API goodness in D7, it seemed like this would be pretty straightforward. However, it's not turning out that way.

One suggestion was to use the File Entity module, so I can add custom fields. This seems to work great, in that it allows me to add fields through the UI to the file entity. However, the problem is that these fields are not available when actually attaching the image to a node - they are only available when you add an image at /file/add.

After looking at the code in image.module, I noticed that the Alt and Title fields are added in the #process callback, which in turn is added in the hook\_field\_widget\_form() imeplentation (image\_field\_widget\_form()). Since there is an alter hook (hook\_field\_widget\_form\_alter()), I implemented it and added my own #process callback:

```
function nb_alters_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_images') {
    // Add a custom #process function to add the fields.
    $element['#process'][] = 'nb_alters_image_process';
  }
}

```

and then added my callback (using code suggestion found here:

```
function nb_alters_image_process($element, &$form_state, $form) {
  if (isset($element['#type']) && ($info = element_info($element['#type'])) && isset($info['#process'])) {
    foreach ($info['#process'] as $process) {
      $process($element, $form_state);
    }
  }

  // Add the additional Person, and Organization fields.
  $element['person'] = array(
    '#title' => t('Person'),
    '#type' => 'textfield',
    //'#default_value' => isset($item['person']) ? $item['person'] : '',
    '#default_value' => t('Default Person text'),
    '#description' => t('The person'),
    // @see http://www.gawds.org/show.php?contentid=28
    '#maxlength' => 255,
    '#weight' => -2,
    //'#access' => (bool) $item['fid'] && $settings['alt_field'],
    '#access' => TRUE,
  );
  $element['organization'] = array(
    '#type' => 'textfield',
    '#title' => t('Organization'),
    //'#default_value' => isset($item['title']) ? $item['title'] : '',
    '#default_value' => t('Default Organization text'),
    '#description' => t('The organization the person in the image belongs to.'),
    '#maxlength' => 255,
    '#weight' => -1,
    //'#access' => (bool) $item['fid'] && $settings['title_field'],
    '#access' => TRUE,
  );

  return $element;
}

```

However, this doesn't work as expected. Instead of the fields being added to each image, they are added separately below the last uploaded image.

What do I need to do differently to get my fields to show up for each image? Am I on the right track?

Thanks.

# Answer
This question got me scratching my head also for a couple of hours, until I found File Entity Inline module.

Basically this module provides the functionality the OP wanted. You just create the field in the file entity you need to and then when creating the file/image field you have an additional box in the editing window where you can select the fields you want to be displayed next to each file.
> 1 votes

---
Tags: entities, media
---


# Question
Title: Drupal 8 master site for managing customer Drupal 8 sites? Possible?
**Question**: Drupal 8 master site for managing customer Drupal 8 sites? Possible?

**Goal:**

There will be a master drupal 8 site developed for managing basic business modules. These basic business modules should be available to all customer sites. (shared) Also the user roles and users must be shared.

There is no 1 shared codebase. There is also the need for customer site-specific modules that can be installed. So log in with the credentials from the master site at a customer site is also needed.

A picture of the goal:

**Research:**

I have researched several solutions like:

* Multi-Site
* Domain Access

These solutions I have explored share the same code base.

**Expected solution:**

The solution that I want to achieve is no shared code base, each project has its own code base, but also the modules of the master Drupal 8 installation. This would come as basic business modules required for each customer site like autopath and xmlsitemap. So if I install a module on the master site must also be available in the customer site.

The master site code may be shared thus not 100%, but also not completely independent from each other.

Is that possible ? Are they better/other methods for achieving this goal ?

# Answer
> 1 votes
It sounds very much like you'll need two solutions. For sharing the code and parts of the configuration a distribution/install\_profile makes sense (https://www.drupal.org/docs/8/creating-distributions). When you make changes to the distribution you'll need to write hook\_update\_N functions to make these changes on the sites that are using it. So updating a customer site becomes the number problem of deploying coding and running update.php (or doing a cli command).

With respect to sharing roles and users this I might look to do something different. Maybe integrate with a third party identity services that allows you to share the identities across your sites. The roles can be deployed as configuration as part of the install profile. Buried somewhere in this presentation https://events.drupal.org/dublin2016/sessions/no-compromises-%E2%80%93-react-relay-and-graphql-drupal-8 is something about integrating Drupal 8 with an identify provider. And there's also things like https://www.drupal.org/project/openid\_connect

---
Tags: 8
---


title: Template for specific content type

text:
# Question
Title: Template for specific content type
I've read documentation about name suggestions but I don't get it. My goal is to create a specific template used only with a specific content type (Drupal 8).

I've copied `page.html.twig` to edit the code inside a new file, named `page--recette.html.twig` (recette is the name of my content type) but this doesn't work.

`html--node--recette.html.twig` doesn't work neither.

Link : http://ofhjfqaj.preview.infomaniak.website/cms/recette-sans-gluten/tarte-tatin-comme-la-vraie

# Answer
You can provide node level content type templates with the pattern `node--node_type.html.twig`.

So, for an `article` it would be `node--article.html.twig`.

In your case, it would be `node--recette.html.twig`. You can also provide view mode level twigs the same way, with `node--node_type--view_mode.html.twig` files.

Lets say you wanted to customize the teaser display markup:

`node--recette--teaser.html.twig`

If you enable twig debugging, you can see in your HTML source (comments) which template is being used, and what other template pattern names are available to you:

https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Going any further than that, you would need to implement hook\_theme\_suggestions\_alter to get more custom template names based on some sort of logic.
> 4 votes

---
Tags: theming, 8
---


title: Esign field in Webform

text:
# Question
Title: Esign field in Webform
I am attempting to add a signature field with validation to a webform. The validation fields show up, the signature field seems to be there (cursor changes to +) but no field for signature is there.

Esign's documentation says to " Did you set the field to display? Does your CSS allow the field to display? " I'm suspecting that one of these may be my issue. However, I have no idea where to set the field to display. I should note that I added the esign field by adding the field in "form components" and not "form builder" as the field esign did not show up in the "form builder" tab.

Any help would be most welcome!

This is for Drupal 7.

# Answer
> 0 votes
You can set the field to display in this page: admin/config/content/webform

For whatever reason the e-sign field doesnt appear for me under `form builder` it appears when i go to `form components` under `type` there should be an option called `E-sign`.

---
Tags: 7, webforms
---


# Question
Title: `Routing` folder not present inside `Drupal\Core\`
I am trying to port a module from D7 to D8.

Since `hook_help()` uses routes instead of paths in D8, so the line `use Drupal\Core\Routing\RouteMatchInterface;` is added at the beginning of the code as mentioned on this page.

But the thing is that no folder named `routing` exists inside my `Drupal\Core\`.

Questions.

1. Am I supposed to add that folder myself?
2. How will I configure `RouteMatchInterface` file.

# Answer
> 2 votes
No, you aren't supposed to add any directories: Drupal already comes with the core/lib/Drupal/Core/Routing/RouteMatchInterface.php file containing the PHP interface you are trying to use.

There isn't anything you need to config: Just use the object passed as second parameter to `hook_help()`. Drupal core's implementations of `hook_help()` don't usually use that parameter, but `system_help()` does use it.

```
case 'system.theme_settings_theme':
  $theme_list = \Drupal::service('theme_handler')->listInfo();
  $theme = $theme_list[$route_match->getParameter('theme')];
  return '<p>' . t('These options control the display settings for the %name theme. When your site is displayed using this theme, these settings will be used.', array('%name' => $theme->info['name'])) . '</p>';

```

`$route_match` is just an object that allows you to understand exactly for which page the help text is being generated. In the code I shown, it allows to understand exactly for which theme the settings page is shown. system.theme\_settings\_theme (the value for the first parameter) just tells you the page is the theme settings page (served on /admin/appearance/settings/{theme}), but the exact page could be /admin/appearance/settings/bartik, /admin/appearance/settings/stark, or /admin/appearance/settings/seven (just using some of the themes Drupal core comes with as examples).

Using `RouteMatchInterface::getParameter()`, or `RouteMatchInterface::getRawParameter()`, is what you normally do with the second parameter passed to `hook_help()`. The route name is already passed as first parameter, so `RouteMatchInterface::getRouteName()` is not providing anything that you don't already have. Eventually, you could get the `Route` object associated with the page, but I cannot think of any case where that is necessary.

# Answer
> 2 votes
That is the namespace. It's actual location in the file system is `/core/lib/Drupal/Core/Routing`. The autoloader knows where to look via the namespace.

---
Tags: 8, hooks
---


# Question
Title: Load required libraries with content using ajax
So I created a form and and attached a Drupal library to it. From there I created a route that uses that form. Last a added a link that uses ajax to render that form.

For some reason when I look at the context that is rendered from that ajax request the ***/core/misc/vertical-tabs.js?v=8.2.6*** gets loaded onto the page along with the form content, but my attached custom library does not.

If I visit the page without using the ajax request both the ***/core/misc/vertical-tabs.js?v=8.2.6*** and my custom library load fine.

How can I get my custom library to load with ajax?

# Answer
So after playing with this for a while I figured out that Drupal only pulls in the js Assets through ajax, not the css. I guess this make sense on some level. But I figured I can easily pull in the necessary css in using js.
> 0 votes

---
Tags: 8, ajax
---


title: Paginated list of group members

text:
# Question
Title: Paginated list of group members
I want to output the membership of a drupal group, but limiting the number of members shown, instead of outputting all members at once, (that i can do with the code bellow).

```
    $members = $group->getContentEntities('group_membership');

```

# Answer
> 1 votes
If you are able to build an entity query for the group members you can use `$query->pager()`. See block to display nodes using entityQuery with pager

If not, you have to calculate the pager variables yourself. There is only one example for a pager in core that is not using a pager query, the taxonomy terms overview OverviewTerms::buildForm. Or you can use pager\_default\_initialize().

And a third and probably quickest solution is to build a view for the group members.

---
Tags: 8, group
---


title: update media object programatically

text:
# Question
Title: update media object programatically
If I have the id of an existing piece of media content, what can I do to update it (modify it)?

I know how to create a new piece of media , (with Media::create) , but not sure of the code to load and then updated an existing piece of Media.

thanks

# Answer
Media is like any other entity based on ContentEntityBase in Drupal.

```
// top of your file
use Drupal\media_entity\Entity\Media;

// in a function
$media = Media::load($id);
// do stuff with $media
$media->save();

```

edit:

In a method of a class you would not want to use `Media::` but instead use `entityTypeManager` service to load the entity:

`$media = $this->entityTypeManager->getStorage('media')->load($id);` where `entityTypeManager` is injected to your class.
> 10 votes

---
Tags: 8, media
---


# Question
Title: How do I make entity reference lookup faster
I am trying to look up entity reference id's for each node so I can do stuff with them.

```
$all_nodes = db_select('node','e')->fields('e',array('nid','type'));
$all_nodes->addField('e','nid');
$all_nodes->condition('type','author');
$data = $all_nodes->execute();
$the_result = $data->fetchAll(\PDO::FETCH_ASSOC);

foreach ($the_result as $node){
     $node_load =  \Drupal\node\Entity\Node::load($node['nid']);
     foreach ($node_load->field_institution_with_date as $item) {
        $the_entity_id = $item->entity->id();
     }
}

```

Any idea on how to optimize this? it seems that `$item->entity->id();` is the bottleneck and it is taking several seconds to iterate through about 1000 nodes.

# Answer
> 3 votes
Ideally you'd use an Entity Query for this, but in principle:

1. You can batch load the parent nodes

```
...
$nids = $data->fetchCol();

foreach (Node::loadMultiple($nids) as $node) {

```

If memory is a concern with thousands of nodes, just implement some simple php logic around the loop to batch it into, say, 50-100 at a time.
2. If you don't need the child entities, just their IDs, they're available without a DB hit

```
foreach ($node_load->field_institution_with_date as $item) {
    $the_entity_id = $item->target_id;

```

If you do need the entities, you could build an array of all IDs using this method, and batch load those using `Node::loadMultiple` after the outer loop.

---
Tags: 8, entities
---


# Question
Title: Why don't I get any CSS after deploying my Drupal site?
I have deployed my Drupal 8 website, but I don't get any CSS on it.

I deployed it on `mydomain.com/newdrupal`, maybe this needs extra configuring somewhere?

When I check my logs, I have about 20 messages with this warning:

> Warning: file\_put\_contents(temporary://filedGJSiQ): failed to open stream: "Drupal\Core\StreamWrapper\TemporaryStream::stream\_open" call failed in file\_unmanaged\_save\_data() (line 888 of /var/www/stijnAerts/notify/core/includes/file.inc).

I also have this in my console:

> Resource interpreted as Stylesheet but transferred with MIME type text/html: "\*****/notify/?o66rbh".

**Note**: This is a base theme, so no custom theme.

# Answer
Looks like something is wrong with your temp folder, such as:

* When you moved my site to a different server the path to temp was changed and needs to be updated.
* The permission of this folder are not set correctly.

Refer to these links for more inspiration:
> 1 votes

# Answer
In addition to @acrosman:

Make sure that your files and temporary files directories are writable by the server.
> 1 votes

# Answer
Be sure to check the logs at /admin/reports/dblog . In some cases, permission errors will not be available at /admin/reports/status , but they do show up on the log.

In particular if you are getting unstyled pages, the paths to the aggregated CSS and JS files are broken, then check Drupal's internal log after clearing caches.
> 1 votes

# Answer
Check your browser's console for errors, and see if there is something obvious there causing it to fail.

If you're using a custom theme check to make sure you had the theme include the CSS files through its processing, not by hard-coding them into your twig files.

Also make sure you've rebuilt the caches after deploying if you copied over a database.

Check the status page to make sure you have write access to the correct parts of your file system.
> 0 votes

---
Tags: 8, deployment
---


title: Unique product creation

text:
# Question
Title: Unique product creation
I'm trying to figure out the best way to create a product on Commerce 2.x.

What we have is physical products that don't have variation, so basically each product is a stand-alone. What would be the best practice for creating a product?

Currently, I created (in this order):

1. Product Variation type (with fields that represent product properties)
2. Product type (where I select the variation type)

I didn't create any attributes though.

Would this be the right way of doing it?

Also for my second question, I created a Product list page with Views and selected Table view. However, I can't find "add to cart" field nowhere.

# Answer
> 0 votes
Sounds like you've configured the entities properly. Nothing requires you to make use of attributes, so if you don't need them, you don't have to make them. : )

Re: the field formatter for Views to display an Add to Cart form, it hasn't been developed yet.

---
Tags: commerce
---


# Question
Title: How to put google map field in my form of my custom module?
i like to build a form field based on google map, where user can put in their address, city and country, then the map will automatically search for it. and then you can put a pin to define the exact location, which the expected output is latitude & longitude which will be saved during form submit.

how to approach this? is there any module in Drupal 8 that i can use during form generation?

maybe something like:

```
 $form['map'] = array(
      '#type' => 'gmap',
      '#otherProperty' => propertyValues,
 );

```

Thank you, AnD

# Answer
> -1 votes
use this it works for me https://www.drupal.org/project/google\_map\_field . . . . . .

---
Tags: forms, 8, google-maps
---


title: I can't uninstall the Webform module

text:
# Question
Title: I can't uninstall the Webform module
I have the Webform module version 8.x-5.0-beta9, and when I try to uninstall the module Drush asks me to uninstall the webform\_demo\_application\_evaluation module, first. When I try
`drush pm-uninstall webform_demo_application_evaluation`, it throws an error.

> PHP Fatal error: Call to a member function `getColumns()` on boolean in /var/www-drupal/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php on line 227
> Drush command terminated abnormally due to an unrecoverable error.
> Error: Call to a member function getColumns() on boolean in /var/www-drupal/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php, line 227

How do I resolve this issue? Do I need to install the development snapshot?

# Answer
You should be able to manually delete the demo forms, blocks, and nodes and then uninstall the demo module.

Please create a ticket in the Webform issue queue.
> 1 votes

---
Tags: webforms
---


# Question
Title: use conditional fields to change a label on a field
Is it possible to change the label on a field using the conditional fields module. What I want is to call a field "Effective Date" in one case and "Published Date" in another but have it be the same field.

is that possible with the conditional fields module or any other module?

# Answer
> 1 votes
I answered this similar D7 question How to change a fields label name based on another fields value?

```
(function ($) {

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

   var grabselectedtext = $('#edit-field-test-und option:checked').text();
   // this grabs the text of the field you want to depend on.

     $('label').each(function(){
      if ($(this).attr('for') == 'edit-body-und-0-value') {

         if (grabselectedtext != '- None -') {
           $(this).text(grabselectedtext);
         } else {
             $(this).text('Field Two');
           }
         }

     });

   setTimeout(Forever, 1);

   })();

})(jQuery);

```

You want to attach this JS code to a library. Then attach the library via a hook\_form\_alter and check for form ID and content type.

---
Tags: 8, entities
---


# Question
Title: How to fetch records from entity base on only Day and month?
How to fetch records from entity base on only Day and month

Like In DOB need to return those user which has current day and month.

E.g:

```
$query = \Drupal::entityQuery('user');
$query->condition('status', 1);
$query->condition('field_dob', date('m-d'));
$entity_ids = $query->execute();

```

In anyone have idea how to do this?

# Answer
Here we are doing a LIKE query as the question stated that it wants to fetch record on basis of current month and day only not a year .

```
 $query= \Drupal::entityQuery('user')
     ->condition('field_dob','%'.date('m-d').'%', 'LIKE')
     ->execute()

```
> 1 votes

---
Tags: 8, users, entities
---


# Question
Title: How do you override Commerce checkout pane output?
I downloaded the commerce bitcoin module and I'd like to override the current output of the pane. There is no theme\_ function to override. How can this be done?

The code is below:

```
 1 <?php
  2
  3
  4 /**
  5  * Implements base_checkout_form()
  6  * Display the bitcoin address at the checkout
  7  *
  8  */
  9 function commerce_bitcoin_pane_checkout_form($form, $form_state, $checkout_pane, $order) {
 10
 11
 12
 13
 14   $output .= t('<strong>Total amount</strong> %total BTC', array('%total' => $bittotal)) . '<br/>';                                                                                15   $output .= t('<a href="https://blockchain.info/address/'. $bitaddress .'" target="_blank">Check Blockchain.info Payment Status</a>') . '<br/>';
 16   $checkout_form['commerce_bitcoin_pane_field_display'] = array(
 17     '#markup' => $output
 18   );
 19
 20   return $checkout_form;
 21 }

```

# Answer
It looks like using

```
 hook_commerce_checkout_pane_info_alter(&$checkout_panes)

```

or

```
 hook_commerce_checkout_page_info_alter(&$checkout_pages)

```

would be the best options. There are also hooks that allow you to create your own checkout panes/pages from scratch if necessary

```
(hook_commerce_checkout_pane_info() and hook_commerce_checkout_page_info())

```

I would suggest reading more about them here and checking out the specific examples (about page/pane info hook implementations) that you can find in the Drupal Commerce submodule (mostly Checkout) files
> 1 votes

# Answer
Checkout panes are fieldsets within the context of per-page checkout router form. You can use a `hook_form_alter()` to modify the contents of the entire page that a form is shown on. For instance, if you want to modify objects that appear on the `checkout` page (which is the first one in Commerce Core), you'd use this hook:

```
MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  // Make the customer profile billing pane's locality field a bit smaller.
  $form['customer_profile_billing']['commerce_customer_address']['und'][0]['locality_block']['locality']['#size'] = 20;
}

```

Where `commerce_checkout_form_checkout` is `commerce_checkout_form_` concatenated with the current checkout router step. See `commerce_checkout_router()`. Each of the panes within the page exists within this form. As Ryan also points out in the comments, the main form traps errors and other items to present them inline with the checkout pane, so a payment error won't show up at the top of the page, but it will show up above the payment pane for instance.

If you're wanting more info on how to theme checkout, I'd recommend you go review the code for Commerce Responsive UI and mimic what it does.

This *includes* the complete pane which is still a form. If you want to override the form completely, you can just change the callback that is called when the completion pane is being built:

```
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['checkout_completion_message']['callbacks']['checkout_form'] = 'MYMODULE_completion';
}

```

Then, you put your own output into the new callback. Just copy what `commerce_checkout_completion_message_pane_checkout_form()` does and put your own content in.
> 6 votes

# Answer
Here's an example to modify the output of the commerce\_payment review pane:

```
/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_pane) {
  $checkout_pane['commerce_payment']['callbacks']['review'] = 'MYMODULE_commerce_payment_pane_review';
}

/**
 * Replacement callback function for the commerce_payment review pane.
 */
function MYMODULE_commerce_payment_pane_review($form, $form_state, $checkout_pane, $order) {
  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.checkout_pane');
  $html = commerce_payment_pane_review($form, $form_state, $checkout_pane, $order);
  // Add our custom HTML, could use theme() here to be nice.
  return $html . "<p>More data here...</p>";
}

```
> 0 votes

---
Tags: 7, theming, commerce
---


title: Grouping Node Comment in Views

text:
# Question
Title: Grouping Node Comment in Views
I am trying to set up the following in Views:

**Review 1**
-Example Field
-All Comments of the Review

**Review 2**
-Example Field
-All Comments of the Review

I'm pulling in the comments from a relationship. However, rather than grouping all the comments under the review, it duplicates the Review:

**Review 1**
-Example Field
-Comment 1

**Review 1**
-Example Field
-Comment 2

And so forth. How can I group all the comments to not duplicate the node, and just appear in order and grouped for the review node?

# Answer
I know an old post anyway. There two solutions to this, here is one, but for this you need to define the type of the view as comment view right from the start, However another solution is that (Assuming Review 1, Review 2 are nodes being pulled and a relationship is set on the `comment and node`), right below the `Title` block you have the `FORMAT` configuration block, set it to `Unformatted list` and to display the `fields` (Notice: I have not tested on other formats such as table etc), click on `Settings` after the `|`pipe symbol and you can see `Grouping field Nr.1` with a drop down, choose `nid` as your grouping method. In other cases there might be `Grouping field Nr.2/3..` and so on. This should be able to group all your comments together for a node.
> 0 votes

---
Tags: views, comments
---


# Question
Title: How do I alter the title of a menu link?
In my website, users can collect some 'points' over time. I have a top-bar menu with some links (e.g. "home", "profile", "logout"). I want to alter the menu item "profile" and add the number points owned by the current connected user.

I tried several hook, and I almost succeeded in getting what I wanted with `hook_link_alter()`.

```
function mycustommodule_link_alter(&$variables) {
  if ($variables['text'] == "profile") {
    // Do some work.
    $variables['text'] = $variables['text'] . " (you have $nb_points points)";
  }
}

```

I cleared the cache (with `drush cr`), and the menu item shows the value I want. But, if the value changes for some reason, it shows the old value. I must clear the cache all the times to update its value.

How can I avoid cleaning the cache to update the menu title all the times the points gained from the user change?

# Answer
I suggest implementing a custom menu link plugin. The code below assumes your module name is *example*.

```
<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Database\Connection;
use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $dbConnection;

  /**
   * Constructs a new points menu link.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Menu\StaticMenuLinkOverridesInterface $static_override
   *   The static override storage.
   * @param \Drupal\Core\Database\Connection $db_connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, StaticMenuLinkOverridesInterface $static_override, Connection $db_connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $static_override);
    $this->dbConnection = $db_connection;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('menu_link.static.overrides'),
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = $this->dbConnection->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

```

If you don't want to inject the database service the class would become much simpler.

```
<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

```

Next you need to put the link definition into *example.links.menu.yml* file.

```
example.user_points:
  route_name: <front>
  menu_name: main
  class: Drupal\example\Plugin\Menu\ExampleMenuLink
  weight: 30

```

**The caching problem**

Whenever the number of points is changed the menu link cache should be invalidated as follows.

```
 \Drupal::service('cache_tags.invalidator')->invalidateTags(['example.points_count']);

```

You need to find out the right place for this. If the points managed by contributed module check the module API and pick up an appropriate hook (*hook\_points\_insert()*, *hook\_points\_delete()* and so on).

Since the number of points is calculated for each user account individually you may consider using per account cache tags (something like `['example.points_count.' . $uid]`). Therefore the cache will be preserved for users with unchanged points.

---

To generate code for the Menu link plugin I used Drupal Code Generator.
> 10 votes

# Answer
I faced the same problem. The menu items are cached, so it always shows the old value until you clear the cache. Alternative way is using `hook_page_attachments()`, attach points to drupalSettings.YOUR\_MODULE\_OR\_THEME.YOUR\_VARIABLE, and access them in JavaScript, and render in the browser.

Normal way is disabling cache for pages whenever the "profile" menu displays at site performance.
> 2 votes

# Answer
Disable the cache for that menu in `hook_preprocess_menu()` by setting `$variables['#cache']['max-age']` to 0.
> 0 votes

---
Tags: navigation
---


# Question
Title: How do I programmatically change contextual filters?
Basing on a blog post, I wrote the following code.

```
/**
 * Implements hook_views_pre_view().
 */
function mm_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() != 'product_listing' && $display_id != 'page') {
    return;
  }

  $tid = reset($args);

  if (! $tid) {
    return;
  }

  $term = Term::load($tid);
  $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
    ->loadTree($term->getVocabularyId(), $tid);

  foreach($terms as $child_term) {
    $args[] = $child_term->tid;
  }

}

```

I cleared the cache, but the code I wrote doesn't have any effect. The SQL query is not altered; only single taxonomy ID is returned. I have selected *Allow multiple values* for the filter.

What is wrong with the code? How can I fix it?

# Answer
> 4 votes
Args should be concatenated with `,` or `+`.

This work:

```
  $term = Term::load($tid);
  $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')
    ->loadTree($term->getVocabularyId(), $tid);

  foreach($terms as $child_term) {
    $args[0]  .= ',' . $child_term->tid;
  }

```

---
Tags: views, 8
---


# Question
Title: Installing latest drupal console RC via composer
I'm trying to install drupal console latest release candidate globally via composer. I run

```
$ composer global require drupal/console:~1.0.0@rc

```

But I get the following error:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - drupal/console 1.0.0-rc9 requires drupal/console-core ~1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc8 requires drupal/console-core ^1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc7 requires drupal/console-core ^1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc6 requires drupal/console-core ^1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc5 requires drupal/console-core ^1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc4 requires drupal/console-core ^1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc3 requires drupal/console-core ^1.0@RC -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc2 requires drupal/console-core ^1.0@RC -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc16 requires drupal/console-core 1.0.0-rc16 -> satisfiable by drupal/console-core[1.0.0-rc16] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc15 requires drupal/console-core 1.0.0-rc15 -> satisfiable by drupal/console-core[1.0.0-rc15] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc14 requires drupal/console-core 1.0.0-rc14 -> satisfiable by drupal/console-core[1.0.0-rc14] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc13 requires drupal/console-core 1.0.0-rc13 -> satisfiable by drupal/console-core[1.0.0-rc13] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc12 requires drupal/console-core 1.0.0-rc12 -> satisfiable by drupal/console-core[1.0.0-rc12] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc11 requires drupal/console-core ~1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc10 requires drupal/console-core ~1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - drupal/console 1.0.0-rc1 requires drupal/console-core ~1.0 -> satisfiable by drupal/console-core[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc9, v1.0.0-rc8] but these conflict with your requirements or minimum-stability.
    - Removal request for drupal/console == 1.0.0.0-beta5
    - Installation request for drupal/console ~1.0.0@rc -> satisfiable by drupal/console[1.0.0-rc1, 1.0.0-rc10, 1.0.0-rc11, 1.0.0-rc12, 1.0.0-rc13, 1.0.0-rc14, 1.0.0-rc15, 1.0.0-rc16, 1.0.0-rc2, 1.0.0-rc3, 1.0.0-rc4, 1.0.0-rc5, 1.0.0-rc6, 1.0.0-rc7, 1.0.0-rc8, 1.0.0-rc9, 1.0.0-beta5].

Installation failed, reverting ./composer.json to its original content.

```

When I run:

```
$ composer global require drupal/console:~1.0.0@dev

```

It installs beta5.

P.S. I don't want to edit composer.json, it will be an automated script

# Answer
> 3 votes
So the problem was that Drupal console's dependent packages (`drupal/console-core`, `drupal/console-en`) didn't use the `minimum-stability` option that I specified via `@`, so I just had to set it globally and run again:

```
$ composer global config minimum-stability rc
$ composer global require drupal/console:1.*

```

---
Tags: composer, console
---


# Question
Title: How to show 404 page for nodes without translation?
I'm using entity translation and I need to show 404 page for a node if it hasn't got a translation available for current language.

For example, the site runs EN, DE, FR, ES languages. Node 100 is translated to EN and DE. If i set current language to FR and visit the node 100, I'll see EN content due to the language fallback. But I would like to show 404 page.

How can I achieve this?

# Answer
At first I was tempted to alter menu items responsible for node auto-loader function like this:

```
/**
 * Implements hook_menu_alter to hijack node auto-loader function.
 */
function et404_menu_alter(&$items) {

  // Remove original node view item...
  unset($items['node/%node']);

  // ... add our own node view item with custom auto-loader
  $items['node/%et404_hijacked_node'] = array(
    // Array items are copy-paste from node.module
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * Overrides node_load to show 404 page if translation is not available.
 */
function et404_hijacked_node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
  global $user;
  global $language;

  $node = node_load($nid, $vid, $reset);

  // Only anonymous users are refused access
  if (!$user->uid && !isset($node->translations->data[$language->language])) {
    $node = false;
  }

  return $node;
}

```

Unfortunately this solution won't work correctly, because of menu\_get\_object() function that is used across drupal. That function assumes that every entity has it's auto-loader function named like `ENTITY_TYPE_load()`. The `_load` suffix is hardcoded into the function whereas it should be red from the entity info array provided by the hook\_entity\_info() (explicitly the `load hook` parameter).

# I decided to use different approach that involves `hook_node_access()`.

Actually instead of showing 404 with `drupal_goto()` I decided to incorporate drupal core and show 403. It can be turned into 404 anyway with a help of m4032404 module.

Please note that the following code is part of a module that also provides language fallback features similar to those from language fallback module \- hence the reference to `$language->fallback` property that doesn't exists in vanilla D7. I am the author of language fallback patch for entity translation for D7 and D8 but for this particular project I needed something very sophisticated that I couldn't achieve with the language fallback module.

```
/**
 * Implements hook_node_access()
 */
function et404_node_access($node, $op, $account = null) {

  // We restrict access only to anonymous users so authenticated users can still manage content
  if ($account->uid) {
    return;
  }

  // Basic sanity check
  if (!is_object($node)) {
    return NODE_ACCESS_DENY;
  }

  global $language;

  // Check if translation for current language exists
  if (!isset($node->translations->data[$language->language])) {
    // Check if translation for fallback language exists
    if (LANGUAGE_NONE != $language->fallback && isset($node->translations->data[$language->fallback])) {
      return;
    }

    return NODE_ACCESS_DENY;
  }
}

/**
 * Implements hook_translated_menu_link_alter()
 *
 * This function checks if specific menu item points to the node entity
 * and if it is, checks if node has translation for current UI language.
 * Nodes without translation are hidden.
 *
 * See StackExchange answer for more info:
 * http://drupal.stackexchange.com/a/32024/5982
 */
function et404_translated_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if ('menu' != $item['module'] || !isset($item['menu_name']) || 'main-menu' != $item['menu_name']) {
    return;
  }

  // Process only nodes
  if (!isset($map[1]) || !isset($map[0]) || 'node' != $map[0]) {
    return;
  }

  if(!is_object($map[1])) {
    // Instead of loading node manually, use core function for that.
    if (!_menu_load_objects($item, $map)) {
      return;
    }
  }

  // After _menu_load_objects() the $map[1] contains node object
  $entity = &$map[1];

  if (!et404_translation_check_entity($entity)) {
    // There is no translation for this entity in current UI language.
    // Hide the item and quit.
    $item['hidden'] = true;

    return;
  }
}

/**
 * Implements hook_menu_link_alter()
 *
 * When custom menu item is saved, we add 'alter' option to be able to
 * customize this item with hook_translated_menu_link_alter() implementation.
 * See et404_translated_menu_link_alter() for details.
 *
 * @param array $item
 * @param array $map
 */
function et404_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if (isset($item['module']) && 'menu' == $item['module'] && isset($item['menu_name']) && 'main-menu' == $item['menu_name']) {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Check if there is a translation for entity in current UI language only
 * @param object $entity
 * @return boolean|string
 *   FALSE if translation is NOT available; otherwise true.
 *   Note that FALSE is returned also for entities without "translations" property.
 */
function et404_translation_check_entity($entity) {

  // Invalid data?
  if (empty($entity)) {
    return false;
  }

  global $language;

  // Check if current UI language is the same as entity language
  // This is a fail-safe in case "translations" property is missing
  // Note that taxonomy terms doesn't have language property
  if (!empty($entity->language) && $entity->language == $language->language) {
    return true;
  }

  // Check if "translations" property exists.
  // Without it further checks doesn't make sense
  if (empty($entity->translations)) {
    return false;
  }

  // Check if there is a current UI language translation available.
  if (!empty($entity->translations->data[$language->language])) {
    return true;
  }

  // Check if there is a fallback language translation available.
  if (LANGUAGE_NONE != $language->fallback && !empty($entity->translations->data[$language->fallback])) {
    return true;
  }

  // No translation available
  return false;
}

```

And as a bonus, a fix for language switching links:

```
/**
 * Implements hook_language_switch_links_alter
 *
 * Function alters language switching links for nodes
 * if there is no translation for currently viewed node
 */
function et404_language_switch_links_alter(array &$links, $type, $path) {

  $translations = array_keys($links);
  $translations = array_flip($translations);

  if (arg(0, $path) == 'node' && arg(1, $path) && !arg(2, $path)) {
    // !arg(2, $path) --> This will make sure we're not altering links like /node/1/edit/LANG

    // Most probably dealing with nodes
    $node = node_load(arg(1, $path));

    if ($node) {
      $translations = array_keys($node->translations->data);
      $translations = array_flip($translations);
    }
  }

  $languages = language_list();

  foreach($links as $lang => &$link) {
    // Check if translation for the language exists
    if (!isset($translations[$lang])) {
      // If not, check if the fallback translation is also missing.
      if (!isset($languages[$lang]->fallback) | LANGUAGE_NONE != $languages[$lang]->fallback && isset($translations[$languages[$lang]->fallback])) {
        continue;
      }
      $link['href'] = '<front>';
    }
  }
}

```
> 1 votes

# Answer
The first step in accomplishing a 404 page for missing translations for an entity/language combination is to disable the 'Enable language fallback' option found on the Entity Translation settings page (/admin/config/regional/entity\_translation). This will prevent Drupal from displaying the source content, but it doesn't get us to the desired 404 and instead displays a '%language translation unavailable for %label.' message.

If we dig a little, we find that this message is provided by the 'entity\_translation\_unavailable' theme implementation. This means that we can override the theme implementation in our theme and call drupal\_not\_found() to return our desired 404. If we want to override this in a module, we can implement hook\_theme\_registry\_alter() and specify a custom function for this theme implementation and call drupal\_not\_found() from that function.
> 1 votes

# Answer
I'm not aware of any contributed module that can be used for this. A possible solution could be to use a custom module that uses **hook\_node\_view**, as in this example:

```
function yourmodule_node_view($node, $view_mode, $langcode){
   global $language;
   if (!empty($node->language) && $node->language != $language->language) {
      drupal_not_found();
   }
}

```
> 0 votes

# Answer
In case you're using Entity Translation this is the simplest implementation you can do.

```
/**
 * Implements HOOH_node_view().
 *
 * @param $node
 * @param $view_mode
 * @param $langcode
 */
function HOOK_node_view($node, $view_mode, $langcode) {
  global $language, $user;

  // In case the translation is missing, trigger 404 for anonymous.
  if (!$user->uid && !isset($node->translations->data[$language->language])) {
    drupal_not_found();
  }
}

```
> 0 votes

---
Tags: 7, i18n-l10n
---


title: Page editing gives an extra text widget

text:
# Question
Title: Page editing gives an extra text widget
When I try to edit a page that already added am getting an extra text area movable widget as shown in below screenshot.

Is it a bug or an issue with the settings in for the content type page?

# Answer
You seem to have your field's cardinality set to greater than 1. Change it to 1 and the problem should be fixed.

In case you already have data in the field but you are sure to only have one value stored per entity change the column "cardinality" in the "field\_config" table manually to 1.
> 0 votes

---
Tags: 8, nodes
---


# Question
Title: How to show Numeric keyboard while entering in textfield?
I am creating a custom form field with text-field type. That will accept only numbers, so I want to display only numeric keyboard instead of alphanumeric keyboard. How can I achieve that?

I tried using `Elements` module but I don't want to use extra features of this module.So I am searching for code snippet. Is there any way to do it in a custom way?

# Answer
First, create a module named html5\_form\_element. Then you need to set up the following

Implement hook\_element\_info() to tell Drupal about your element type:

```
/**
 * Implementation of hook_element_info()
 */
function html5_form_element_element_info()
{
  $types['number_input'] = array
  (
    '#input' => TRUE,
    '#theme' => 'number_input',
    '#theme_wrappers' => array('form_element'),
  );

  return $types;
}

```

Next implement hook\_theme() to define the theme for your input type:

```
/**
 * Implementation of hook_theme()
 */
function html5_form_elements_theme()
{
  $theme = array
  (
    'number_input' => array
    (
      'render element' => 'element',
    ),
  );

  return $theme;
}

```

And finally, create the theme function that will theme your element:

```
function theme_number_input($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'number';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-number'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input']))
  {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

```

Clear your caches, and you can now use `'#type' => 'number_input'` in the Form API.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: Taxonomy Term Reference Fields Don't Get Created on Nodes During Migration
I have followed the steps shown here to create/run the migration. Everything seems to migrate correctly except the Taxonomy Term Reference fields never get added to the nodes. The taxonomies and vocabularies do get created.

I'm thinking that those fields should have been created in d6\_field\_instance so here is my migrate\_plus.migration.upgrade\_d6\_field\_instance.yml.

```
uuid: 6e1fd6ac-1ec4-4631-93d1-753068fdc667
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_field_instance
migration_tags:
  - 'Drupal 6'
migration_group: migrate_drupal_6
label: 'Field instance configuration'
source:
  plugin: d6_field_instance
  constants:
    entity_type: node
process:
  field_type_exists:
    -
      plugin: migration
      migration: upgrade_d6_field
      source:
        - field_name
    -
      plugin: extract
      index:
        - 1
    -
      plugin: skip_on_empty
      method: row
  entity_type: constants/entity_type
  field_name: field_name
  bundle:
    -
      plugin: migration
      migration: upgrade_d6_node_type
      source: type_name
    -
      plugin: skip_on_empty
      method: row
  label: label
  description: description
  required: required
  status: active
  settings:
    plugin: d6_field_field_settings
    source:
      - widget_type
      - widget_settings
      - global_settings
  default_value_callback: ''
  default_value:
    plugin: d6_field_instance_defaults
    source:
      - widget_type
      - widget_settings
destination:
  plugin: 'entity:field_config'
migration_dependencies:
  required:
    - upgrade_d6_node_type
    - upgrade_d6_field
  optional:
    - upgrade_d6_field
    - upgrade_d6_node_type

```

Any idea what it can point me where in code to look.

# Answer
The problem wasn't in migrate\_plus.migration.upgrade\_d6\_field\_instance.yml but instead the problems were in migrate\_plus.migration.upgrade\_d6\_field.ym and migrate\_plus.migration.upgrade\_d6\_field\_instance\_widget\_settings.yml. Also in the term yml files I had to update the field name to include `field_` in the file name.

I documented how I was debugging and what I was changing here.
> 0 votes

---
Tags: 8, migrations
---


# Question
Title: Redirect to entity ID after entity create form submit with AJAX
I have an AJAX entity create form and I want to redirect to that entity ID after I submit the form and create the entity, I know I can't use goto() because it's AJAX. I have the hook form alter for that entity already for some other customization of the form.

# Answer
> 1 votes
You should not use `drupal_goto()` for form redirects. You should set the redirect in the form state.

```
function mymodule_myform_submit($form, &$form_state) {
  // other code
  $form_state['redirect'] = 'path';
}

```

Ctools provides a way to do a redirect in an AJAX callback, a function called ctools\_ajax\_command\_redirect.

I found an example of someone using this function in a form callback that is AJAX:

```
function mymodule_custom_ajax_form_submit($form, &$form_state) {
  //Close lightbox and redirect to the current page
  $path = $_SESSION['current_path'];
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);
  exit;
}

```

So, in your case, you would need to know the entity id in the submit handler, and you can get the uri with entity\_uri, which you can pass as the `$path` and that should work. Just load the entity object, and pass it to entity\_uri. It should return 'myentity/(id)' ex 'node/123', which you can redirect to.

---
Tags: 7, ajax
---


# Question
Title: How do I edit an external database from the UI?
I am working with Drupal 7.54.

Using the great module Views Database Connector, I managed to display data from an external database, previously configured in settings.php as mentioned by Drupal.org.

Now, using Views 3.15, I can create pages, blocks, etc to display data from this extra database and it's nice.

My client will be able to edit this external database from Access, Sequel Pro, Navicat, etc and the modifications will be automatically displayed on the website.

But now, I have a problem with *the other way* : **modify data from Drupal UI and insert these new values in the external database**.

I have tried to find modules or tutorials and here are the options I may have :

* Using Feeds SQL: with this module, I can link the external database through import process. I should first create a content type to map fields with columns and then import data from the external database in Drupal ecosystem. Later, when I modify contents, I may be able to create an *inverse process* to export Drupal fields values into the external database columns (not quite sure it is possible). BUT if I modify something through Drupal UI and set an automatic import through cron, it will overwrite the external database, possibly modified before through another interface (Sequel Pro, etc) so I need a non-automatically way to edit the external database through Drupal UI. Maybe add an "Update database" button on the Drupal edit form? Hope I am clear here...
* Creating a custom module : I am **not** a senior Drupal developer, more a site builder. I always try to use modules and configuration between them to reach my purpose which seems natural if you use a CMS (or CMF), imho. Anyway, if someone has an obvious solution with a handmade module, any advice is welcome, of course.
* Other modules : Data, Schema, Forena... they seem to be very useful and powerful but they also seem to work only for display, am I right? You may adopt tables, create reports or custom SQL queries but in fine, you may not be able to edit external database with these tools?

Well, I am still lost in thoughts and I hope that this forum (which helps me each time) could give me a way to achieve this goal.

A last option would be to work without Drupal but I am not ready for that!

Thanks in advance.

Related questions on this website :

Insert into table from Drupal 7

Inserting data to external DataBase

Manipulate Database from Drupal

Drupal as an interface for users to Add/Edit/Search a database

Related posts elsewhere :

Module to sync with external database

Save data to external (non drupal) database

Working with an external database

**EDIT 1** : After different tests, maybe I will not need Views Database Connector at all since **Feeds SQL** does a tremendous job with SQL data from an external database. With an automatic cron job and a nice mapping, you can convert your SQL data into Drupal nodes and thus using Views, Panels, Drupal Commerce, Taxonomy, etc. If I update the external database (with any software you like, from PHPMyadmin to Access), next time the cron runs, Feeds SQL will update the related nodes on the website and no one needs to edit the fields values through Drupal interface. Awesome. This part is OK.

But I still need the reverse way : **synchronize** the Drupal fields values with the external database lines... A sort of export... Views Data Export? but the resulting file (csv, xml...) will always need manual process to overwrite the external database... To be continued...

**EDIT 2** : I have tried to work with Data and Schema. First, I exported a table from the external database and imported it in the Drupal database among all the usual tables. Then I adopted the orphan table and create an entity with this table (thanks to Schema module). Thus I managed to create a View listing the table contents. Finally, I installed Views Bulk Operations and added an action button "Modify entity values". Now, I have a view displaying values from an extra-Drupal table with a possibility to edit the values. But I must admit that it is not user-friendly compared to a Drupal usual content form (custom with panels or display suite). So, any new idea Drupal friends?

**EDIT 3** : I guess a custom module should be the answer. So I started something based on this question. It works if I need to create a new line in the external database. Now I would need some advice to write this module so I can **edit** an existing row? To clarify that part, I posted another question: How to send values to an external database with a custom module?. Thanks in advance.

# Answer
> 1 votes
Finally, I manage to edit an external database from Drupal interface following these steps (just a simple example) :

* Modify the settings.php file to declare my `external_database` with one table `datatest`(primary key : id)
* Create a Drupal content type External Data with fields (`field_integer, field_varchar, field_long_text, field_date`) related to the `datatest` columns (`column_int, column_varchar, column_longtext, column_date`)
* Create a Feeds importer using Feeds and Feeds SQL to map Drupal fields with `datatest` columns
* Import `datatest` values in Drupal nodes with my Feeds importer
* Using Feeds Job Scheduler, now any modification in `datatest` table will be transfered to my Drupal nodes, each cron.
* Writing a rule (Rules module) to update `datatest` values each time a Drupal node is edited

+ Event : After updating existing content of type External Data
    + Condition : none
    + Actions :
        - Execute custom PHP code

`db_set_active('external_database');
db_query("UPDATE datatest
SET column_int='[node:field-integer]',
column_varchar='[node:field-varchar]',
column_longtext='[node:field-long-text]',
column_date='[node:field-date]'
WHERE id=[node:title]");
db_set_active();`

+ Show a message on the site (to confirm the rule has fired)
* Using this last item, now each time I updated a node through External Data Drupal form, values are also modified in `datatest`.

---
Tags: views, database, feeds
---