# Question
Title: How to convert User points to vote ballots?
I want to achieve the following functionality and I'm wondering if this could be possible:

For each purchase, one can gain userpoints (I can handle this using Rules).

Those userpoints will then be used to vote nominees. So if I have 1000 userpoints, i can use 300 for Candidate A, 500 for Candidate B, and and 200 for Candidate C. ( 1 userpoint = 1 ballot)

Can some give a hint/suggestion on how I could implement this. Workflow would be:

1. I select a candidate.
2. "Input" a vote amount.
3. Vote gets recorded.
4. Vote amount will be deducted from my userpoints.

# Answer
Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

```
{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

If you simply adapt the amount of points (-2 and -1) to something like (eg) +300 and -300, you've a prototype to transfer (300) user points from one user to another (eg Candidate A). Just repeat for Candidate B and C.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer some predefined (hardcoded) amount of user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved", so that the user could enter "300" for Candidate A (instead of some hardcoded, fixed amount).

However, the above Rules example may need further refinements, e.g. if you want to ensure that after moving points from User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

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

# Answer
First of all i think you need to elaborate the question a bit more. And as far as i understand your question, you can do this using flag, you can provide the user some flag to vote and set a rule where the nominee will be donate the vote from his points when the flag is flagged. Hope it helps
> 0 votes

# Answer
So according to your desired workflow. You can follow these steps:

1. Create a drupal form having two fields 'select candidate' and 'input vote'.
2. Now check if input vote \< userpoint.
3. And if yes on form submit record the vote and grant nominee points and deduct from the logged in user. You can use form\_rules to trigger a rule on form submit or validate or alternatively you can use userpoints api to grant or deduct points.
4. And if no , show the user a message that user don't have enough points.
> 0 votes

---
Tags: userpoints
---


# Question
Title: Does Yoast SEO put "Focus Keyword" as H1 Tag?
At the outset thanks you all for not assuming that I do coding. My question is related to my very simple and a first-timer's website http://enconengineers.in/ written in Drupal-8 with Zircon theme. While checking my Content with Yoast SEO module, it asks for "Focus Keyword" for the H1-Tag. It also red-flags about missing H-2 Tag. My query is does Yoast SEO automatically put the focus keyword as a H1-Tag in the content?

If not, shall appreciate if anyone can share the Steps/ways/setting-processes using which I can globally (for my website) define H1-Tag (which will always be a keyword (different for each content) in each content's Title Tag) and H2-Tag (which will be in 1st/2nd paragraph of each content) for all the content pages?

# Answer
Without having to heavily modify the theme itself the most direct approach to solving your problem to have a better Yoast score would be to install and use the Meta Tag module in Drupal 8.

It sets many typical metatags in the head portion of every HTML page Drupal renders for visitors. If you need a custom meta tag for h1 focus word or h2 related items, I'm sure the metatag API supports creating your own metatags that can make use of Tokens.

Either use pre-existing Drupal 8 tokens provided by the Token module, or use the API provided by the Token to programmatically create tokens specific to your site that implement the functionality you need for a focus word or an H2 related token. This of course requires some PHP and web development experience, or hiring a web developer.
> 0 votes

---
Tags: meta-tags
---


title: Drupal 8 Query Questions

text:
# Question
Title: Drupal 8 Query Questions
Is there a reason to be using `\Drupal::database()` vs `\Drupal\core\Database\Database::getConnection()`?

How do I know when I can chain my query methods and when I can not? For example

```
$db = \Drupal\core\Database\Database::getConnection();

$query = $db->select('node', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'blog');

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

```

vs

```
$db = \Drupal\core\Database\Database::getConnection();

$query = $db->select('node', 'n');
$query->fields('n', ['nid']);
$query->fields('nb', ['body_value']);
$query->join('node__body', 'nb', 'n.nid = nb.entity_id');
$query->condition('n.type', 'blog');

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

```

# Answer
> Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?

Yes. The former returns a correctly instantiated service object, with all required dependencies automatically injected. You would need to load up all the relevant services yourself and inject them manually if using the latter method.

> How do I know when I can chain my query methods and when I can not?

There are 2 common approaches:

1. Read the docs for the methods you're using.
2. Use an IDE with good code completion.
> 3 votes

---
Tags: 8, database
---


# Question
Title: Can I add external js and css via module info files?
I have read that I can add js and css file via .info files. Can I add external css and js files there as well? Eg http://somewhere.com/in\_a\_galaxy

# Answer
> 3 votes
External JS/CSS files can't be specified in the info file at all. You need to add them via hooks, typically I use `THEMENAME_preprocess_page()` for things that need to be included on all pages, or you can use `drupal_add_js()` in your `.module` file.

And you can refer to this page. Here you can see how many ways you can add script/css files.

# Answer
> 2 votes
To add external javascript.

```
drupal_add_js('http://example.com/example.js', 'external');

```

To add external css.

```
drupal_add_css('https://fonts.googleapis.com/css?family=Droid+Serif:regular', 'external');

```

---
Tags: 7, javascript, theming, .info
---


# Question
Title: Practical solution to get an overview of input formats in use
I'd like to clean up unused text formats on some D7 sites. So I need to know which formats are not used. I tried using VBO for this, but there is no field `Content: Text format` I can add there.

What's a good way to get an overview of formats in use? I'd be ok with using `drush` for this and I can settle with just knowing the nodes and blocks that use a specific format (ignoring other places like views headers).

I'm not looking for a generic answer like "it's stored in these and these database tables". I'm looking for a practical solution that I can use on many Drupal sites.

# Answer
> 2 votes
Use this module: https://www.drupal.org/project/text\_formats\_report

The module pages says don't use this on production.

# Answer
> 3 votes
This is stored on a per-field basis.

Take a look at your database, any `field_data_*` table. In those tables, the `field_X_format` column will contain the input format.

# Answer
> 1 votes
It's hard to clean up old text formats, they are in multiple tables, including the `field_revision_*` tables.

A better strategy is often just to not use them - only the super admins will see them if you remove permissions from everyone. The only downside of this is that any content using those input filters will become uneditable by everyone else.

It does sound like a problem that a `drush` command would be useful for.

---
Tags: 7, input-formats, views
---


# Question
Title: Webform and Jquery Validate Plug-In - Submit button is being disabled
Having an odd issue using Webform and the Jquery Validate plugin.

I have a custom page where I added the following lines to the template under the tag:

```
    <!--   Core JS Files   -->
    <script src="/sites/all/themes/tao/assets/js/jquery-3.2.1.min.js" type="text/javascript"></script>

    <!-- Jquery Validate -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>

<script>
$("#webform-client-form-45").validate();
</script>

```

The form does validate but if there is an error the submit button is disabled:

```
<input class="webform-submit button-primary  form-submit hide-submit-disable" type="submit" name="op" value="Submit" disabled="">

```

I cannot find where / why this is happening. If I do not use the validate plug-in then all works fine but my hope is to be able to use the plug-in.

Anyone else have an experience with this?

# Answer
I have used the Clientside Validation and it just automatically handles everything. I have not tested it with the latest Webform 8.x-5.x beta release.

There is also a screencast showing how the Clientside Validation module works with the Webform module for Drupal 8.
> 0 votes

---
Tags: javascript, webforms
---


# Question
Title: Show Taxonomy Terms that have been tagged on any piece of content
I have a content type and it allows for one taxonomy term to be tagged to it.

I want to show that term on each nodes page. How can I do this with views Please?

# Answer
With views, you can create a view of content with type filter of your specific content type. And then select format as fields

Then add the term reference field which saved the taxonomy term for nodes.

After that in Advanced settings, you will need to add contextual filter of node id. with default value to take from the URL.

You can make this view as a block and then assign this block on node pages.
> 0 votes

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


title: Check if cache cid exist

text:
# Question
Title: Check if cache cid exist
I have this code:

```
$cache = \Drupal::cache();
$result = $cache->get('tdcf_00SPH46T');

```

Then, I got this notice:

```
Notice: Undefined index: tdcf_00SPH46T in Drupal\Core\Cache\DatabaseBackend->getMultiple() (line 92 of core/lib/Drupal/Core/Cache/DatabaseBanckend.php).
Drupal\Core\Cache\DatabaseBackend->getMultiple(Array, ) Line: 63
Drupal\Core\Cache\DatabaseBackend->get('tdcf_00SPH46T')_(Line: 46)
...

```

Is any way for check if this cid is defined, for example:

```
$cache->has('tdcf_00SPH46T');

```

# Answer
> 1 votes
What database backend are you using? Sounds like a case problem, that a cache entry with a different upper/lower case version exists and then it can't map that back. I'd suggest using only lowercase but this shouldn't happen IMHO and it doesn't for me:

```
>>> $cache = \Drupal::cache();
=> Drupal\Core\Cache\DatabaseBackend {#48
     +"_serviceId": "cache.default",
   }
>>> $cache->get('foo');
=> false
>>> $cache->set('foo', 'bar');
=> null
>>> $cache->get('foo');
=> {#9809
     +"cid": "foo",
     +"data": "bar",
     +"created": "1505412278.945",
     +"expire": "-1",
     +"serialized": "0",
     +"tags": [],
     +"checksum": "0",
     +"valid": true,
   }
>>> $cache->get('Foo');
=> false

```

---
Tags: 8, caching
---


# Question
Title: Simple AJAX callback fired on form submission button click
I am trying to fire an AJAX callback when the user presses the submit button. This is such a simple thing but trying to debug Drupal's Form AJAX API is driving me crazy. At this point I just need a fresh set of eyes to look over it. Currently, when I press the button the page just refreshes and the AJAX callback is never fired. I have a form being built with the following code:

```
class OnlineRevenueForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['resetbutton'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#prefix' => '<div class="buttons">',
        '#suffix' => '</div>',
        '#ajax' => array(
            'callback' => 'Drupal\revenue_projection_model\Controller\RPMController::ResetFields',
            'event' => 'click',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        )
    );
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild(FALSE);
  }
}

```

Inside of my controller I load this form using the following code:

```
class RPMController extends ControllerBase implements ContainerInjectionInterface {
 public function rpm() {
    // Load the module's template file
    $TemplateFilePath = drupal_get_path('module', 'revenue_projection_model') . "/templates/revenue_projection_model.html.twig";
    $template = $this->twig->loadTemplate($TemplateFilePath);
    //Load Forms
    $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
        $markup = [
         '#type' => 'inline_template',
         '#template' => $template->render(
            ['online_rev_form' => $OnlineRevForm]
         )
        ];
   return $markup;
 }

```

This form is then displayed via the twig template file. The callback that I'm trying to call is also inside of the Controller:

```
public static function ResetFields(array &$form, FormStateInterface $form_state) {
     $ajax_response = new AjaxResponse();
     $ajax_response -> addCommand(new AlertCommand("Testing"));
     return $ajax_response;
}

```

**Update 1:** I have updated how the form is being return in the controller. It is now being returned as a unrendered form in a render array.

```
public function rpm() {
  $OnlineRevForm = \Drupal::formBuilder()->getForm('Drupal\revenue_projection_model\Form\OnlineRevenueForm');
  return [
        '#theme' => 'rpm_page',
        '#online_rev_form' => $OnlineRevForm
  ];
}

```

I have also added this code to the .module file:

```
function revenue_projection_model_theme() {
  $theme['rpm_page'] = [
    'variables' => ['online_rev_form' => NULL],
    'template' => 'revenue_projection_model',
  ];

  return $theme;
}

```

# Answer
> 2 votes
You also need a submit function.

You can have a look here. It's a complete example with submit handler and callback. In this case I altered the form as I didn't create it but is quite similar. Also a really nice post is here

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


# Question
Title: Credit card and check payments in one order type
I've created a store in Commerce 2. The store has 1 order type currently, which uses the default workflow (Draft-\>Completed/Cancelled). There is also 1 order item type only and all products belong to it. We currently have 1 payment gateway for people to pay by credit card (live).

I am now being asked to add payment by check as a possibility.

I added a new "Check" payment gateway using the "Manual" plugin and things looked good, but when choosing it, the order gets the "Completed" status. (Payment is "Pending" as expected.) This is rather counter-intuitive for the staff. Another status (even staying at "Draft") would be preferable.

I though to switch the order type to the "Default, with Validation" workflow (Draft-\>Validation-\>Completed/Cancelled). This seems like to right solution for people paying by check... But the vast majority of people pay by credit card and their order should be immediately be completed without any validation.

I also read up on creating a 2nd order type with the "Default, with Validation" workflow, but that seems to entail having a completely separate order item type (and therefore separate products!) so it seems like the wrong way to go.

* Is the solution to create a custom workflow that encompasses both possibilities? (With a way to transition from "Draft" to "Completed" for credit card payments and from "Draft" to "Validation" for check payments.)
* Or is it better to use the "Default, with Validation" workflow and have a subscriber wait for when an order is set to the "Validation" state, verify the payment gateway and advance the credit card orders to "Completed" automatically? (seems a bit hack-y)
* Is there another solution to this (I assume) common problem that I missed?

# Answer
Seems like I was wrong about the 2nd order type. Here's what I ended up doing:

I created a 2nd Order Type with the "Default, with Validation" workflow and a 2nd Order Item Type pointing to the new Order Type.

Then I used the "hook\_commerce\_order\_presave" hook to change the order type from the default first Order Type to the other at the "review" step of the checkout.

Still, to me, this seems like a common enough occurrence (checks & credit cards accepted in one store) that there should be a no-code solution. If someone know it, please share!
> 0 votes

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


# Question
Title: twig if Term ID is something, then do something
I have a taxonomy called Fish and 2 terms in it. Bass and Gold. I have a term reference field on a Page node, and its a select list. The editor can select either Bass or Gold. And I want display something depending on what the user selects. I cannot get it to work. This is what I have tried. Below the Bass tid is '1'.

```
{% if node.field_term_reference.value == '1' %}
  <p>The value is Bass</p>
{% else %}
  <p>The value is Gold</p>
{% endif %}

```

Below I am outputting the string value bass.

```
{% if node.field_term_reference[0]['#title'] == "bass" %}
  <p>The value is Bass</p>
{% else %}
  <p>The value is Gold</p>
{% endif %}

```

Both of these return "The value is Gold" I tried this also

```
{% if node.field_term_reference.label == "bass" %}
 <p>The value is Bass</p>
{% else %}
 <p>The value is Gold</p>
{% endif %}

```

What if you want to add multiple terms and use AND OR "bass" and "finch".

```
{% if node.field_term_reference.entity.label == "bass" and or "finch" %}

```

How would it be written?

# Answer
The original question is how to use the term id in a twig condition. You find the term id in the property `target_id` of the reference field:

```
{% if node.field_term_reference.target_id == '1' %}
  <p>The value is Bass</p>
{% else %}
  <p>The value is Gold</p>
{% endif %}

```
> 4 votes

# Answer
It's because the value of `node.field_term_reference[0]['#title']` in reality it's `<div class="something">bass</div>`; therefore, your condition is false every time. Same for the other two.

Thus, in your condition you need to get the raw (no markup) value of the field. See How do I get the raw field value in a template?

This should work:

```
{% if content.field_term_reference.0 == '1' %}
  <p>The value is Bass</p>
{% else %}
  <p>The value is Gold</p>
{% endif %}

```
> 2 votes

# Answer
I found the answer here if anyone needs it.

```
{% if node.field_term_reference.entity.label == "bass" %}
 <p>The value is Bass</p>
{% else %}
 <p>The value is Gold</p>
{% endif %}

```
> 0 votes

---
Tags: theming, 8
---


title: Error installing any module

text:
# Question
Title: Error installing any module
I have an error in my Drupal 7 site when I try to install any module.

If I try the Install from a URL I get:

> HTTP error 0 occurred when trying to fetch http://ftp.drupal.org/files/projects/google\_analytics-7.x-1.3.tar.gz.
>
> Unable to retrieve Drupal project from http://ftp.drupal.org/files/projects/google\_analytics-7.x-1.3.tar.gz.

If I try Upload a module or theme archive to install I get:

> An AJAX HTTP request terminated abnormally. Debugging information follows. Path: StatusText: ResponseText: ReadyState: 4

The error page shows me:

> Notice: Undefined index: log in update\_authorize\_install\_batch\_finished() (line 235 of V:\www\site\modules\update\update.authorize.inc).
> Warning: Invalid argument supplied for foreach() in update\_authorize\_install\_batch\_finished() (line 235 of V:\www\site\modules\update\update.authorize.inc).
> Notice: Undefined index: log in update\_authorize\_install\_batch\_finished() (line 276 of V:\www\site\modules\update\update.authorize.inc).
> Notice: Undefined index: tasks in update\_authorize\_install\_batch\_finished() (line 277 of V:\www\site\modules\update\update.authorize.inc).
> Installation failed! See the log below for more information.

Any ideas on how I can troubleshoot this?

# Answer
> 4 votes
This looks like a ownership / permissions problem on a Linux server. Make sure to set the ownership of the drupal root folder and underlying files to the webserver's user (like 'apache', for example).

Also, make sure that the "temporary" and the "private" folders are setup correctly and with the right permissions (if in doubt, just test with 777 - don't forget to lower them to your requirements afterwards).

# Answer
> 2 votes
There can be another issue at play, as well--the version of PHP you're running on your server.

I have a few test sites running in a local dev environment, and when I updated one from 7.39 to 7.42, all appeared OK, until I attempted to download module updates via the GUI where I was hit with HTTP error 0. Checked file path, OK. Ran update.php and cleared caches, still the same issue. Granted, I could run updates via Drush, just not the GUI.

On a hunch, though, I changed the version of PHP from 5.6.7 to 5.5.23, and the issue was resolved.

# Answer
> 0 votes
I have been having the same issue since moving my site from a hosted platform to an internal iis8 server2012 machine. I fixed the issue by installing and switching to the latest revision of PHP5.6 with wincache in Web Platform installer. There is not much info out there for us windows guys so I hope this helps someone else too.

# Answer
> 0 votes
* Install CA certificates (should be sufficient)

```
# apt-get install ca-certificates
```

In others cases:

* Configure /etc/php/7.0/apache2/php.ini

```
openssl.capath=/etc/ssl/certs/
```
* Fix function drupal\_http\_request

```
--- ./includes/common.inc       2017-06-21 15:20:18.000000000 -0300
+++ /var/www/drupal-7/includes/common.inc       2017-09-14 22:20:02.254394637 -0300
@@ -823,7 +823,7 @@
     'data' => NULL,
     'max_redirects' => 3,
     'timeout' => 30.0,
-    'context' => NULL,
+    'context' => stream_context_create(array('ssl'=>array('capath'=> ini_get('openssl.capath'),))),
   );

   // Merge the default headers.

```

---
Tags: 7
---


title: Drupal 7 drush - delete / edit views

text:
# Question
Title: Drupal 7 drush - delete / edit views
Drush for Drupal 6 had a plugin that allowed you to delete a view. That plugin's functionality was mostly rolled into drush for Drupal 7.

I have a view that can't be edited through the UI, and I was hoping the drush could solve the problem.

# Answer
I don't know of a Drush command for this, but if you know your view's machine name or ID wiping it from the database isn't too hard.

```
SELECT vid FROM views_view WHERE name = 'your_views_machine_name';
DELETE FROM views_view WHERE vid = id_from_above;
DELETE FROM views_display WHERE vid = id_from_above;

```

That should be the last you ever hear from that view.
> 4 votes

# Answer
Drush Views has not been fully incorporated in Views for D7 yet, supposidely only `drush views-export` works at this time. And, I couldnt get even that to work.
> 0 votes

# Answer
Or without doing a lookup for vid. Find the view id in the url, or html code.

For example in admin/structure/views/view/section\_banner, section\_banner is the view name.

```
delete views_display from views_display inner join views_view on views_display.vid = views_view.vid where views_view.name =  'view_name';
delete from views_view where name = 'view_name';

```
> 0 votes

---
Tags: views, drush
---


# Question
Title: After adding info an entity via hook_ENTITY_TYPE_storage_load, how do I access that data in hook_ENTITY_TYPE_view?
I'm adding data to the node on the storage\_load hook, and trying to put it into the $build on the view hook. However, when I try to get the data, I can't figure out how to do it. $node-\>get('i18nfiles') gives me a "Field i18nfiles is unknown" exception, while $node-\>values\['i18nfiles'\] cannob be accessed because it is protected. Sure miss simple stdClass objects about now. :) Code below.

```
/**
 * Implements hook_ENTITY_TYPE_storage_load() for nodes.
 *
 * @param type $nodes
 *   the array of nodes being loaded from the database.
 */
function hqq_node_storage_load(array $nodes) {
  $nids = array_keys($nodes);
  $result = db_query('SELECT fa.* FROM {node__field_attachments} fa INNER JOIN {node_field_data} nfd ON nfd.nid = fa.entity_id AND nfd.langcode = fa.langcode WHERE nfd.nid IN (:nids[]) AND nfd.status',[':nids[]' => $nids])->fetchAll();
  foreach ($result as $record) {
    $nodes[$record->entity_id]->i18nfiles['files'][$record->langcode] = $record->field_attachments_target_id;
  }
}

/**
 * Implements hook_ENTITY_TYPE_view() for nodes.
 *
 * @param array $build
 *   The renderable build array.
 * @param \Drupal\node\Entity\Node $entity
 *   The entity being rendered.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options.
 * @param string $view_mode
 *   The view mode for the entity.
 *
 */
function hqq_node_view(array &$build, \Drupal\node\Entity\Node $node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, string $view_mode) {
  if ($display->getComponent('i18nfiles') && ($files = $node->get('i18nfiles')->getValue())) {
    foreach ($files as $langcode => $fid) {
      $lang = Drupal::languageManager()->getLanguage($langcode)->getName();
      $url = file_create_url(File::load($fid)->getFileUri());
      $options[$url] = $lang;
    }
    $build['i18nfiles'] = [
      '#type' => 'select',
      '#options' => $options,
      '#attributes' => ['class' => ['i18nfiles']],
    ];
  }
  if ($display->getComponent('i18noutdated') && $node->get('content_translation_outdated')->value) {
    $build['i18noutdated'] = [
      '#type' => 'item',
      '#markup' => '<div class="messages messages--warning">' . t('This translation is outdated') . '</div>',
    ];
  }
}

/**
 * Implements hook_entity_field_info().
 * Returns an array of extra fields provided by the module.
 *
 * @return array
 *    The array of extra fields provided by hqq module.
 */
function hqq_entity_extra_field_info() {
  $extra = [];

  // Add the i18nfiles element, for translations of documents
  $extra['node']['document']['display']['i18nfiles'] = [
    'label' => t('Translated files'),
    'description' => t('A dropdown list of all languages in which a published translation is available'),
    'weight' => 10,
  ];

  foreach (NodeType::loadMultiple() as $bundle) {

    // Add also the 'language' select if Language module is enabled and the
    // bundle has multilingual support.
    // Visibility of the ordering of the language selector is the same as on the
    // node/add form.
    $configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', $bundle->id());
    if ($configuration->getThirdPartySetting('content_translation', 'enabled')) {
      $extra['node'][$bundle->id()]['display']['i18ninprogress'] = [
        'label' => t('Translation in progress'),
        'description' => t('An indicator for if there are translations in progress.'),
        'weight' => 0,
      ];
      $extra['node'][$bundle->id()]['display']['i18noutdated'] = [
        'label' => t('Translation outdated'),
        'description' => t('A notification if the current translation is outdated.'),
        'weight' => 0,
      ];
    }
  }

  return $extra;
}

```

# Answer
You access the property the same way you write it, as $node-\>i18nfiles. This goes through \__set()/\__get() which also supports non-fields.

That said, I'm a bit confused about what exactly you're doing. Your table name is node\__field\_attachments, so it looks like a managed field table, which would load the data automatically and making it available in $node-\>get('field\_attachments')?

And since it's a field, you could then write a custom formatter for that field to display the data and get rid of those hooks.

It is also kind of a deprecated approach, if what I said is for some reason not possible, I'd recommend to either just load the data when you need it in hook\_node\_view() (with both node load being cached as well as rendered nodes being cached it's hard to compare what is more performant) or make it a computed field, but those are currently still quite painful to implement, see PathItem in Drupal 8.4.x.
> 0 votes

---
Tags: 8
---


# Question
Title: How to create nested paragraphs items programmatically?
Basically, i am programmatically generating a node. Those nodes have several anidated paragraphs like this:

```
-title parent
 -body parent
 -links parent
 -title child
   -body child
   -links child

-another parent
 ..etc..

```

I'm doing this with paragraphs, i have a parent paragraph that includes another. At the time of generating the node i'm generating in a sufficient manner the parent paragraph with the following code: ('*field\_contenido\_padre*' is the field that contains the parent paragraph)

```
$paragraph = new ParagraphsItemEntity(
      array(
        'field_name' => 'field_contenido_padre',
        'bundle' => 'acordeon'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $parent);
$paragraph->field_titulo_acordeon[LANGUAGE_NONE][0]['value'] = $value["title"];
$paragraph->field_body[LANGUAGE_NONE][0]['value'] = "jajaja";

$ia = 0;
foreach ($value["items"] as $k => $item){
    $paragraph->field_link_archivo[LANGUAGE_NONE][$ia]['title'] = $item;
    $paragraph->field_link_archivo[LANGUAGE_NONE][$ia]['url'] = $value["items"][((int) $k + 1)];
}
$paragraph->save();

```

OK. this works. Following further from here is my problem. Now i would like to attach a child paragraph to this recently generated parent paragraph. I've tried the following with no success:

1. first, generate the child paragraph ('*field\_acordeon\_hijo*' is the field in parent paragraph that contains the child)

> ```
> $paragraph = new ParagraphsItemEntity(
>     array(
>       'field_name' => 'field_acordeon_hijo',
>       'bundle' => 'acordeon-hijo'));
> $paragraph->is_new = TRUE;
> $paragraph->setHostEntity('paragraphs_item', $parent);
> $paragraph->field_titulo_acordeon_hijo[LANGUAGE_NONE][0]['value'] ='TITULAko Hijo';
> $paragraph->body[LANGUAGE_NONE][0]['value'] = 'jajaja';
> $paragraph->save();
>
> ```

2. Now i try to save the recent child into the parent's container field:

```
 $entity = entity_load('paragraphs_item', array($parent->item_id));
 $entity = reset($entity);
 $entity->field_acordeon_hijo[LANGUAGE_NONE] = array(
     0 => array(
       'value' => $id_child,
       'safe_value' => $id_child,
       'format ' => NULL));
 $entity->revision = TRUE;
 $entity->save(FALSE);

```

I get no errors, the parent paragraph is generated fine, but i don't see the children paragraphs :-/

I guess it's because I'm attaching the child to the parent, while maybe I must attach it to the node; but in that case, how to point the child to the parent?

# Answer
After two days, finally, i got it working. Step 3 is not necessary. My error was in step 2, where I wrote badly the bundle name :-( so it was

```
new ParagraphsItemEntity(
    array(
      'field_name' => 'field_acordeon_hijo',
      'bundle' => 'acordeon_hijo'))

```

note the underscore in **acordeon\_hijo**
> 2 votes

---
Tags: 7, paragraphs
---


# Question
Title: Language switching does not work when browser language is configuired in drupal 8.3.7
Language switching fails after enabling browser on Detection and selection

> /admin/config/regional/language/detection

**Exisiting :**

On switching language from the browser the url changes but the content remains the same

E.g, Default language browser is Germen.

mywebsite.com mywebsite.com/about etc shows German content.

While swiched to English url changes to mywebsite.com/en mywebsite.com/en/about etc

It shows Germen content instead of English.

**Expected**

On browser configured with Germen as default language, the site url should be mywebsite.com/de.

When I swich to the English website, it should show English content

Please find the configuration.

# Answer
> -1 votes
I have fixed the issue with htaccess.Please refer this code,it may be helpful for similar issues.

```
  ## On frontpage redirect to /de if the browser language start with de
  RewriteCond %{HTTP:Accept-Language} ^de.*$ [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /de [L,R=302]

  ## On frontpage redirect to /en if the browser language start with en
  RewriteCond %{HTTP:Accept-Language} ^en [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]

  ## To make all other requests (that is, URLs not starting with /en/ or /de/) redirect to a default language (say en)
  RewriteCond %{HTTP:Accept-Language} () [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]

```

# Answer
> 0 votes
It is very obvious why this is happening. Language selection process the language detection systems from top to bottom. (Top has highest priority.) Your configuration means that the browser will always be selected first and that url and user settings are ignored.

If you move browser below user (drag with the arrows icon), the processing order will be:

* url
* user (if url resolved no language)
* browser (if user had no language configured)

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


# Question
Title: How to add onBlur attribute to ZIP code field in Address Field
In order to control the input format in the ZIP code field in the dynamic address fields provided by the Address Field module (I use it in Drupal Commerce) I need to add the attributes `onKeyUp` and `onBlur` to this field. My plan is to use Javascript to manage the formatting, but I need to add the above attributes first. How do I do that? I imagine I should use `hook_form_alter` in my template.php, but I could need a pointer on how to do it.

```
if($form['#id'] === "edit-customer-profile-billing-commerce-customer-address-und-0-postal-code"){
  dsm($form); // devel message does not show up in the checkout page in question
  $form['#attributes']['onBlur'] = '(this)';
}

```

EDITED: I have now managed to add the attributes this way:

```
  function mytheme_form_alter(&$form, &$form_state, $form_id) {
    if($form_id === "commerce_checkout_form_checkout"){
      // Merge new attributes with existing ones.
      $form['customer_profile_billing']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
      $form['customer_profile_shipping']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
    }
  }

```

And this is the js script (I found it here):

```
(function($) {
        $(document).ready(function(){
            'use strict';
        var setZip, setLimit;
        console.log('outside');

        function setZip(theField){
          console.log('setzip');
          var num = theField.value.replace(/\D/g,"");
          theField.value = num.substr(0,3)+" "+num.substr(2);
        }

        function setLimit(theField, maxDigit){
          console.log('setlimit');
          var num = theField.value.replace(/\D/g,"");
          if(num>maxDigit){
            theField.value = theField.value.substr(0,maxDigit);
          }
        }

    });

})(jQuery);

```

The problem now is that I get a javascript reference error like this:

> Uncaught ReferenceError: setZip is not defined at HTMLInputElement.onblur

I suspect this has something to do with the scope, so I have tried to place the js script with the setLimit and setZip functions in the header, in the body and in the footer, with the same error message. I also tried to remove the `$(document).ready(function()`... but the reference error reamins.

Any ideas?

# Answer
> 0 votes
In case anyone else has this same problem. I have learned that it's a better practise to only use Javascript with an addEventListener to do this job, due to the scope rules.

This is how I finally did it. Change the code to adapt the formatting to the standard format in your country. This one changes the ZIP code format to five digits with a space inserted between digit 3 and 4.

```
  if($("#edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").length){
    document.getElementById("edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").addEventListener("blur", function(){
        if(this.value.length>5 && /\s/.test(this.value)){
          this.value = this.value.substr(0,6);
        }   else if(this.value.length>5 && !(/\s/.test(this.value))){
                        this.value = this.value.substr(0,5);
                    }
        if(this.value.length===5 && this.value.substring(3,4) !== " "){
            this.value = this.value.split(/(?=.{2}$)/).join(' ');
        }
    });
}

```

---
Tags: 7, commerce, javascript
---


# Question
Title: Hook_preprocess - disable CSS caching with drupal_add_css
I'm wondering how to disable css caching when you use the function drupal\_add\_css. In hook\_preprocess I have some dynamic css loading with this function and by default it generates a cached version of the css file (f.e. style.css?ow65jm) and I couldn't find any information on how to disable this. It gives an issue with some third party applications how rebuild a page view (f.e. Hotjar) who expect a single version of an certain file.

I've checked the performance settings (admin/config/development/performance) and CSS and JS merge/compression is disabled.

Adding the CSS files directly into the tpl files can fixes this but can this also be accomplished with in the preprocess hook and with the drupal\_add\_css function.

*Update - Added template.php and .tpl code:*

template.php:

```
function mytheme_preprocess(&$vars, $hook) {
...
if (!(path_is_admin(current_path())) || (arg(0) == 'user' && arg(2) == 'edit')) {
      drupal_add_css('https://fonts.googleapis.com/css?family=Merriweather:700', array('type' => 'external'));
      drupal_add_css( $path_odisee . '/css/normalize.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => -10));
      drupal_add_css( $path_odisee . '/css/odisee.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => 0));
      drupal_add_css( $path_odisee . '/css/override.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'weight' => 0));
    }
...
}

```

html.tpl.php:

```
...
<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <?php print $styles; ?> <!-- here the preprocessed CSS gets loaded -->

</head>
...

```

Additional information: The people over at Hotjar suggested to keep the cached versions of the css files on the server. Any suggestion on how to force this?

# Answer
> 0 votes
You can try using AdvAgg. Not sure it'll fix your issue because the source of the problem hasn't been identified. https://www.drupal.org/project/advagg

---
Tags: 7, theming
---


# Question
Title: feeds importer only reading first 240 of csv
Using Feeds to upload a very simple csv of Node title and body fields, via the one time import form. It is only loading the first 250 rows regardless of the setting. I have tried adding `$conf['feeds_process_limit']` to my setting file, but it's not working.

`$conf['feeds_process_limit'] = 100;` will result in 250 being loaded

`$conf['feeds_process_limit'] = 1000;` will result in 250 being loaded.

Any ideas? I have tried moving around items in my csv so I know it's not bad data that is screwing up the works. I never get any other errors, or anything in the log.

thanks, summer

# Answer
> 1 votes
Do you use the process in background option? If so, run cron to complete the import. Else, try the dev version of Feeds. In there the UX on this part has been improved. Feeds will for example say that you need to run cron to continue the import.

---
Tags: feeds, importing-exporting
---


# Question
Title: How to migrate using explode with occasional empty array
We've made a migration from the City of Helsinki's Linked Events API, and during this work we've been seeing these migration messages:

> Array index missing, extraction failed

Here is an example of an event that works nicely: https://api.hel.fi/linkedevents/v1/event/hko:14004/

And one that causes the error: https://api.hel.fi/linkedevents/v1/event/matko:16134/

In the latter you see that offers is returned as an empty array. We're using the `skip_on_empty` plugin to handle those:

```
field_offers_is_free:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    index:
      - 0
      - is_free
field_offers_info_url:
  -
    plugin: skip_on_empty
    method: process
    source: offers
  -
    plugin: extract
    default: false
    index:
      - 0
      - info_url
      - fi

```

The problem is that never reaches the `skip_on_empty` plugin. I've been stepping through this in the debugger based on my findings I created an issue in Drupal Core https://www.drupal.org/node/2905929

When Get sets `$multiple` to `true`, `processRow()` in `MigrateExecutable` runs a `foreach ()` on an empty array - resulting in the `skip_on_empty` plugin to be skipped.

Is there something wrong in our setup or did I uncover a bug? Any ideas on how to work smoothly around this?

# Answer
I solved this by creating my own migrate plugin that sets the multiple flag to false if we get an empty array, like this:

```
/**
 * The Get plugin causes issues for us when it fetches and array that is empty.
 *
 * It sets multiple to true which prevents the skip_on_empty plugin from being
 * triggered.
 * @see https://www.drupal.org/node/2905929
 *
 * @MigrateProcessPlugin(
 *   id = "get_array_fix_multiple",
 *   handle_multiples = TRUE
 * )
 */

class GetArrayFixMultiple extends ProcessPluginBase {

  /**
   * Flag indicating whether there are multiple values.
   *
   * @var bool
   */
  protected $multiple;

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
      $array = is_array($value);
      $empty = empty($value);
      $this->multiple = $array && !$empty;
      return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() {
    return $this->multiple;
  }

}

```

Either the bug is in the get plugin or then skip\_on\_empty should support multiple.
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: "Drupal\Component\Plugin\Exception\PluginNotFoundException: The 'integer' plugin does not exist."
When I try to update from drupal 8.27 to 8.35, I get the following error. How can I resolve this issue?

> Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "integer" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of C:\Users\ven\_arajendra\Sites\devdesktop\offshore2-dev\docroot\core\lib\Drupal\Component\Plugin\Discovery\DiscoveryTrait.php).

# Answer
> 1 votes
As an option just try to add this code in the enabled custom module in your project.

```
/**
 * Implements hook_entity_base_field_info_alter().
 */
function custom_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
  if ($entity_type->id() === 'menu_link_content' && isset($fields['weight'])) {
    $options = $fields["weight"]->getDisplayOptions('view');
    // Lets check if field definition is buggy.
    if ($options['type'] === 'integer') {
      $options['type'] = 'number_integer';
      // @TODO: This should be fixed in the menu_link_content core module.
      // @see https://www.drupal.org/node/2903161
      $fields['weight']->setDisplayOptions('view', $options);
    }
  }
}

```

Or try to use this patch from this issue

---
Tags: 8, plugins
---


# Question
Title: Argument 1 passed to EntityViewBuilder must implement interface, null given
In my Drupal project I have this error:

> Recoverable fatal error: Argument 1 passed to Drupal\Core\Entity\EntityViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given, called in /Users/team1/workspace/ga\_p/modules/field\_collection/src/Plugin/Field/FieldFormatter/FieldCollectionItemsFormatter.php on line 33 and defined in Drupal\Core\Entity\EntityViewBuilder-\>view() (line 110 of core/lib/Drupal/Core/Entity/EntityViewBuilder.php).

I do not know if it's from having created multiple fields (fieldCollections)

But I do not know how to remove this error.

Drupal Version: 8.3.4

# Answer
Try this patch

```
diff --git a/src/Plugin/Field/FieldType/FieldCollection.php b/src/Plugin/Field/FieldType/FieldCollection.php
index 8721220..c5335be 100644
--- a/src/Plugin/Field/FieldType/FieldCollection.php
+++ b/src/Plugin/Field/FieldType/FieldCollection.php
@@ -183,19 +183,15 @@ class FieldCollection extends EntityReferenceItem {
   public function preSave() {

     if ($field_collection_item = $this->getFieldCollectionItem()) {
-      // TODO: Handle node cloning
-      /*
-      if (!empty($host_entity->is_new) && empty($entity->is_new)) {
+      $host = $this->getEntity();
+
+      // Handle node cloning
+      if($host->isNew() && !$field_collection_item->isNew()) {
         // If the host entity is new but we have a field_collection that is not
         // new, it means that its host is being cloned. Thus we need to clone
         // the field collection entity as well.
-        $new_entity = clone $entity;
-        $new_entity->target_id = NULL;
-        $new_entity->revision_id = NULL;
-        $new_entity->is_new = TRUE;
-        $entity = $new_entity;
+        $field_collection_item = $field_collection_item->createDuplicate();
       }
-      */

       // TODO: Handle deleted items
       /*
@@ -231,11 +227,10 @@ class FieldCollection extends EntityReferenceItem {
       }
       */

-      $this->newHostRevision = $this->getEntity()->isNewRevision();
+      $this->newHostRevision = $host->isNewRevision();

       // If the host entity is saved as new revision, do the same for the item.
       if ($this->newHostRevision) {
-        $host = $this->getEntity();

         $field_collection_item->setNewRevision();

diff --git a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
index 4d6ae09..800383f 100644
--- a/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
+++ b/src/Plugin/Field/FieldWidget/FieldCollectionEmbedWidget.php
@@ -104,9 +104,8 @@ class FieldCollectionEmbedWidget extends WidgetBase {
   protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
     // We don't want to render empty items on field collection fields
     // unless a) the field collection is empty ; b) the form is rebuilding,
-    // which means that the user clicked on "Add another item"; or
-    // c) we are creating a new entity.
-    if ((count($items) > 0) && !$form_state->isRebuilding() && !$items->getEntity()->isNew()) {
+    // which means that the user clicked on "Add another item"
+    if ((count($items) > 0) && !$form_state->isRebuilding()) {
       $field_name = $this->fieldDefinition->getName();
       $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
       $parents = $form['#parents'];

```

mentioned here.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How to show translated taxonomy terms in a view?
I have used the Views module to create a view of taxonomy terms.

The taxonomy terms are translated in the Greek language also (apart from English), using the typical i18n modules.

But when I switch the language to Greek (while visiting the site), still the English taxonomy terms are appearing (and not the terms in Greek).

How can I solve this?

# Answer
Make sure to use the Internationalizations Views module, which extends the i18n module with multilingual support for Views.

To make Views results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the **User's Current Language** is available in the filter criteria form, then verify your configuration at *Configuration -\> Languages -\> detection and selection*: The order should be **URL, Default, User** and not something like **Default, URL, User** (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

If you're using **Block visibility settings** and indicated to only show that block on page `<front>`, then be aware that you may have to address yet another translation issue, as illustrated in my answer to the question How to make content translation available for front page?. It is about using the Variable module to correctly translate the **Default frontpage value**. Without that, Drupal will only show that block on the frontpage of your default value.

**Notes**:

1. True, the Internationalizations Views module only has a **DEV** version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+31K users can't be wrong*, right?
2. Filtering Views results in a multi language site can sometimes be challenging, as illustrated also in discussions such as in https://groups.drupal.org/node/47478 .
> 4 votes

# Answer
Instead of adding the term: name, add term: name (localized) to your view.
> 4 votes

# Answer
You need to add multilingual content for each term in your Taxonomy and inside the Views block use the "Content: Tag (field\_tag) (translated)" term as exposed filter. Similarly if you want to display Node Title we need to use "Entity translation: Node Title: translated" fields.
> 2 votes

# Answer
You need to install the i18n module, enable taxonomy translation and then do that programatically, for example in a block implemented by a custom module that calls `i18n_taxonomy_localize_terms()`.
> 1 votes

# Answer
Assuming you're using Drupal 7 and the *Taxonomy Translation* module (i18n\_taxonomy, part of Internationalization (i18n)...

I wrote the following for one of my clients. It works for the sites it was intended for, but as Drupal configurations can differ massively from one site to another, YMMV :)

* Works for a vocabulary with *translation mode* set to *Localize. Terms are common for all languages, but their name and description may be localized*.
* Works when the View displays content (*base table* is *node*) and displays taxonomy terms via *Content: All taxonomy terms*.
* Also works when the View is displaying taxonomy (*base table* is *taxonomy\_term\_data*).

Note use of taxonomy\_term\_load\_multiple for better performance. There are some solutions offered elsewhere that load terms one by one and translate them one by one.

```
/*
 * Implement hook_views_pre_render(&$view)
 * Here we handle translation of taxonomy terms.
 * Note: i18n_taxonomy_views module has its own _views_pre_render hook
 * but that does not currently (7.x-1.18) do what we need here.
 * This could probably be done using HOOK_views_post_execute instead.
 */
function mymodule_views_pre_render(&$view) {
  // If the i18n_taxonomy module is not installed then we have nothing to do.
  if (!function_exists('i18n_taxonomy_localize_terms')) {
    return;
  }

  // ----- Processing for content-based (nodes) View -----
  if ($view->base_table == 'node') {
    //dpm($view->field['term_node_tid']->items, 'pre render: field[term_node_tid]->items');

    // If there is no term data then exit now.
    if (empty($view->field['term_node_tid']->items)) {
      return;
    }

    // Array to track tids used and placeholders for term name translations.
    $term_translations = array();
    // Loop through nodes in the result set, track the term ids used and set a reference to the translation...
    foreach ($view->field['term_node_tid']->items as $nid => &$vterms) {
      // Loop through all terms for this node.
      foreach ($vterms as $tid => &$vterm) {
        // Track this term id.
        $term_translations[$tid] = '';
        // Store a *reference* to the translated term name which will be loaded later (below).
        $vterm['name'] =& $term_translations[$tid];
      }
    }

    // Load the terms that we need.
    $terms = taxonomy_term_load_multiple(array_keys($term_translations));
    // Fetch the translations of the terms.
    $terms= i18n_taxonomy_localize_terms($terms);
    // Update our $term_translations array with the translated term names.
    foreach ($terms as $tid => $term) {
      $term_translations[$tid] = $term->name;
    }
  }

  // ----- Processing for taxonomy-based View -----
  elseif ($view->base_table == 'taxonomy_term_data') {
    // Reference the terms array from $view->result.
    $vterms =& $view->result;

    // Build an array of tids...
    $tids = array();
    foreach ($vterms as $vterm) {
      $tids[] = $vterm->tid;
    }

    // Load all terms.
    $terms = taxonomy_term_load_multiple($tids);
    // Translate the terms.
    $terms = i18n_taxonomy_localize_terms($terms);

    // Copy translations for term names and descriptions back into the $view->result.
    foreach($vterms as &$vterm) {
      $vterm->taxonomy_term_data_name = $terms[$vterm->tid]->name;
      $vterm->taxonomy_term_data_description = $terms[$vterm->tid]->description;
    }
  }
}

```
> 0 votes

---
Tags: views, taxonomy-terms, i18n-l10n
---


# Question
Title: Adding content of products based on subtype
I have type (eg. women in clothes) and sub type (eg. jeans in women category). Now i need to add product but the product properties are decided by type(women) and sub type(jeans) and product is itself custom content type. I know in eCommerce website, this is basic situation but my project(**drupal 7**) is not eCommerce. I need to create this manually.

I have created the category and sub category as custom content type and mapped subcategory to category using entity reference. Now i have created new content type "product feature" and mapped to subcategory using entity reference. Now i need to add those product feature as field to the product when admin add the product. I need help in that.

# Answer
Lets start by saying that content types are not meant to be used for grouping. Drupal content (nodes) come with permission checking and invoke a lot of hooks upon loading. That is not bad per sé (and in fact required for most content), but is overkill for grouping. Your parent child structure would involve 3 node loads where you want to display one.

If you need grouping, you need taxonomy. This offers almost the same functionality as content types with regards to fields and url aliases, but is much lighter in use. To start you could recreate your reference structure using taxonomy terms.

However, as I already explained in the comments, why not use nested taxonomy? You could place all your categories in one taxonomy vocabulary, allowing you to see, edit and rearrange all terms from one page. It would make your system much more maintainable. Also the fact that you state that you need second level terms to show up after selecting the first is possible. Have a look at Hierarchical Select, Simple hierarchical select and Client-side hierarchical select. These offer exact that functionality.

Your last requirement (if there is more please edit them into the question):

> I need to list category and sub category separately

Depending on how you want to achieve this, is can be done. With views it is very easy. Add a filter to the view, select the parent term, then select that it should be empty. It should give you a list of top level taxonomy terms.
> 0 votes

---
Tags: entities
---


# Question
Title: How can I translate config entity fields?
The question is fairly straight forward. I have several config entities with various fields.

I haven't found a way to translate config entity fields in the Drupal 8 documentation(or maybe I haven't looked hard enough, both are a strong possibility).

# Answer
> 5 votes
You need a schema of the type `config_entity`.

See for example the one for the node type config entity:

*/node/config/schema/node.schema.yml:*

```
node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

```

Choose for fields you want to make translatable the types `label` and `text`. See also D8 How to create custom configurational form translatable?

---
Tags: 8
---


title: How do I change the views ajax URL?

text:
# Question
Title: How do I change the views ajax URL?
I build a view page and have exposed filter, when I change any filters I use ajax to fetch data and re-build the content area. The ajax URL looks like

> views/ajax

I want to change the above URL to some external middleware something like below

> http://www.example.com/getData

with the existing post data. Is it possible?

# Answer
You can try changing the settings data on the `ajaxSend` event.

```
$(document).ajaxSend(function(event, request, settings) {
  settings.url = '/views/ajax';
});

```
> 1 votes

---
Tags: views, ajax, search
---


# Question
Title: Display all nodes with identical field value to current node
**BACKGROUND:** Site is using content types which are auto-created through Rules, called CT-A and CT-B. CT-B represents a full URL, and CT-A represents that URL domain. CT-A is always created via Rules only once, the first time a content type CT-B is created. Both content types share a field (*field\_domain*) specifying the domain. The original content is user entered, so it isn't possible to predict the value of *field\_domain* in advance.

**ISSUE:** I need to display a simple 'related content' type view in CT-A, showing all nodes of type CT-B which match the value for *field\_domain*. The value for *field\_domain* cannot be pre-defined, and needs to be provided program / systematically, either by being taken from the field in the node, or as a token (same difference).

**APPROACHES:** I am assuming the answer is in Views. Specifying a value for *field\_domain* doesn't work, because the value changes based on user entry. I've tried Global: Field Comparison, but it doesn't seem to be possible to compare both the current node's *field\_domain* and that same field in the nodes displayed in Views. I have tried using Views Panes to pass the argument for the current node's *field\_domain* into the pane display, but it also didn't return results. I have seen various Contextual Filter PHP solutions, but they also don't seem to work (the most promising one is https://www.drupal.org/node/1006484#comment-4990312 , but this returns the following error: https://www.drupal.org/node/829250).

**Taxonomy** hasn't worked, because of the auto-create nature. It doesn't seem to be possible to create unique TermID by passing values in Rules - the Term name will be the same, but the TermID is different, and Views judges the Term based on its ID. It isn't possible to auto-create a Term Vocabulary in Rules due to a bug with assigning the machine name.

**Entity Reference** also has problems with the auto-create nature. I haven't figured out a way in Rules to reference the two types according to field\_domain value, and not sure if there is one.

**Search API** Tried this approach (compare the search index) suggested in the link below, but again it doesn't work unless you have a predefined value for *field\_domain*, as it requires setting the value manually.

The most obvious approach seems to be "Views filter display all nodes with same field value. But despite being obvious, this doesn't seem to be easily possible. Perhaps there is a non-Views way which I haven't considered?

Related questions to this (all seem to be unsolved):

\[apologies, I'm limited by reputation...but there are at least 4 open questions in related questions to the right which are still unsolved\]

Throwing it open...seems like a few people have run up against this problem. Any new ideas out there?

# Answer
> 2 votes
The way I've always handled this is to build the view in question using the "field value to match" as a Contextual Filter. For the Contextual Filter's settings, choose "Provide default value", for the type choose "PHP Code", and for the "PHP contextual filter code", load the current node and grab it's field value,

```
$node = menu_get_object();
return $node->field_domain['und'][0]['value'];

```

# Answer
> 0 votes
\** !! SOLUTION !! \**

A version of Sgorneau's suggestion worked. For some reason, a contextual filter comparing the node field (e.g. the page in which the view is displaying) with the same field in the displayed nodes (e.g. the nodes in the view) was not working for me. As a test, I created an identical field value in both types of node and compared those fields to each other. This now works in the View as desired. Steps for anyone trying to replicate:

Create a mirror field for the field you want to view (Rules -\> Event: after saving / updating content -\> Condition: has "field\_domain"-\> Action: Set data value: Set "field\_domain\_copy" using value for "field\_domain".

Views -\> Create -\> Content -\> Content type Contextual Filter -\> Content:domain (field\_domain) -\> When filter not available provide default value. Select PHP, enter this code:

```
$node = menu_get_object();
return $node->field_domain_copy['und'][0]['value'];

```

Filter -\> Content:Type -\> select content type to display if appropriate

So in effect, although comparing the value for the same field wasn't working for me, for some reason, comparing the actual value from a different field works fine. No idea why this is, whether it is a problem with my individual build or more widespread, but in case anyone finds the same problem, you can try this workaround.

---
Tags: 7, views, entities, rules
---


# Question
Title: 8 - How to open node preview in a new tab
I'm trying to get the preview button to always open in a new tab. Are there any "clean" or "correct" ways of doing this? Currently I feel like I would need to hack core to achieve the job.

# Answer
I was able to create a simple hack with jQuery that works better than I expected. I would prefer to handle it in php though. What I did was when the user hovers over the preview button I manually add and remove the target attribute to the form.

```
jQuery('#edit-preview').on('mouseover', function(e){
  jQuery('.node-form').attr('target', '_blank');
});
jQuery('#edit-preview').on('mouseout', function(e){
  jQuery('.node-form').removeAttr('target');
});
jQuery('#edit-preview').on('click', function(e){
  jQuery('.node-form').attr('data-drupal-form-submit-last', '');
});

```

The last part, allows the form to be submitted after launching the preview. Otherwise, it thinks you are hitting the submit button twice.
> 1 votes

---
Tags: 8
---


# Question
Title: How to get the number of items in a user's cart from commerce?
I've been looking into the drupal 8 commerce module, I want to take the variable **$count** that is generated within

> ../commerce/modules/cart/src/plugin/block/CartBlock.php

and place it into a custom block in my own theme. I see that the build() function returns the count variable through #count which can then be accessed via twig. Just for reference Drupal commerce currently uses the template:

> ../commerce/modules/cart/templates/commerce-cart-block.html.twig

to output the variables and markup:

```
<div{{ attributes}}>
  <div class="cart-block--summary">
    <a class="cart-block--link__expand" href="{{ url }}">
      <span class="cart-block--summary__icon">{{ icon }}</span>
      <span class="cart-block--summary__count">{{ count_text }}</span>
    </a>
  </div>
  {% if content %}
  <div class="cart-block--contents">
    <div class="cart-block--contents__inner">
      <div class="cart-block--contents__items">
        {{ content }}
      </div>
      <div class="cart-block--contents__links">
        {{ links }}
      </div>
    </div>
  </div>
  {% endif %}
</div>

```

My question is, how I can I make that variable global, are there any implications to just making it global, like what if the user updates the basket?

How do I go about achieving this? Does anyone have a possible solution?

# Answer
> 1 votes
you will have to use hook\_preprocess\_hook to achieve this by passing the variable to the template.

```
function template_preprocess_TEMPLATE_NAME(&$variables) {
    $variables['YOUR_VAR_NAME'] = $YOUR_VAR;
}

```

Then you can access your var in the template like so:

```
{{ YOUR_VAR_NAME }}

```

---
Tags: theming, 8, commerce
---


title: Add config forms to existing admin page

text:
# Question
Title: Add config forms to existing admin page
Instead of creating a new route and menu:

```
  amustatuscode.config:
  path: '/admin/config/statuscode/config'
  defaults:
    _form: '\Drupal\amu_http_status_code_display\Form\AmuHttpStatusCodeDisplayConfigForm'
    _title: 'HTTP status code error messages'
  requirements:
    _permission: 'administer http status code'

amustatuscode.config:
  title: 'AMU HTTP status code'
  description: 'Customize HTTP status code error messages'
  parent: system.admin_config
  route_name: amustatuscode.config
  weight: 100

```

How can I add this form to the existing basic site settings?

> /admin/config/system/site-information

# Answer
You could extend the default form by using a Route subscriber. To do so, create a file named RouteSubscriber.php whithin your module in a src/Routing folder.

the file should look like this:

```
<?php
namespace Drupal\YOUR_MODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.site_information_settings'))
      $route->setDefault('_form', 'Drupal\YOUR_MODULE\Form\ExtendedSiteInformationForm');
  }

}

```

You should then create a ExtendedSiteInformationForm.php file within your module src/Form folder like that:

```
<?php

namespace Drupal\YOUR_MODULE\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\system\Form\SiteInformationForm;

class ExtendedSiteInformationForm extends SiteInformationForm {

   /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
   $form=  parent::buildForm($form, $form_state);
   //update your $form...
   return $form;
}
}

```

This way you won't need your routing.yml file anymore.
> 2 votes

---
Tags: 8, forms, routes
---


# Question
Title: How do I display a form element only when a checkbox is selected?
I want to create a form with a checkbox and two text fields. The text fields should only be shown when the checkbox is selected.

I am using this code.

```
$form['display_count'] = [
  '#type' => 'checkbox',
  '#title' => t('Display count'),
  '#description' => t('Display how many times each term is used on a node.'),
  '#default_value' => $config['display_count'],
];

$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => [
    'visible' => [
      ':input[name="display_count"]' => [
        ['checked' => TRUE],
      ],
    ],
  ],
];

$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => [
    'visible' => [
      ':input[name="display_count"]' => [
        ['checked' => TRUE],
      ],
    ],
  ],
];

```

Setting the #states value doesn't seem to work.

How do I display a form element only when a checkbox is selected?

# Answer
> 1 votes
Use like this:

```
$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];
$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];

```

---
Tags: forms, blocks
---


# Question
Title: My static content has query string and this keeps on changing why?
I have a Drupal website. I've tested my site with speed sites like gtmetrix.com, and they advised to remove query strings (e.g. http://www.example.com/script/jquery.js?n) from my static content.

I also noticed that the "n" keeps changing sometimes to another character like "h" or something else.

Why do these query strings keep changing? Plus, is there anyway to stop having those query strings?

# Answer
This is part of Drupal's caching mechanism, it caches the css and js files that is why you get this query string. It is not recommended to remove this caching. But for development purpose we can disable it by adding the following in settings.php file,

```
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data
$conf['cache_default_class'] = 'DrupalFakeCache';

// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

For more info, from drupal.org
> 0 votes

---
Tags: views
---


# Question
Title: Custom products, variations and order items
I'm trying to create custom products with Commerce 2. More specifically I'm trying to have custom ui for customers to build their purchasable products.

I thought that I would be able to create single Product and it's variation and then make some adjustments for price and some other fields. It seems that I'm able to programmatically create custom OrderItem, set all custom fields as needed and then add item to cart. Apparently this works as expected.

But I'm having issues getting custom price set for the OrderItem. Seems that I have to create separate ProductVariation for each ordered item, even if it's the same in all practical purposes. Only differing data is price. I tried using instructions here(http://docs.drupalcommerce.org/v2/recipes/orders.html).

```
$order_item = \Drupal\commerce_order\Entity\OrderItem::create([
  'type' => 'custom_order_item_type',
  'purchased_entity' => $variation_red_medium,
  'quantity' => 2,
  'unit_price' => $variation_red_medium->getPrice(),
]);
$order_item->save();

```

If I leave unit\_price empty, to be set later, I get TypeError: Argument 1 passed to Drupal\commerce\_order\Entity\OrderItem::setUnitPrice() must be an instance of Drupal\commerce\_price\Price, null given, called in /var/www/drupalvm/web/modules/contrib/commerce/modules/order/src/OrderRefresh.php on line 143

I'm trying to do this:

```
// You can also set the price with setUnitPrice.
$unit_price = new \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price);
$order_item->save();

```

Only way I got this to work was setting ProductVariation price separately, but this then updates the basic price on the Product page, which really isn't what I'm looking for..

On the documentation it says this:

```
 * adjustments [OPTIONAL] - [Array(Drupal\commerce_order\Adjustment)]
 *   Array of any price adjustments.

```

but I can't get this far because OrderItem creation fails because of the missing price. If I set price, it just get's overridden from the initial ProductVariation.

I suppose that I can get around this by creating those ProductVariations on the fly, but I'd rather not since I don't need those for anything else than this single purchase.

So I guess I'm looking for some instructions on how to do dynamic products. Tried PurchasableEntity initially, but couldn't get that working at all and wasn't able to reverse engineer my needs from ProductBundle or similar.

Or any info how to set OrderItem price independently from ProductVariation.

Cheers,

Janne

# Answer
When setting the unit price, you must set the override parameter to true as so:

```
$unit_price = new \Drupal\commerce_price\Price('9.99', 'USD');
$order_item->setUnitPrice($unit_price, TRUE);
$order_item->save();

```
> 2 votes

# Answer
I'm just starting to look into this myself. Ideally, I'd like to be able to let admin users directly edit the unit price field as well as the total price field for any order item. (Sometimes for bulk orders, there's no way to set the price properly by multiplying the unit price if we want to avoid weird total prices like $10,000.01.)

I just figured out one thing that might help you set the prices independent from the product variation prices. It's the "order refresh" stuff that causes the custom price overrides. (Drupal\commerce\_order\OrderRefresh::refresh()). And since the order refresh stuff only happens when the order is in Draft state, if you transition the order to another state, you can then manually edit the unit prices without them getting overwritten.

If you use the validation workflow, you could set custom prices as soon as you change an order's state from Draft to Validation (or you could create your own custom workflow.)
> 0 votes

---
Tags: 8, commerce
---


title: Search facets by title vs node id

text:
# Question
Title: Search facets by title vs node id
I have Search API, Search API Solr and Facets setup in drupal 8. The view settings used as data source for the facet is as below.

There are two content types: Language and Role. Both are used as inline entities in other content types with field names: file\_language and field\_role. The facet setting are as below:

However, in the facet browse view language is displayed with title link and role is displayed as node id link.

I am not sure which setting is causing this issue. How to display role by title, similar to language?

Thank you

# Answer
Compared the facet definitions via Dev module and noted the " Transform entity ID to label" option. That does it.
> 1 votes

---
Tags: views, search
---


# Question
Title: Issue with translating SQL query into Database API (count(*))
I'm currently building some SQL queries for a view that will display some statistics, and I'm having trouble with adding `COUNT(*)` in a couple SQL queries:

**Original SQL query**

```
SELECT LIBELLE, COUNT(*)
FROM PRESTATIONS
WHERE EXERCICE = 2017
AND NUMCOLL = 89519
AND ETAT = 'R?gl?e'
AND PRESTATION = 'AIDES'
group by LIBELLE;

```

The result is the following:

```
+----------+----------+
| LIBELLE  | COUNT(*) |
+----------+----------+
| RESULT 1 | 1        |
+----------+----------+
| RESULT 2 | 3        |
+----------+----------+

```

This is how I set my code up after reading a bit of documentation:

```
$group = $value->andConditionGroup()
    ->condition('EXERCICE', 2017, '=')
    ->condition('NUMCOLL', 89519, '=')
    ->condition('ETAT', 'R?gl?e', '=');

$con = \Database::getConnection('old_db');
$value = $con->select('PRESTATIONS', 'prestations');
$value->fields('prestations', ['LIBELLE']);
$value->condition($group);
$value->condition('PRESTATION', 'AIDES', '=');
$value->groupBy('LIBELLE');
$nb_demandes = $value->countQuery()->execute()->fetchAll();

```

However, when executing this code, I have the following error:

> Syntax error or access violation: 1055 'old\_db.prestations.PRESTATION' isn't in GROUP BY: SELECT COUNT(\*) AS expression FROM (SELECT prestations.PRESTATION AS PRESTATION, prestations.LIBELLE AS LIBELLE, 1 AS expression FROM {PRESTATIONS} prestations WHERE ( (EXERCICE = :db\_condition\_placeholder\_0) AND (NUMCOLL = :db\_condition\_placeholder\_1) AND (ETAT = :db\_condition\_placeholder\_2) )AND( (EXERCICE = :db\_condition\_placeholder\_3) AND (NUMCOLL = :db\_condition\_placeholder\_4) AND (ETAT = :db\_condition\_placeholder\_5) )AND (PRESTATION = :db\_condition\_placeholder\_6) GROUP BY LIBELLE) subquery; Array ( \[:db\_condition\_placeholder\_0\] =\> 2017 \[:db\_condition\_placeholder\_1\] =\> 89519 \[:db\_condition\_placeholder\_2\] =\> R?gl?e \[:db\_condition\_placeholder\_3\] =\> 2017 \[:db\_condition\_placeholder\_4\] =\> 89519 \[:db\_condition\_placeholder\_5\] =\> R?gl?e \[:db\_condition\_placeholder\_6\] =\> AIDES )

I do believe I didn't set up my `COUNT(*)` correctly but I can't find another way to do so.

How can I solve this?

Thank you in advance

# Answer
As @Clive said, just add an expression to your first query. countQuery() is only about getting a single count for a query and in many cases it is very inefficient.

```
$con = \Database::getConnection('old_db');
$query = $con->select('PRESTATIONS', 'prestations');
$query->fields('prestations', ['LIBELLE']);
$query->addExpression('COUNT(*)', 'count');
$query->condition($group);
$query->condition('PRESTATION', 'AIDES', '=');
$query->groupBy('LIBELLE');

foreach ($query->execute() as $row) {
}

```
> 2 votes

---
Tags: 8, database
---


# Question
Title: Use path argument of display in fitler criteria
I have a view which displays all terminology terms from a specific terminology.

The view also have a display with a `path=/taxonomy/term/%` so if I go to "details page" of a specific term, the display is used.

This works fine expect that it, of course, that the view filters for all terms in that terminology. I now want to only show the `%` one.

Can I somehow use the `%` in my filter criteria?

I think that what I want is to use the parametric value `%` inside "Configure filter criterion: Taxonomy term: Term ID"

# Answer
> 0 votes
The `%` sign corresponds with an argument. Within views, these are known as contextual filters (advanced section).

If you add a contextual filter for `taxonomy id` and provide a numeric value for the % it should work. You also get options for what to do when % is empty, etc.

---
Tags: views
---


# Question
Title: how to show teaser view of my content types in search result page in drupal 7
I have customize my teaser view of my content types. Now i want to show that teaser view in search result page also. How can i do this? If anyone can give me a example with code will great help.

# Answer
> 0 votes
1. You can use template\_preprocess\_search\_result for that

```
function MYTHEME_preprocess_search_result(&$vars) {
  $node = $vars['result']['node'];
  if ($node->nid) { // here you load the teaser if the result is a node
    $vars['teaser'] = node_view($node, 'teaser');
  }
}

```
2. You can make a template file to customize the result: https://api.drupal.org/api/drupal/modules!search!search-result.tpl.php/7.x

---
Tags: theming, search
---


title: Set regions size

text:
# Question
Title: Set regions size
Very new Drupal user and I'm building a theme for my site on Drupal 8, I've setup everything, the site works locally. Now I would like to know how do I make my regions look like the schema (see Image). What files do I edit and which values to add, edit.

Edit: The theme is under construction, so now it has only 4 files: .info.yml, .libraries.yml, styles.css and page.html.twig.

Below their contents: page.html.twig:

```
    <div id="page">

  {% if page.headline %}
    <section id="headline">
    <div class= "container">
      {{ page.headline }}
    </div>
    </section>
    {% endif %}

  <header id="header">
    <div class="container">
        {{ page.header }}
    </div>
  </header>

  {% if page.navigation %}
  <navigation id="navigation">
    <div class="container">
        {{page.navigation}}
    </div>
  </navigation>
  {%endif%}

  <section id="main">
    <div class="container">
        <div class="row">
            <div id="content" class="col-md-9 col-sm-9 col-xs-12">
                {{ page.content }}
            </div>
                {% if page.sidebar %}
            <aside id="sidebar" class="sidebar col-md-3 col-sm-3 col-xs-12">
                 {{ page.sidebar}}
            </aside>
                 {% endif %}
        </div>
    </div>
  </section>

  {% if page.footer %}
    <footer id="footer">
      <div class="container">
        {{ page.footer }}
      </div>
    </footer>
  {% endif %}
</div>

```

mytheme.info.yml:

```
name: MyTheme
type: theme
base theme: classy

Description: "Theme moderne et responsif pour Drupal 8"
package: custom
core: 8.x

regions:
      headline: headline
      header: header
      navigation: navigation
      content: content
      sidebar: sidebar
      footer: Footer

```

style.css :

global-styling: css: theme: includes/bootstrap/css/bootstrap.css: {} css/style.css: {}

The .libraries.yml file has nothing yet.

# Answer
1. You can edit that only by using CSS.
2. You can add a theme like Boostrap that have predefined classes for that (and you only add the classes, like col-md-6), or you can add your classes in page.html.twig (you search the region in your template file, add a class to the wrapper and then define a size for it via CSS).
> 1 votes

---
Tags: theming
---


title: Add custom action buttons to a view

text:
# Question
Title: Add custom action buttons to a view
Suppose that I have a view that outputs a list of some content. Now I'd like to add some action buttons next to each content item, so that clicking these buttons triggers some custom action or redirect the user to another path (specific for that item).

I found a solution here that comes close to what I'd like to do, but that solution is based on D7 Add custom action buttons to view. Without repeating the content of this link, could someone let me know whether that approach is still valid/good practice for Drupal 8?

In case it is the solution, how would you implement the functionality of passing the $nid of a list item to a different form via POST when clicking one of the action buttons ? Would this be part of the function `function query() {...}` in step 5 of the link ? If so, how would you approach this ?

Are there solutions that might be better suited to D8?

# Answer
> 5 votes
Drupal 8 lets you add 'DropButtons' to your View, which looks really good in UI.

1. add a 'Custom text' field for each action you want to provide - use 'exclude from display' and 'output as custom link'
2. add a 'dropbutton' field and select your custom links to be shown in it
3. profit

---
Tags: views, 8, forms
---


# Question
Title: Which Omega theme should I use with Drupal 7?
I need to use the Omega theme framework. I find there is two different versions: Omega 3 and Omega 4.

Which one should I use with Drupal 7?

# Answer
There are Drupal 7 versions of both, so you can choose either. As of writing the 4.x branch is actively maintained, and 3.x not so much.

The 3.x branch will hold your hand a lot more, and make a lot of decisions about how you want to work. This may be or ideal, or may be frustrating. SASS support is clunky and a bit of a pain to work with, if I'm honest. Its main 'selling point' is that you can configure most of the options it supports through the UI.

The 4.x branch is much more of a developer-focused solution. Very little UI, but it incorporates a full front-end stack of tools for development/asset management. If you're a developer, this will likely be the one for you.

This is what the docs have to say:

> Whether you should use Omega 4.x or Omega 3.x depends on several considerations:
>
> * Do you rely on the user interface for building layouts, or are you comfortable defining layouts in code in a tpl.php file? Omega 4.x does not include the elaborate layout definition UI that was a hallmark of Omega 3.x
> * Do you want to use a theme that is under active development, or are you comfortable with a theme that is minimally maintained? Omega 3.x is minimally maintained. In all likelihood, unless a new maintainer steps up to the task, Omega 3.x will not be upgraded to Drupal 8.
> * Are you comfortable with or willing to learn SASS, or do you want to stick with straight CSS? Omega 4.x does NOT require use of SASS but certainly is much easier to implement if you adopt SASS.

Beyond that, the only way you'll get a satisfactory answer is to install and try both.

**Edit**: to add a bit of balance to the above docs (thanks @FreeRadical for the info):

The 2nd point (claim?) *is hotly disputed. It has been written by the Omega 4.x team who currently holds "ownership" over the project pages. This is a bitter dispute and there are negotiations currently taking place which probably will get the project page rewritten soon.*

Sounds like fun :/
> 5 votes

# Answer
On Omega 3.x vs. Omega 4.x - Comparing Apples and Oranges, you can read:

> Whether you should use Omega 4.x or Omega 3.x really depends on how much you want to rely on the user interface for building layouts as this is no longer included in the 4.x branch. If you are okay with a possible lack of documentation and the fact that Omega 4.x does not come with a layout builder as 3.x did then you should definitely prefer the 4.x branch.

It is really a matter of personal taste/skills and of course the form of the project. I am using Omega 3.x, and it suits my purposes perfect. I don't have any really experience with Omega 4.x, and when i got between those two for a new project, after research and testing, I stick to 3.x, since it behaves much nicer (in my eyes) with very useful theming modules like Delta. As mentioned, it is a matter of requirements and personal view.

I propose you should take a look at the comparison done in the linked page.
> 1 votes

# Answer
Both are created for Drupal 7, and both are responsive.

Due to an "disagreement" about policy and future direction within in the Omega development community, the project has - in effect - been split in two (Omega 3.x and Omega 4.x). These two branches are maintained by two completely separate groups of maintainers, and should be regarded as two different projects.

* Omega 4.x is a base theme framework aimed at themers who want to gain full control over the theme through code, rather than a user interface.
* Omega 3 is best suited to those who like to build their themes through the user interface.

**Omega 3** is the original version and has about 55 000 installs for Drupal 7. It is stable and mature. It works well, but do not expect much new development.

**Omega 4** is a recent development. It only has about 6 000 installs for Drupal 7. It is currently much more "dynamically" maintained than Omega 3.

Both are solid platforms. Which one to use depends on whether you like to do your tweaks and adjustments through a GUI (**Omega 3**), or interact with the code of templates and CSS or SASS (**Omega 4**).
> 1 votes

# Answer
At the time I am writing this, there are 3 branches for Drupal 7:

* 7.x-3, with a 7.x-3.1 version used from 47538 sites
* 7.x-4 with a 7.x-4.4 version used from 13144 sites
* 7.x-5 with a 7.x-5.0-alpha1 version used from 3134 sites

Despite the 7.x-4.4 version being suggested by the project maintainers, that is not the most used version, even though it was released on July 21, 2015 (3 years after the 7.x-3.1 version, released on February 19, 2012). The 7.x-5 branch will not have an official release (which means a version that is not alpha, beta, or a release candidate) before the 8.x-5 branch (whose development snapshot was last update on October 16, 2016).

So, after two years, the choose is still between branch 7.x-4 and 7.x-3, for which the most important difference is (IMO), the presence of a user interface to tweak the theme in the branch 7.x-3. If you are comfortable with editing the code of templates, CSS, and SASS files, then you can consider using branch 7.x-4, which was also updated more recently than the other branch.

If then you would be interested in updating to Drupal 8, you could consider the 7.x-5 branch, even though the 7.x-5.0-alpha1 version was released on October, 2014; it seems rather behind the 8.x-5.0-alpha7 version which was released on July 25, 2016 (almost two years later).
IMO, at this point, it is still too early for thinking about using the Drupal 8 version of the theme.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How get views advanced dynamic URL contextual filter to work with full taxonomy path?
I've tried all settings, with joint paths etc...but I just can't get the filter working properly, I know it's a settings thing, watched a whole bunch of videos but can't put my finger on it!

This is for advanced contextual filter, the dynamic one that can change depending on URL, not the static one.

Like this:

```
Animals
-Pets
-Farm

```

Path is:

```
localhost/animals/pets/cats.htm
localhost/animals/farm/cows.htm

```

I would like the filter ***animals/pets*** to show cats.htm content

I would like the filter ***animals/farm*** to show cow.htm content

I can get the filter working with single taxonomies, but not with full path.

**animals** works, but not **animals/farm** and not **animals/pets**

Attaching an image with the screen where I should set this up

# Answer
> 4 votes
You must use 2 contextual filters

First one is: Contextual filter: Content: Has taxonomy term ID depth modifier

Second one is: Contextual filter: Content: Has taxonomy term ID depth modifier with the same criteria you did.

I put the view path to be the vocabulary name and tested contextual filters like:

```
//Hierarichay
      tag1
        tag2
        tag2

//Urls
    tag1/tag2
    tag1/tag3

```

The views gets results for the child tags every time {2, 3}. If you didn't use the first filter it will consider the parent as argument.

Hope it solve your problem.

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


# Question
Title: Why does Drupal still convert links using a non-existant url alias pattern
First I created an alias for an entity type like this:

```
project/[project_type]/[id]

```

which worked fine. After a while I decided to delete all aliases and created a new pattern, and bulk generated all aliases.

```
[project_type]/[id]

```

However, drupal still converts menu links (with internal path) as well as links in views (linkto content) using the old pattern project/\[project\_type\]/\[id\]

* I have cleared cache of the site,
* I have cleared the views cache,
* I have re-saved all entities, I have checked the alias list, the aliases pattern that drupal uses is not present in the list, the new alias patterns are present.

In some way, drupal still uses this phantom-pattern which is cached somewhere apparently. It refuses to use the new alias pattern for converting links.

The new alias patterns do work for manually created links that correspond with the new pattern. Just the automatic conversion from internal path to alias path does not work, it does use the new alias but an already deleted alias.

# Answer
Home » Administration » Configuration » Search and metadata » URL aliases (settings tab)

```
Update action
 Do nothing. Leave the old alias intact.
 Create a new alias. Leave the existing alias functioning.
 Create a new alias. Delete the old alias.

```
> 0 votes

---
Tags: 7, views, caching, path-aliases
---


# Question
Title: How to update a computed field in a rule's "set data a value" action
I have a custom field called **field\_balance** in the user account form which is a **computed field**. It keeps the actual **number of coins** bought by the **current user**. That value is supposed to change (increase or decrease) if the user makes particular manipulations on my **custom content type** which is called **Ads**.

**How do I increase the field's value?** By setting up the field.

**How do I decrease the value?** I am using **Rules module** to make the field's value decrease. **But it doesn't work well yet**. This is what I have already tried:

* **The Event**: After updating existing content of type Ads
* **The conditions**: User has roles "ad editor"
* **The Action** : Set a data value. **But when I select the field called "site:current-user:field-balance" and hit "Continue", The Data selector turns red and a notification appears**.

Here is the **illustration**:

What is it about the **computed field** that does not continue the rule? Is there any other way to update a computed field with the Rules module?

# Answer
I cannot answer your question directly, so I will propose a solution without computed fields for your specific situation. Since your computed field is just a sum of two other fields, it is perhaps easier to replace it with an ordinary integer field *Balance* and update its value with a simple Rule every time the entity in question changes. In order to allow users to see the field *Balance*, but deny them access to edit it, you can use the Field Permissions module:

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

---
Tags: rules, entities
---


# Question
Title: How do I request core maintainers attention in drupal.org issue queues?
A white ago I have discovered a bug in Drupal. However, in my attempt of fixing it, I ran into a few walls. The main reason probably being that I miss history (e.g. why several decisions have been made).

It there a tag, status, or anything else to signal the core maintainers that I am stuck in resolving the issue?

# Answer
> 0 votes
There is a list of usable tags here : https://www.drupal.org/issue-tags Browse this and the following pages to get an understanding of using tags in the issue queue. You could also mention the bug in irc on freenode #drupal-contribute. You can tweet about it. Or you could post a link to the issue here!?

---
Tags: community-official-site
---