# Question
Title: How to not change value in computed field
I have a field created with Computed Field module, the field generate a unique id with `uniqid()` php function.
It's work fine but when I edit contents, value of the field changes to a new value!

I use this field to create tracking number for user requests. How can I lock the field to not give a new value on edit form?

# Answer
> 1 votes
If you are using `hook_form_alter` then following will help

```
/**
 * Implementation of hook_form_alter().
 */

function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form['#node'] && $form['#node']->type .'_node_form' === $form_id) {
    // Is node form.

    if (empty($form['#node']->nid)) {
      // This is a new node
    }
  }
}

```

# Answer
> 1 votes
In the config of your computed field, in the section: "`Code (PHP) to compute the text value`", add the following code:

```
//We check if the node is new
if ($entity->isNew()) {
$value = uniqid();
}
//else, we get the value of the computed field of the node
else {
 $node= Drupal\node\Entity\Node::load($entity->id());
 $value = $node->field_computed->value;
}

```

***Note***: change the "`field_computed`" for your field machine name.

---
Tags: entities
---


title: Parameters with uppercase letter?

text:
# Question
Title: Parameters with uppercase letter?
Is it possible to handle querystring parameters in webform module in Drupal 8.x with Uppercased letters like in this example? example.com?collectionId=123 (notice uppercase "I")

Webform fields requires machine names (capital letters not allowed). Currently i get forms pre-filled as expected using **collectionid=123** instead of **collectionId=123** but in my current scenario using the capital letter is a requirement in order to keep some legacy external process working untouched.

Any suggestions?

# Answer
You need to write some custom code to lowercase the query string parameters before the webform is built and displayed.

Another hack would be to pass the query string parameter using a token `[current-page:query:collectionId]`
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Limiting input on node title and plain text area fields
Is there a way to add a character limit on node title and plain textarea fields in Drupal 8? I don't want to use the Title module.

# Answer
> 4 votes
There's the beta version of the Maxlength module which can be applied to built-in fields as well custom text fields. The Maxlength module allows you to set maximum length of any field; one option includes showing a javascript character countdown on the edit forms next to the applicable fields.

You could also take the js library this module is based off of and apply with the `hook_form_alter` approach.

---
Tags: 8
---


# Question
Title: Creating a bootstrap sub-theme with the SASS starter kit
I am attempting to create a bootstrap sub-theme using the SASS starter kit in the the bootstrap base theme. I'm using bootstrap version 7-3.16.

I followed the directions here: How to create bootstrap subtheme using sass? as best as I could.

I copied the SASS starter kit into a new directory in the sites/all/themes directory and named it "bootsub". Then I changed the sass.starterkit file to "bootsub.info" and edited the file to reflect the name "bootsub".

Then I copied the bootstrap framework files into a file in the subtheme named "bootstrap". I had previously installed compass and sass.

I then ran the command "compass init" from the command line (in the subtheme root directory). This created the config.rb file. I then ran the command "compass compile" in the subtheme root directory.

I am still not able to see any styling on the site. I have flushed the cache and I have double checked to make sure that the subtheme is enabled and set as default and the bootstrap base theme is enabled.

I am including an images of the directory structure and a copy of the config.rb file

```
require 'compass/import-once/activate'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/sites/all/themes/bootsub"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"

# You can select your preferred output style here (can be overridden
via the command line):
# output_style = :expanded or :nested or :compact or :compressed

# To enable relative paths to assets via compass helper functions.
Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of
your selectors. Uncomment:
# line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv
scss sass

```

# Answer
Try using Radix Theme. Check how the compiler gulp is setup and try to replicate it to bootstrap sass.
> -1 votes

---
Tags: 7, theming
---


# Question
Title: Random page rendering error: A stray renderRoot() invocation is causing bubbling of attached assets to break
I have a D8 site that's in development and I am getting this error thrown at random on pages which most of the time render quite happily. There doesn't seem to be any real pattern in it.

I can see that it looks like it's designed to prevent the renderer creating an infinite loop (the code is on line 133 of core/lib/Drupal/Core/Render/Renderer.php), but it isn't really clear what's actually causing it. The log error is pretty useless really.

Anyone seen this and found out the cause? Thanks

# Answer
> 9 votes
The error is caused by Renderer::renderRoot() in a wrong place, see the docs:

> Renders final HTML given a structured array tree.
>
> Calls ::render() in such a way that placeholders are replaced.
>
> Should therefore only be used in occasions where the final rendering is happening, just before sending a Response:
>
> * system internals that are responsible for rendering the final HTML
> * render arrays for non-HTML responses, such as feeds
>
> (Cannot be executed within another render context.)

Look for `renderRoot()` in custom code. Check if you need to render at all (most times you need not) and don't render too early, only in theming when there is a render context collecting the bubbled up metadata. Then replace it with Renderer::render().

The random behavior is probably because of caching.

---
Tags: 8, theming
---


# Question
Title: Element called "Likert" - Result showing wrong data
I'm building a survey using the Webforms module. And, I was trying to use the Element called "Likert". I had some problems displaying the value of the field. After submitting a simple form, I get a value word "Strongly Disagree" rather than the value "1".

https://ibb.co/jE9ZFG

https://ibb.co/jqhzhw

Any advise,

# Answer
Likerts and all options based elements show the label/text and not the submitted value by default. You can display the 'raw' value by changing the element's 'Submission Display' under the 'Advanced' tab in the element's edit dialog.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to use views to filter specific workflow state in current month
I have a system that is heavily workflow dependant. I have a content type called 'Profile' with 3 states :

1. Lead
2. Prospect
3. Customer

I would like to know how to create a views contextual filter of all Profiles that changed to the Customer state in a given month i.e. which Profiles Customer this month. D6 Views 2.x has this option but I cannot find it in D7 Views 3.x

Thanks

# Answer
> 0 votes
You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

> ... allows to format date fields using SQL.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.
>
> The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts module.

---
Tags: views, workflows
---


title: View filter, relative date

text:
# Question
Title: View filter, relative date
Is there any way to achieve relative date in Views FILTER CRITERIA?

I need a date between 'first day of' and 'last day of'.

Views Contextual Range Filter Module does not work on Drupal 8.4.x.

# Answer
The standard date Views filters in Drupal 8 have two options:

* A date in any machine readable format. CCYY-MM-DD HH:MM:SS is preferred.
* An offset from the current time such as "+1 day" or "-2 hours -30 minutes"

The first is an absolute date. The second is a relative date string (I don't know why this is called an offset date).

So, add a filter, choose 'offset' as an option, and then enter your relative date. These work for simple comparisons, and between/not between.

At runtime, the value you entered will be parsed by `strtotime()`; any date-like string that it will accept can be used. This means that it will be dynamic and always be relative to when the view is executed and not when the view was created. php|architect’s Guide to Date and Time Programming has a nice appendix in it about what are parsable values (and some of the quirks).

Keep in mind that you may need to adjust the cache rules for the view to prevent stale data from being displayed. Also, there is a bug1 regarding time zone handling that has not been committed to core yet, which may result in some weirdness.

1 Barring unforeseen problems, this will be fixed in Drupal 8.5.0.
> 2 votes

---
Tags: 8, views, datetime
---


# Question
Title: What's wrong with this simple debugging code?
Spend whole day trying to make working simple debugging code for Tweme theme (using D8).

```
function tweme_preprocess_node(&$variables) {
   $node = $variables['elements']['#node'];
   kint($node);
   kim ($variables);
}

```

The only response is blank page no other info.

What's wrong with my debugging code?

# Answer
> 1 votes
The `kint()` and `ksm()` functions output the results in the status messages block.

Make sure in */admin/structure/block* the **Status messages** system block is set to a region.

---
Tags: debugging
---


# Question
Title: Wrong number of Cart items in Foundation theme topbar
I use AuthCache and Drupal Commerce in my Drupal 7 site. I am currently building a new Foundation subtheme for the site with the Foundation topbar activated for mobile only.

Now, to show the number of items in the cart I simply replace the default cart block content with this in my template.php:

```
function mynewtheme_block_view_alter(&$data, $block) {
  global $user;
  if ($block->module == 'commerce_cart') {
    if ($order = commerce_cart_order_load($user->uid)) {
      // Count the number of product line items on the order.
      $wrapper = entity_metadata_wrapper('commerce_order', $order);
      $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      if($quantity){
        $data['content'] = ('<a class="varukorg" href="/cart"><i class="fi-shopping-cart"></i>('.$quantity.')</a>');
      }else{
        $data['content'] = ('<span class="varukorg cart-empty-block"><i class="fi-shopping-cart"></i> (0)</span>');
      }
    }else{
      $data['content'] = ('<span class="varukorg cart-empty-block"><i class="fi-shopping-cart"></i> (0)</span>');
    }
  }
}

```

The above shows a basket with the number of items in the cart.

Then, to show the number of items also in the Foundation topbar on mobile devices or narrow windows I use this code in a `preprocess_page` hook in template.php:

```
  $cartblock = block_render('commerce_cart', 'cart');
  $vars['varukorgen'] = $cartblock;

```

Followed by this line in page.tpl.php:

```
<?php print render($varukorgen); ?>

```

Now to my problem... the number of items shown by the variable `$varukorgen` in page.tpl.php is incorrect on smaller window sizes when the topbar is toggled. It think that is shows a cached version of the number.

In the AuthCache settings in the block in question i have set "Never" for the Cache lifetime, Per user and I also enabled Ajax.

So why is the number not showing correctly when it is rendered by means of a custom variable in page.tpl.php?

EDITED: the solution was as suggested below to create a new region in the .info file, place the cart block in that region in the UI and then render that region inside the topbar region in page.tpl.php like this:

```
    <?php if ($page['topplist']): ?>
      <div id="topplist" class="basket">
        <?php print render($page['topplist']); ?>
      </div> <!-- /#topplist -->
    <?php endif; ?>

```

Now the the number of items in the cart is updated as it should on every page by the means of Ajax (enabled in the cart block).

# Answer
You don't want to put this code directly into your tpl, as it will indeed cache. What you want to do is create a region in your template and then add your cart block to that region in the UI. You will also have to set that block to load via ajax or ESI so that it works properly with Authcache. You will see those settings if you go to configure the block.

Ideally you don't ever want to include any code that "does stuff" in your tpl files, as it can get cached. This is more obvious in Drupal 8 thanks to twig making this harder, but it is very easy to do incorrectly in Drupal 7.

You can be even more efficient if you change your code to save the cart quantity as a session variable or cookie and only calculate it when the cart changes, thus saving you from performance heavy order loads on every page. This is outside of the scope of your initial question though, but I thought I would mention it.
> 2 votes

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


# Question
Title: Remove paper size options on node add forms
Node add forms show some paper size options no matter who the user is, even regular authenticated users. It seems to be part of the Printer, email and PDF versions module.

I added the following code to my helper (let's call it `my_helper`) module, as suggested here:

```
/**
 * Implements hook_form_alter().
 */
function my_helper_form_alter(&$form, &$form_state, $form_id) {
  // Hiding the print fields that print.module puts into the node form.
  if (strpos($form_id, '_node_form') !== FALSE && !empty($form['print']['print_pdf'])) {
    foreach ($form['print']['print_pdf'] as &$print_field) {
      $print_field['#access'] = FALSE;
    }
  }
}

```

I am also using the Simplify module to hide certain form elements but this isn't coming up as an option there.

Edit: I looked at the system table in MySQL to see that the weight of the module was 0, so I added a .install file to change the weight to 10. But still not seeing an affect.

```
   function my_helper_update_7100() {
        db_update('system')
        ->fields(array('weight' => 10))
        ->condition('name', 'my_helper', '=')
        ->execute();
    }

```

# Answer
> 0 votes
Cross-posting my answer from drupal.org as these two pages are the first results in google. https://www.drupal.org/project/print/issues/2714635

> I just fixed this on my works web site. The form alter code needs to be added in an #after\_build callback as the paper size and orientation fields don't exist yet in the form array in using hook\_form\_alter. Here is a complete example.

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {

  // Hiding the print fields that print.module puts into the node form.
  if (strpos($form_id, '_node_form') !== FALSE) {
    $form['#after_build'][] = 'mhfa_pdf_form_alter_after_build_remove_print';
  }
}

/**
 * Remove pdf print controls.
 */
function my_module_form_alter_after_build_remove_print($form, &$form_state) {
  unset($form['print']);
  return $form;
}

```

---
Tags: 7, files
---


title: Drupal 8 allow only listed languages

text:
# Question
Title: Drupal 8 allow only listed languages
Is there a way on Drupal 8 to remove "Not specified" and "Not applicable" languages from list and to display only listed Languages?

# Answer
> 6 votes
Go to Manage form display of a content type and click on settings cog on right corner of Language field. There you will see a checkbox **Include locked languages such as Not specified and Not applicable** uncheck it to remove options like *Not specified* and *Not applicable*.

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


title: How to add view to view mode?

text:
# Question
Title: How to add view to view mode?
We have a view, custom\_view, that was created to be displayed on a page that is of the basic page content type. The basic page content type is using the Default View mode and has a taxonomy term, custom\_tag.

Initially we thought about adding the block to the theme block layout, but that does not provide what we need. The custom\_view should only be visible on the basic page content type for the Default View and not others.

How do you add Views to a View Mode?

The view has a contextual filter so it takes in the current language and it takes in the value of the custom\_tag since it is present on the basic page content type.

# Answer
> 1 votes
## How do you add Views to a View Mode?

If you want to add a view to a content type's view mode there is a few ways to do this and depending on your exact requirement one might be better than the others

### views field formatter

Use https://www.drupal.org/project/views\_field\_formatter will allow you to choose a formatter for a field and it will pass automatically the value of the field to the view

### viewfield

https://www.drupal.org/project/viewfield will allow you to add a field and to choose what views can be chosen and allows you to also include an argument on the node edit form

### EVA: Entity Views Attachment

https://www.drupal.org/project/eva will allow you to create a specific EVA views display and configure it to appear for specific bundles (content types). After saving the view it will appear as a field in the display mode of that content types so it can be positioned appropriatelly

All the above module can take advantage of arguments and contextual filters so you can do very complex things with them

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


# Question
Title: How to only display languages in language switcher block where a translation exists?
I need to enable thousands of languages on my Drupal 7 site, but I do not want to incur the rendering overhead of creating the language switcher sidebar for every language. The default behavior for the language switcher block is to show languages which do not have translations in gray font and struck out.

How would I modify the language switcher block to only show active links, i.e. only display the languages for which a translation exists? I looked at this code from this post but need help adjusting it for my needs:

```
<?php
  function YOURTHEMENAME_links__locale_block($variables) {
  foreach($variables[links] as $key => $lang) {
    if (isset($lang['attributes']['class']) && in_array('locale-untranslated', $lang['attributes']['class'])) {
      $variables['links'][$key]['href'] = '<front>'; // Set here any page link...
    }
  }
  return theme_links($variables);
}

```

What should the code be, and where do I put the code in my theme?

# Answer
> 0 votes
To adapt the solution you tried, you would just have to unset entries for languages where no translation exists, so no link will be printed for them in the `theme_links()` call. So:

```
function YOURTHEMENAME_links__locale_block($variables) {

  foreach($variables['links'] as $key => $lang) {
    if (isset($lang['attributes']['class'])) {
        if (in_array('locale-untranslated', $lang['attributes']['class'])) {
            unset($variables['links'][$key]);
        }
    }
  }
  return theme_links($variables);
}

```

You would put this code into the `template.php` file of your theme, adapting the `YOURTHEMENAME` part of the function name above according to how all the other functions in your theme start. Means, you always start the function name of all your theme functions with the so-called "machine name" of your theme.

# Answer
> 0 votes
There is also a different way to determine missing translations. Namely, instead of looking for a `locale-untranslated` CSS class for the link, you can check if the link is the same as the one for the *current* language. Because that is the Drupal Core default behaviour for the language switcher in case a translation is missing. So:

```
function YOURTHEMENAME_links__locale_block($variables) {
    global $language;

    if (isset($data[$language->language])) {
        $current_href = $variables[links][$language->language]['href'];
    }
    else {
        $current_href = false;
    }

    foreach ($variables[links] as $key => $lang) {
        // If we find a missing translation, remove its entry from the list.
        if ($lang['href'] == $current_href) {
            unset($variables[links][$key]);
        }
    }

    return theme_links($variables);
}

```

Again, this function would go into your theme's `template.php`.

# Answer
> 0 votes
This would more likely work:

```
   $current_href = \Drupal::languageManager()->getCurrentLanguage()->getId();

    foreach (array_keys($variables["links"]) as $key) {
    // If we find a missing translation, remove its entry from the list.
    if ($key == $current_href) {
      unset($variables["links"][$key]);
    }
  }

```

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


# Question
Title: how to add to html.twig from a node twig file?
I need to add the article image to the post shared on facebook and twitter, this is done by meta tags added in the as shown below

```
<head>
  <head-placeholder token="{{ placeholder_token|raw }}">
  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token|raw }}">
  <js-placeholder token="{{ placeholder_token|raw }}">

  {# RIGHT HERE  #}
  <meta name='og:image' content='{{ file_url(element['#object'].field_image.0.entity.uri.value) }}'>
  <meta name="twitter:card" content="photo" />
  <meta name="twitter:site" content="@nestle" />
  <meta name="twitter:title" content="Article Picture" />
  <meta name="twitter:description" content="A description" />
  <meta name="twitter:image" content="{{ file_url(element['#object'].field_image.0.entity.uri.value) }}" />
  <meta name="twitter:url" content="{{ base_path }}" />
</head>

```

I need to add meta tags in the in the html.html.twig file, the problem is those meta tags depend on the article being shared because I need to get the URL of the image, I cannot figure out how to do it such that a block of code written in the node.html.twig file would be placed in the in the html.html.twig file.

**WHAT I TRIED** i tried adding a block in start of node file and extending the html.html file node--article.html.twig (start of file) :

```
{% extends "html.html.twig" %}
{% block metablock %}
  <meta name='og:image' content='{{ file_url(element['#object'].field_image.0.entity.uri.value) }}'>
  <meta name="twitter:card" content="photo" />
  <meta name="twitter:site" content="@nestle" />
  <meta name="twitter:title" content="Article Picture" />
  <meta name="twitter:description" content="A description" />
  <meta name="twitter:image" content="{{ file_url(element['#object'].field_image.0.entity.uri.value) }}" />
  <meta name="twitter:url" content="{{ base_path }}" />
{% endblock %}

```

then calling this block from the html.html file like this:

```
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">

    {# RIGHT HERE #}
    {{ block('metablock') }}
  </head>

```

But this gives an error

> The website encountered an unexpected error. Please try again later.Twig\_Error\_Syntax: A template that extends another one cannot include contents outside Twig blocks.

I tried putting the rest of code in node--article inside a block, this does work but the metablock block gets placed in the start of every article viewport (Not what I intended) I need it to be placed only in the head tag.

Hope I was clear enough, to summarize, How can I place meta tags in the head from the node--article.html file, not the html.html file.

# Answer
> 2 votes
You're going about it the wrong way, you cannot affect other Twig template files, it needs to be done way before you get to Twig. Everything you want to can be done using the Metatag module:

Supports a large number of commonly used meta tags, including the page title, canonical URL, description, etc, and for Facebook's Open Graph, Twitter Cards and Dublin Core via included submodules (see full list)

---
Tags: 8, theming, social-network
---


title: Redis and Internal Page Cache?

text:
# Question
Title: Redis and Internal Page Cache?
I just set up Redis on a site that has been having some performance problems, and it seems to be running well so far. Does anybody know if it would be recommended to also run the Internal Page Cache and/or Internal Dynamic Page Cache module(s) in addition to Redis, or is this redundant? There isn't much documentation around yet regarding Redis and D8.

# Answer
> 2 votes
The Drupal modules decide *what* to cache (and for how long etc), Redis is just *where* the cached data is stored.

Having both/all enabled is not inherently redundant (though as 4k4 noted in the comments, there's a theoretical chance that one cache will improve speed so much that it renders the other redundant in terms of further speed improvements).

Enabling the lot will probably be common practice, and if not with Redis as the storage backend then Memcache, etc.

# Answer
> 0 votes
As said before Redis is just a "bin" where to store cache, it should be faster than the database bin (default Drupal cache bin).

* Dynamic Page Cache module should always be enabled or you get crappy performances.
* Internal Page Cache module could be disabled if you have already a cache server in front of your Drupal (for example, Varnish), this module cache whole pages for anonymous users only.

These two modules are enable by default on Drupal 8; it is safe to enable them.

---
Tags: caching
---


# Question
Title: 'Text format field is required' error when saving Better Exposed filters (BEF)
For one of the views exposed filters I'm using BEF but when I'm trying to save one of the filters as checkboxes/radio buttons it give me below error. I've no clue to what I'm doing wrong.

Any help would be much appreciated.

# Answer
I found the problem.

Navigate to the BEF settings under the view in question (like the screenshot above).

Scroll down to **Require input before results are shown**, select the checkbox, there should be a "Text on demand" field.

Set the Text format field to one a valid text format.

Then apply the changes.

I created a video tutorial for you to follow: http://recordit.co/V75Zl4gAAl
> 2 votes

---
Tags: entities, views
---


# Question
Title: How to transform the CSV link in the Views Data Export module in a non-image link display?
I'm using the Views data export module for my search interface so users can click a link to download the search results. It's working and displaying. But it's not pretty.

*My Data Export has the following settings:*

* **Format**: CSV file
* **Filter criteria**: published, type=resource, topic \> (exposed), category (exposed), search terms (optional)
* **Data export \> settings \> path**: /search-export Attach to: search footer: global: text \> area (what I've been trying to add the manual link to)
* **pager**: display \> a specified number of items \> 0 items (required to make the CSV export \> not return all results be default)

Right now there's a button at the bottom of the page that the module creates in the format of a tiny bright orange button with white text that says 'CSV'. I think it's an ugly button. A user may not even know what it means. Here's the code via inspect element:

```
<div class="feed-icon">

    <a href="/search-export?attach=page">
        <img title="Download Results" alt="Download Results"
src="http://staging.grantstation-pathfinder.com/sites/all/modules
/views_data_export/images/csv.png" typeof="foaf:Image"></img>
    </a>

</div>

```

If the user set exposed filters or set a keyword in the search box when clicked this link adds parameters to the URL (ie. /search-export?field\_topics\_value=All&etc).

I don't know how it's adding those parameters which is probably the crux of my problem.

I could just swap out my own image I guess...but...

I'd rather change this to not use an image whatsoever and instead have it just be a link that says 'download results' or some such thing.

I tried just adding a link manually to the header or footer in the search view that has the same link as the image but it doesn't capture the parameters the way the button does for some reason.

The link I tried adding:

```
<div class="feed-icon">
  <a href="/search-export?attach=page">
    Download Spreadsheet
  </a>
</div>

```

When clicked the above doesn't include the parameters in the URL like the image does, it just exports ALL the results (and ignores whichever filters are set).

My question: How to fix my new download spreadsheet link so it outputs the results only with the exposed filters and keywords as the view itself does (and as the CSV button does)?

# Answer
> 3 votes
I agree that this CSV button needs some refinements, similar to what you are describing in your question. And quite a few others seem to think likewise.

To actually solve your issue, consider looking at the module's issue # 2261167, which is about an Option for non-image link display (issue status = needs review). Comment # 26 of that issue contains a patch which adds 2 new settings as shown in this screenprint:

Here are some more details about these 2 new settings:

* a checkbox to (if selected) provide the download link as a text link instead of an icon/image link.
* a textfield to add a class to the link, so that you can give the link a class like "button" (see picture) to your text link

Do I'd definitely consider this patch.

As an alternative (2nd choice?), you may also want to look at issue # 1379672, which is about Export Button, make it styleable with CSS. It also includes a patch that you may want to consider (eg if the previous one for some reason doesn't fit).

# Answer
> 2 votes
I'm posting this as a workaround for anyone that is looking to theme the button. I was looking for a way to theme the button and used the solution offered in 12 just without the jQuery, using only CSS with FontAwesome.

The result looks like this:

I added another class to the div surrounding the export link called "export-button" (from 12)

```
<?php if ($exposed): ?>
<div class="view-filters">
<?php if(isset($view->feed_icon)): ?>
<div class="feed-icon-wrapper export-button">
<?php print $view->feed_icon; ?>
</div>
<?php endif; ?>
<?php print $exposed; ?>
</div>
<?php endif; ?>

```

In my CSS I used the following:

```
.export-button a {
padding: 15px 35px 15px 35px;
display: -webkit-inline-box;
background: #2295f3;
color: white;
text-align: center;
}
.export-button a:hover {
box-shadow: 0 2px 6px rgba(0,0,0,.3);
}
.export-button img {
display:none;
}
.export-button a:before {
content: "Download CSV";
color:white;
}
.export-button a:after {
content: "\f019";
display: inline-block;
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-size: 15px;
color: white;
margin-left: 8px;
}

```

Please note, to use font awesome in the CSS you need to declare it in your CSS file.

```
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.0.3');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3')
format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?
v=4.0.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?
v=4.0.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?
v=4.0.3#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}

```

I hope this helps.

---
Tags: 7, views, importing-exporting
---


# Question
Title: What is the difference between $variables['elements']['#node'] and $variables['node']?
Just wonder what is the difference between `$variables['elements']['#node']` and `$variables['node']` in `hook_preprocess_node()`. Are the same instance of the same node?

# Answer
> 2 votes
See the code executed in `template_preprocess_node()`, the function called before the preprocess functions implemented by modules for a node.

```
$variables['node'] = $variables['elements']['#node'];

```

So, yes, `$variables['node']` and `$variables['elements']['#node']` contain the same value.

---
Tags: theming
---


# Question
Title: How can I list Drupal 8 Content Moderation draft
I'm able to write a "draft" as an admin so it's visible as unpublished content on the content list.

The problem is that I can not make list visible to other "editors" (Who even can access the node as "draft" and even edit it and store again).

In short words admin only is able to view all contents including drafts, other user see only published contents.

How can I make people able to browse full content list, including the drafted nodes?

# Answer
Out of the box, on Drupal, only users with the *Bypass content access control* permission can see every unpublished post, but that is a permission to give to a very small set of users, such as administrator users.
The other users can only see the unpublished nodes they created.

You can create a module that defines a new permission (e.g. *View unpublished content*), and implement `hook_node_access_records_alter()`/`hook_node_grants_alter()` to grant the view access to those users with the new permission.
> 0 votes

---
Tags: 8
---


title: Redirect after user pass form submit

text:
# Question
Title: Redirect after user pass form submit
I'm trying to do a redirect after hitting the submit button in a Drupal 8 reset password form.

I use the `theme_form_alter` hook and a function as a new submit actions. The problem is, that the redirect works but no email is send. If I uncomment the line for the new submit hook the mail is send but of course there is no redirect.

```
function theme_form_alter(&$form, &$form_state, $form_id) {
  if($form['#form_id'] == 'user_pass') {
    $form['actions']['submit']['#submit'][] = 'user_pass_redirect';
  }
}

function user_pass_redirect(&$form, $form_state) {
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', [
    'node' => '87',
  ]);

 $form_state->setRedirectUrl($url);
}

```

I'm doing exactly the same thing for the `contact_message_personal_form` form and it works.

So, I have no idea why that happens for the `contact_message_personal_form` and the `user_pass` has isn't working.

Thanks for your help

# Answer
> 1 votes
I found a solution. I compared the output from a dump of user\_pass $form and contact\_message\_personal\_form $form variable.
My problem was, that my `$form['actions']['submit']['#submit']` array was empty. So I added the missing '`::submitForm`' parameter and everything works.

```
function module_form_alter(&$form, $form_state, $form_id) {
  if($form['#form_id'] == 'user_pass') {
    $form['actions']['submit']['#submit'][] = '::submitForm';
    $form['actions']['submit']['#submit'][] = 'user_pass_redirect';
  }
}

function user_pass_redirect(&$form, $form_state) {
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', [
    'node' => '87',
  ]);
  $form_state->setRedirectUrl($url);
}

```

I have no idea why my variable was empty but this works for me.

---
Tags: 8
---


# Question
Title: How to get user id of order from order entity metadata wrapper
I am implementing `hook_commerce_cart_line_item_refresh()`. It will be receiving line item and entity metadata wrapper for the commerce order.

How can I get user id of order from its metadata wrapper without loading user object like this

```
$uid = $order_wrapper->owner->value()->uid

```

With above line it will be loading user object. I would like to avoid loading user object and simply take uid directly.

Following line does not work:

```
$uid = $order_wrapper->uid;

```

Or should I think of loading order object? As it might be already in static cache.

Thanks

# Answer
It's the same as any property on a metadata wrapper:

```
$uid = $order_wrapper->uid->value();

```

> Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with

```
$order = $order_wrapper->value();

```
> 8 votes

# Answer
You need to get `uid` from the entity object.

```
$uid = $order_wrapper->value()->uid;

```
> 2 votes

# Answer
For a multi-valued entity reference field you can get the raw values using this pattern

```
$wrapper->field_multiple->raw()

```

This would return an array like this:

```
array(0 => 123, 1 => 456)

```
> 0 votes

# Answer
Correct answer is:

$uid = $order\_wrapper-\>author-\>uid-\>value();
> -1 votes

---
Tags: 7, commerce, entities
---


# Question
Title: How to modify the image output for just one content type using Responsive Images?
There is a field\_image (image) field on the basic content type. Using the Responsive Image, we enabled it on the Default view mode for the field\_image field using a Responsive Image style.

The reason why we are setting the Image url as the data-src attribute is because we are using Lazysizes javascript library to lazyload the images. The Responsive Image module outputs using source srcset as separate tags from the img tag.

In my testing, I have found that although the browser fetches whatever size it needs to based on the Responsive Image style configuration, it does not change the image url.

How would we control the output of the image so that we can get the image to display similar to below?

Goal:

1. Lazy load images even while using Responsive Image Module
2. Output the image field so that the data-src is set, src is not set, and the "lazyload" class is added

Current situation:

```
<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">
<img src="/original-image" alt="alt_text" >
</picture>

```

Desired Output:

```
<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">
<img src="/original-image" alt="alt_text" class="lazyload">
</picture>

```

# Answer
The responsive image module creates these with a twig template called: `responsive-image.html.twig`.

You have two options to change the output. You can either copy this template from it's location under `core/modules/responsive_image/templates` to your theme.

Or you can use the `hook_preprocess_responsive_image()` in a module or your `my_theme.theme` file.

Basically, you will need to change the values in the `source_attributes` object. E.g. grab the value of the `src` attributes, delete it, and add your `srcset` attribute with the value of the `src` attribute.
> 1 votes

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


title: Problems with aggregated CSS

text:
# Question
Title: Problems with aggregated CSS
I activated aggregate CSS on my local development and on a remote testing environment without any problems. Now on staging the aggregation of CSS files causes trouble: on some pages the styling looks correct but on random pages it is completely broken. The HTML sometimes shows:

```
<link rel="stylesheet" href="/?p0upgh" media="all" />
<link rel="stylesheet" href="/?p0upgh" media="all" />
<link rel="stylesheet" href="/?p0upgh" media="print" />

```

Sometimes some of the aggregated files seems not to be inserted via HTML meaning: there are no Tags or just one - some of the stylesheets are missing.

I checked folder permissions: sites/default/files and sites/default/files/css have 777 as chmod values. The owner and the group of the folders and files belong to the correct folder and CSS are aggregated in sites/default/files/css.

Does anyone has some hint for me what my cause this problem?

# Answer
> 0 votes
The issue was connected to this: https://www.drupal.org/project/paragraphs/issues/2914259

I am not quite sure what exactly was the problem but when I went to the status report page I realized the error message

```
Entity/field definitions
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Paragraph

- The Published field needs to be updated.

```

I implemented the update function

```
_update_function() {
  try {
    $entityUpdateManager = \Drupal::service('entity.definition_update_manager');
    $entityUpdateManager->applyUpdates();
  }
  catch (EntityStorageException $e) {
    print_r($e);
  }
}

```

run update and the problems with the aggregated css disappeared.

---
Tags: 8, css-js-aggregation
---


title: Webform submitForm hook

text:
# Question
Title: Webform submitForm hook
I am using drupal 8 and webform `8.x-5.0-beta25`. I have a multistep form with ajax enabled, 5 pages.

I need to alter the confirmation message but I haven't been able to figure it out. What I want to achieve is change the message depending on some form values the selected on the last question. I've created a custom module and extended the `WebformHandlerBase` and created a `confirmForm` function but I am not seeing anything once the form is submitted.

Again, it is submitting through ajax so I am not sure if that has anything to do with it.

Here is what I have tried so far

`/modules/custom/cbed_ux/src/Plugin/WebformHandler/QuizWebformHandler.php`

```
<?php
namespace Drupal\cbed_ux\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\WebformInterface;
/**
 * Form confirm handler.
 *
 * @WebformHandler(
 * id = "quiz_handler",
 * label = @Translation("Quiz Handler"),
 * category = @Translation("Quiz Handler"),
 * description = @Translation("Quiz Webform handler."),
 * cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 * results = \Drupal\webform\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class QuizWebformHandler extends WebformHandlerBase {
  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    kint($webform_submission);
    drupal_set_message ('submitted!!');
  }
}

```

The form submits, but I do not see my kint or set message

# Answer
Did you attach your WebformHandler to your webform via /admin/structure/webform/manage/WEBFORM\_ID/handlers?

Your `QuizWebformHandler::submitForm` method does not match the `WebformHandlerInterface::submitForm` definition and should be throwing a fatal exception.
> 4 votes

---
Tags: 8, webforms
---


title: How to call a CSV resource

text:
# Question
Title: How to call a CSV resource
I have a decoupled Drupal website and I want to call a REST resource outputing CSV, using the CSV Serialization module. I have also configured REST UI to accept CSV in that particular resource.

I tried sending headers with `Content-Type: application/csv`, or `Content-Type: text/csv`, I'm sending `_format=csv` as a GET parameter, but the only response I'm getting is:

```
   "No route found that matches ""Content-Type: application/csv"""

```

What am I doing wrong?

# Answer
I've found out I also have to send the Accept header:

```
Accept: text/csv

```

I'm also sending some parameters on POST and PUT, in JSON format (the resource also accepts JSON for input), so I also send:

```
Content-Type: application/json

```

and, on the query string, as mentioned, \_format=csv
> 0 votes

---
Tags: 8
---


# Question
Title: "Output this field as a custom link" set here link to the content
How to set in "Output this field as a custom link" a link to the content.

In drupal 7 it looks like this:

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

Tried this, but this doesn't work:

Replacement patterns in `image` field:

And in `link to content` field:

# Answer
Found a solution:

1. Add a `Link to Content` field, outer fields hide from display and remove links.

2. then setup `Link to Content` like this:

`Link to Content` haven't **link path** input - it always link to content. This what I needed!
> 2 votes

---
Tags: views, 8
---


# Question
Title: Output all instances of a repeating field together
I have Paragraphs installed and am creating a content-type which has nested Paragraphs - so there is a Paragraph with a Title Field, a Body Field - this is then nested in a another Paragraph, so that I can have several boxes across the page. So far so good - what I want to learn is to output the fields so I can put them in jQuery UI tabs.

In my template I currently have:

```
{{ content.field_tab_title }}
{{ content.field_body }}

```

Which outputs: *Title Body Title Body Title Body etc.*

What I need is: *Title Title Title Body Body Body*

So that I can put all the titles in li's for jQuery UI. I've tried putting

```
{% for item in items %} {{ content.field_tab_title }} {% endfor %}

```

But then nothing comes out at all.

**UPDATE** Following Kevin's Suggestions, I've started again with my templates and have now got;

in `paragraph--tab.html.twig`:

```
<ul class="tab-box">
{{ content.field_tab_title }}
</ul>
<div>{{ content.field_body }}</div>

```

and in `field--paragraph--tab.html.twig`:

```
{% for item in items %}
  <li class="tab-title">{{ item.content }}</li>
{% endfor %}

```

but this is still outputting:

```
<ul><li>Tab Title - 1</li></ul>
<div>Body Copy 1</div>
<ul><li>Tab Title - 2</li></ul>
<div>Body Copy 2</div>

```

But what I need is:

```
<ul><li>Tab Title - 1</li><li>Tab Title - 2</li></ul>
<div>Body Copy 1</div>
<div>Body Copy 2</div>

```

# Answer
This is going to be tricky, but you will need to think through the rendering layers via twig and work inside out.

Example, if you need all field tab titles in li's, the twig for field tab title (`field--field-tab-title.html.twig`) should look something like this:

```
{% for item for items %}
  <li class="tab-title">{{ item }}</li>
{% endfor %}

```

In your Paragraph field twig, you would put the wrappers as needed, like:

```
<ul class="tabs">
  {{ content.field_tab_title }}
  {{ content.field_tab_body }}
</ul>

```

The same applies to Body:

```
{% for item for items %}
  <li class="tab-body">{{ item }}</li>
{% endfor %}

```

Here is a similar example perhaps you can follow. This isn't tabbed content, but it is accordion based, so it is similar. Still paragraphs.

Main container (`paragraph--component`):

```
<div{{ attributes.addClass(classes) }}>
  {% block content %}
    {{ content }}
  {% endblock %}
</div>

```

Main accordion paragraph twig, extends the main container (`paragraph--component` is a custom twig suggestion I made for easier theming):

```
{% extends 'paragraph--component.html.twig' %}

{% set attributes = attributes.addClass('c-accordion') %}

{% block content %}
  {{ content }}
{% endblock %}

```

The accordion item itself, containing a title and other fields:

```
<section class="c-accordion__item">
  <input type="checkbox" class="c-accordion__trigger visuallyhidden" id="step-{{ paragraph.id() }}" />
  <label for="step-{{ paragraph.id() }}" class="c-accordion__header">
    {% if paragraph.field_accordion_step_title is not empty %}
      <h4 class="c-accordion__step">{{ content.field_accordion_step_title }}</h4>
    {% endif %}
    <h5 class="c-accordion__title">{{ content.field_accordion_title }}</h5>
  </label>
  <div class="c-accordion__body">
    <div class="c-accordion__description">{{ content.field_accordion_body }}</div>
  </div>
</section>

```

When this renders, all X accordion items are rendered the same way into one container. Granted, in my example, the markup container for fields live outside of the field twig and in this twig here, because I chose to have 0 field markup in that project. You can go either way you want.
> 0 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: REST response gets cached for guest user requests
I've implemented kind of a page hit counter as REST request. The article page renders a JS into the page that does a jQuery.getJSON to the REST resource later.

So far that works fine. The page is delivered from cache (X-Drupal-Cache:"HIT") and the browser does an extra request to the REST resource (/api/v1/check/l/1?\_format=json).

Unfortunately the REST handler is not called for guest user views. Instead, Drupal delivers the cached response. It only works for authenticated users.

For guest I get

```
Cache-Control:"must-revalidate, no-cache, private"
X-Drupal-Dynamic-Cache:"UNCACHEABLE"

```

BUT:

```
X-Drupal-Cache:"HIT"

```

And the REST handler is not executed. My REST response is

```
return (new ResourceResponse($rc))->addCacheableDependency(null);

```

Thanks

# Answer
> 4 votes
This is probably the page cache for anonymous users, which works independently from the dynamic cache.

You can disable it with this command:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

You can trigger this anywhere in your code and it will be valid for any response you send for the request. So this should also work for a REST response.

# Answer
> 5 votes
I have a resource post (for anonymous). The above answers Didn't help me.

The following did :

```
$response = new ModifiedResourceResponse($result);
return $response;

```

Read more at ModifiedResourceResponse()

# Answer
> 0 votes
Try add 'addCacheableDependency' to 'ResourceResponse'

```
$response = new ResourceResponse($result);
$response->addCacheableDependency($result);
return $response;

```

Create Rest Resource for GET Method in Drupal 8

---
Tags: caching, 8
---


# Question
Title: How can I order views Attachments in views page
I have created to views attachments and placed them after my views page. But the issue is the order of the attachments is in reverse. How can I add weight to them?

# Answer
Actually Drupal have re-order display, but I think it is for admin page only.

I also got same problems as you, but finally I found a way.

1) Click to ADVANCE.

2) Click to the machine name and edit it by ABC order.

Hope it will help.
> 7 votes

---
Tags: 7, views
---


# Question
Title: Add values to a list (text) field that stores already content
I want to add additional values to a list field, that stores already content.

In the field configuration i get of course:

> There is data for this field in the database. The field settings can no longer be changed.

Is it acceptable to ignore this message, add my values via the textfield without touching the current ones and save the field?

# Answer
Yes, that message is very unfortunate. Ignore it.

Adding options is perfectly fine. Removing unused options is fine too. If you try to remove options that are still used, it will prevent you from doing so.
> 4 votes

# Answer
I ran into a similar situation. In my particular case I wanted to redo a list field completely. My field was on a paragraph entity and I needed to truncate the tables in the database. I used the execute php page that is created when you install the Devel module (/devel/php). From there I ran the following two lines, one at a time.

```
$trunc = db_truncate('paragraph__field_list')->execute();
$trunc2 = db_truncate('paragraph_revision__field_list')->execute();

```

It's worth mentioning I did this on a dev environment first!
> 0 votes

---
Tags: entities, 8
---


# Question
Title: Bulk redirect update from CSV: in code or manually?
I have a D7 question. My latest site change involves using the Path Redirect Import module and `drush path-redirect-import` to bulk-create a bunch of URL redirects from a CSV file. It works fine in *dev* on my Linux box and I need to deploy it to *test* on Pantheon.

I'm striving to do code-based deployments, so I use Features and a `MYSITE.install` module with `hook_update_n()` calls.

1) Is it a best practice or am I misguided in trying to code a `hook_update_n()` to perform the DB update? Code-based development aims for recording every developer-initiated site change in code, right? Or are there cases where you don't commit something to code?

2) If the answer is "yes, you should do this in code", then I see that the `drush_path_redirect_import` function simply processes command-line options and executes:

```
$result = path_redirect_import_read_file($file, $options);

```

so I should simply do the same in my `hook_update_n()`, right?

# Answer
You either use hook\_update\_n as you described. Or, sync down TEST to DEV in pantheon, perform the task there as needed, and then sync the DB/code back to TEST from DEV.

The workflow that works best for you depends on whether your site is accessed alot by users and can have no downtime or disruptions, or if your sites workflow/content is more static.
> 0 votes

---
Tags: deployment
---


# Question
Title: Broken file derivatives when creating an article
I recently installed Drupal 8 to familiarize myself with this platform. I've noticed that, whenever I create an Article, and attempt to upload an image for that article, the styles created from that upload don't work and result in broken links.

The image uploads work just fine. Consider the image below:

In the Article view under Add Content, I have uploaded a small 312 KB file.

* The thumbnail preview (red) does not work here, nor elsewhere, and attempting to visit the link generated for this thumbnail results in a 403 Forbidden result: *mysiteurl.com/sites/default/files/styles/thumbnail/public/2015-12/Untitled.gif?itok=Y40Z0DEa*
* The link to the image uploaded (blue) works just fine. Clicking that link displays the image: *mysiteurl.com/sites/default/files/2015-12/Untitled.gif*
* Last detail: I see that this error extends to the Styles configuration screens as well, where the default image on the left side displays fine whereas the right-hand, style-applied preview is broken (and attempting to display the image in a new browser tab, just like the preview in the Article screen, results in a 403 Forbidden result).

How would I go about resolving this? I don't think it's GD, following the directions outlined in a troubleshooting page on Drupal (I cannot post more than two links, due to reputation) I see in the Configuration area for my site that I have a writable file system, and GD installed - bundled (2.1.0 compatible).

I may be coming from left field here, but might the 'Styles' directory be the culprit? If there's some way I can have this folder get regenerated by Drupal, I wonder if that would resolve these errors.

# Answer
Change the ownership of file folder to www-data:www-data and give permission to 755 in recursive way.
> 3 votes

# Answer
In your settings.php this is effective if permissions don't help:

```
$config['image.settings']['allow_insecure_derivatives'] = TRUE;
$config['image.settings']['suppress_itok_output'] = TRUE;

```

(Also check your log for entries on failing to make directories). There is some aggressive permissions block Drupal puts on derivative images partly because of possible DDOS attack vector. If you don't have many images though it doesn't matter much. The itok output line removes the token strings, which is needed if you call the images in unorthodox ways.
> 0 votes

---
Tags: 8, media
---


# Question
Title: Column not found: 1054 Unknown column 'revision.revision_user' in 'field list': after Update from 8.2 to 8.4
I'm encountering an error when updating from 8.2 to 8.4, in my case it seems to be related to block\_content and maybe also commerce. I've found others with similar issues, but no solid resolution. Has anyone experience this?

Here is the error in the error log:

```
Uncaught PHP Exception Drupal\Core\Database\DatabaseExceptionWrapper:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column
'revision.revision_user' in 'field list': SELECT revision.revision_id
AS revision_id, revision.langcode AS langcode, revision.revision_user
AS revision_user, revision.revision_created AS revision_created,
revision.revision_log AS revision_log, base.id AS id, base.type AS
type, base.uuid AS uuid, CASE base.revision_id WHEN
revision.revision_id THEN 1 ELSE 0 END AS isDefaultRevision
FROM
{block_content} base
INNER JOIN {block_content_revision} revision ON revision.revision_id =
base.revision_id; Array
(
)
" at /core/lib/Drupal/Core/Database/Connection.php
line 686

```

When I try to run `drush entity-updates`, it errors out with this:

```
block_content entity type :
  The Revision create time field needs to be updated.
  The Revision user field needs to be updated.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while
performing a schema update. [error]
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'revision_created' in 'where clause':
SELECT 1 AS expression
FROM
{block_content_revision} t
WHERE revision_created IS NOT NULL
LIMIT 1 OFFSET 0; Array
(
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage-
>wrapSchemaException() (line 1513 of /core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Fatal error: Cannot use Drupal\entity\BundleFieldDefinition as
BundleFieldDefinition because the name is already in use in /modules/commerce/src/ConfigurableFieldManager.php on
line 8
Drush command terminated abnormally due to an unrecoverable error.
[error]
Error: Cannot use Drupal\entity\BundleFieldDefinition as
BundleFieldDefinition because the
name is already in use in
/modules/commerce/src/ConfigurableFieldManager.php,
line 8
The external command could not be executed due to an application
error.

```

Any help is appreciated, the site is down

# Answer
As per this comment, this could be related to *Dynamic Entity Reference* module as per this bug report.

The solution is to apply this patch or upgrade to the latest version of this module.

To fix the problem manually, you need to rename the field in the database from `revision_user` to `revision_user_int`.

Another suggestion from here says to add: `$settings['update_free_access'] = TRUE;` into your settings file and run `/update.php` to invoke the database updates again.
> 1 votes

---
Tags: 8
---


# Question
Title: What module would give an image thumbnail list in a slider format?
Which module would give the following slider effect? So i have a list of image thumbnails and I want to be able to scroll through them by clicking on the left or right arrows and have it show X number of them depending on my screen size.

# Answer
> 1 votes
I used jCarousel for views: --- its a bit outdated so you need the updated patch.

**You have to apply the following patch: https://drupal.org/node/1548484#comment-8260283 to make it responsive.**

If you have a better solution. Do let us know! :)

# Answer
> 1 votes
You can use Juicebox HTML5 Responsive Image Galleries Module of drupal.

This module provides an integration between the popular Juicebox HTML5 responsive gallery library and Drupal. Juicebox is in many ways the successor of Simpleviewer and offers a powerful cross-device solution for image galleries, sliders and more.

# Answer
> 0 votes
Try the jcarousel .

This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration so that you can turn any list of content or images into a carousel.

You can also try the views slideshow but this would need some extra javascript code.

# Answer
> 0 votes
You can use bxslider views slideshow module to achieve slideshow functionality.

> This module provides integration with bxSlider

There is a bug in `views slideshow` module that if you select `Left Scroll` as slide option, then it will only slide in only one direction (`Left`) wheather you click on `right` or `left` arrow.

You can also use jCarousel Module suggested by @sokratis in his answer.

---
Tags: 7, views, javascript
---


# Question
Title: How to define the site to be used in BrowserTestBase on a multisite?
I am working on a multi site where there is no database defined in the default directory, so whenever I run a Functional test extending BrowserTestBase I get the following error:

```
copy(/var/www/drupal-int/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

```

I'm not really sure why the files were removed in the first place and I don't want to add them back in there in case there was a good reason for removing them. Is there a way to define the site to use for the test?

My simple test:

```
<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;

/**
 * Simple test to ensure that main page loads with module enabled.
 *
 * @group dnsw_scheduler_workbench_integration
 */
class LoadTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['my_module'];

  /**
   * A user with permission to administer site configuration.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->user = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($this->user);
  }

  /**
   * Tests that the home page loads with a 200 response.
   */
  public function testLoad() {
    $this->drupalGet(Url::fromRoute('<front>'));
    $this->assertResponse(200);
  }

}

```

# Answer
None of your existing sites are used during a fonctionnal test, drupal creates a fresh install defined by your static attribute `$modules` and the `setUp()` method.

So, you should get the `default.settings.php` file back (and create a `/sites/simpletest` folder)
> 1 votes

---
Tags: testing
---


# Question
Title: How to use DataDefinition::create('list')?
This answer links to a list of all possible types that can be used with `DataDefinition::create()`.

One plugin that can be used is ItemList.

But I can't find any documentation on how to define what items are on the list.

I would have expected something like this:

```
$status_definition = DataDefinition::create('list')
  ->setLabel(new TranslatableMarkup('Status'))
  ->setRequired(TRUE)
  ->setListItems([
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
  ]);

```

But the method setListItems (or anything similar) does not exist.

For some more context I'm following this article on how to extend the entity reference field type but instead of adding an integer field I want to add a list field.

# Answer
`ItemList` is a generic base class. *List* is used here in the context of multivalued field items. Because Drupal has no separate class for single value fields (they are multivalued fields restricted to one value), this generic list data type is used in all Drupal fields.

When you look at the list of field types

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Annotation%21FieldType.php/class/annotations/FieldType/8.4.x

you'll find ListStringItem, where *List* is used in the context you are probably looking for and you can use this as an example for this kind of field types implementing OptionsProviderInterface.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Installing a new table into the Database
So i created a custom module, it's been installed etc, but then i figured out that i need a custom table in my db so i created a `mymodule.install` and in it three hooks (`mymodule_schema(), mymodule_install() and mymodule_uninstall()`). Now that all works fine if you are installing the module for the first time, or if you uninstall and then install the module again. But it can be a pain to reinstall a module during development, isn't there a way to trigger the \_schema() to install when you want it to ?

# Answer
You can use `drupal_install_schema()` for that:

```
drupal_install_schema('mymodule');

```

If you're looking for somewhere to execute it, a `hook_update_N()` implementation is one potential option.
> 1 votes

---
Tags: database
---


# Question
Title: How to perform a webform_submission query with a conditional based on a custom field in the submission data
I'm attempting to query all webforms with a specific id, and sorted by a boolean field that was added to a webform by me in the webform configuration manager. Below is my attempt

```
    $submission_ids = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', $webform_id)
        ->exists('paid')
        ->sort('paid', 'desc')
        ->sort('created', 'desc')
        ->pager(50)
        ->execute();

```

However when I perform this query I get

> Drupal\Core\Entity\Query\QueryException: 'paid' not found in Drupal\Core\Entity\Query\Sql\Tables-\>ensureEntityTable() (line 316 of core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

If I omit the -\>sort('paid','desc'), but keep the -\>sort('created', 'desc') the query works fine. I'm assuming this is because created is one of the base fields defined in the webform entity.

I also tried using 'field.paid', and 'data.paid' as a guess but I ended up with

> Call to a member function getColumns() on boolean in /var/www/aaep.org/http/web/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php on line 228

Is there a way to sort webform submissions by user defined fields in an entity query?

# Answer
You first need to select the Submission IDs (SIDs) from the table webform\_submission\_data:

```
$select = \Drupal::service('database')
  ->select('webform_submission_data', 'wsd')
  ->fields('wsd', array('sid'))
  ->orderBy('wsd.sid', 'DESC')
  ->condition('wsd.webform_id', $webform_id, '=')
  ->condition('wsd.name', 'paid', '=')
  ->condition('wsd.value', 1, '=')// Not sure how your BOOL value is saved
  ->execute();

// Get all the results.
$results = $select->fetchAll(\PDO::FETCH_COLUMN);

```

Then you need to use entity\_load\_multiple() or similar to load the entities:

```
if (count($results) >= 1) {
  $submissions = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->loadMultiple($results);

  foreach ($submissions as $submission) {
    // Do something
  }
}

```

Drupal.org thread Reference for basis of my answer.
> 3 votes

---
Tags: 8, entities, webforms
---


# Question
Title: Contribute D8 version of an existing D7 contrib project?
Can someone describe on how to contribute the D8 version of an existing D7 contrib project? I maintain the D7 project, and further want to add the D8 version of it.

I am struggling with creating 8.x.1.x Dev branch.

Please share any references or steps to follow.

My Project link: Check DNS.

So when I create `8.x.1.x` branch, I can see Drupal 7 specific files within that, so I am confused that how should I manage set of files for D8 and D7.

# Answer
> 2 votes
You can use *Browse code repository* to see your source code on your project page. Currently when you go to list of branches, the `8.x-1.x` doesn't exist yet.

To maintain both D7 and D8, you need to have one branch for each, `7.x-1.x` for Drupal 7, and `8.x-1.x` for Drupal 8.

To create Drupal 8 out of Drupal 7 version, you should first clone your repository as per these Git instructions:

```
git clone --branch 7.x-1.x your_user@git.drupal.org:project/check_dns.git

```

then create a new branch:

```
git checkout -b 8.x-1.x

```

which allows you to freely modify your files for Drupal 8 version.

Once you did your conversion, you can push your branch back to Drupal.org, e.g.

```
git push origin 8.x-1.x

```

To switch between branches, use `git checkout` command, so you can contribute to both version.

Ideally, you should read more about managing source code using Git. Checkout this GitHub Cheat Sheet.

---
Tags: 8, community-official-site
---


title: How to alter user's input?

text:
# Question
Title: How to alter user's input?
I have a form to get some user input in Drupal. I want to add some prefix to the user input.

For example, the user enters "Laptop"; I want to save it in the database as *resource\_Laptop*. I want to add the prefix before the validation is done, to avoid it fails.

How do I do this? Will `hook_form_alter()` help me here?

I have used this method, but not satisfied with this hack.

```
function mymodule_form_alter(){
  drupal_add_js("
    (function ($) {
      $(document).ready(function() {
        $('.field-suffix').hide();
        $('#edit-submit').click(function(){
        var s = $('#edit-machine-name').val();

        if (s.indexOf('_resources') == −1) {
          $('#edit-machine-name').val($('#edit-machine-name').val() + '_resources');
        }
      });
    })(jQuery);", 'inline');
}

```

# Answer
> 0 votes
Use the hook\_form\_FORM\_ID\_alter and add a custom submit handler.

```
function example_form_form_id_alter(&$form, &$form_state,$form_id){
  $form['#submit'][] = 'example_form_id_submit',
}

function example_form_id_submit(&$form,&$form_state){
  $form_state['values']['resource_name'] = 'resource_' . $form_state['values']['resource_name'];
}

```

# Answer
> 0 votes
Add one more validation callback handler by giving it the priority(executed first) in `$form['#validate']` and change the values in `$form_state`.

---
Tags: forms
---


# Question
Title: Can I set a CSS-class on the node in a view list based on a text field of the node?
As I understand, I need a module like this: https://www.drupal.org/project/field\_formatter\_css\_class but for Drupal 8

For example, I want to highlight one node in the views using CSS-class, how to do this?

PS

Finally I got necessary result:

```
/**
 * Preprocess function for views-view-grid.tpl.php.
 */
function themename_theme_preprocess_views_view_grid(&$vars) {
   foreach ($vars['items'] as $row) {
        foreach ($row['content'] as $item) {
             $subclass=$item['content']['#row']->_entity->field_fieldname;
             if(!empty($subclass[0])){
                $item['attributes']['class'][] = 'col-'. $subclass[0]->value;
             }
        }
   }
}

```

# Answer
> 1 votes
```
/**
 * Implements hook_preprocess_html().
 */
function themename_preprocess_html(&$variables) {
$node = load_your_node// Load you node here and add proper condition and type for following code
    $variables['attributes']['class'][] = 'page-node-' . $node->custom_textfield();
}

```

# Answer
> 0 votes
I had to add '#' before 'attributes'.

This is an exemple in a Listbuilder class for those which are doing this.

```
class SubscribeMeMailListBuilder extends EntityListBuilder {

  /*
   * {@inheritdoc}
   */
  public function render() {
    $render = parent::render();
    $render['table']['#attributes']['class'][] = 'subscribeme_table';
    return $render;
  }
}

```

---
Tags: views, 8
---


title: Drupal 8 Rules and Media

text:
# Question
Title: Drupal 8 Rules and Media
I want to publish Media associated with content when the content is published.

Is that possible with rules?

If so, what are the conditions I need to set?

The conditions I have set are:

> 1. Node is published - data selector: node
> 2. entity has field - data selector: node, value: field\_my\_media\_field

# Answer
> Is that possible with rules?

I'm a bit familiar with the (amazing!) Rules module. But to my knowledge the current answer to this question is ***No***, ***Non***, ***Neen***, ***Nein***.

### More info

* Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some (scary) quotes from it:

> + ... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.
>     + ... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.
* Start here if you wonder how to contribute.

---

One never realizes what ***has been*** done, only what ***remains to be*** done ...
> 1 votes

---
Tags: 8, rules, media
---


# Question
Title: How can I embed a video in a drupal page that is remotely hosted in Amazon s3 cloudfront?
When I try to embed a video in a drupal page that is hosted remotely on an Amazon s3 server, I get the following error message:

"Could not find a video provider to handle the given URL"

I have the Video Embed Field, Video Embed Media, Video Embed WYSIWIG modules enabled, but still cannot get this to work.

The URL of my video has this form, where the x's represent the directory path to the videos. https://s3-us-west-2.amazonaws.com/xxxxx/xxxxx/xxxx.mp4

Can anyone help me get this working?

# Answer
> 0 votes
Those modules only know how to embed videos from particular providers (Youtube, Vimeo, Facebook, etc). They actually parse the URL and check that it contains "youtube" or "vimeo" or whatever. The modules won't work with arbitrary URLs, S3 or not.

A couple of potential solutions:

1. Use a more generic module, for example VideoJS, which should theoretically let you embed a video from anywhere.
2. Write your own handler for Video Embed Field which knows how to embed videos from S3. You'll presumably have to find a JS library which can play the video from Amazon, and integrate that as part of it. Writing the handler itself is pretty easy, it's just a matter of a hook or two and a few functions. The code for the existing handlers makes it pretty obvious what needs to be done.

---
Tags: media
---


# Question
Title: Disable user registration in /user/register, but allow registration during commerce checkout?
Only users who paid can finish registration and they get a role applied to their user.

Problem is that, users can still register through default registration form.

Disabling registration for in Account settings will disable the registration globally everywhere?

How to disable it only in `/user/register`? But allow during commerce module checkout process?

# Answer
> 3 votes
You can do that with `hook_menu_alter()` by changing the access for that path:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = FALSE;
}

```

---
Tags: 7, users, commerce
---


# Question
Title: How do I change the label and help text of the publishing status checkbox?
We recently updated our site to Drupal 8.4 and the widget for publishing a node has changed from a dropdown to a checkbox. Now, how do I change the label and help text of the checkbox? It cannot be changed in the field UI.

# Answer
You can use hook\_form\_alter() to change label and help text Use devel module to debug the label and help text change accordingly.

```
/**
 * Implements hook_form_alter().
 */

  function hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'node_page_form'){
   kint($form);
   kint($form['status']['widget']['value']['#title']);
   $form['status']['widget']['value']['#title'] = t('Published status label changed');
  }
}

```

After applying above code for basic page node form i was able to see the change in label of published text to Published status label changed
> 5 votes

# Answer
You can try use the hook\_form\_alter,

```
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //obtain the default value
  $value_status_default= $form['status']['widget']['value']['#default_value'];

  //we modified the title of the field
  $form['status']['widget']['value']['#title']='Publishing Status';
  //we modified the description of the field
  $form['status']['widget']['value']['#description']='New Description Publishing status';
  //we modified the type of the field
  $form['status']['widget']['value']['#type']='select';
  //we modified the options of the field
  $form['status']['widget']['value']['#options'] = [
    true => t('Published'),
    false =>t('Not Published'),
  ];
  //we modified the default valueof the field
  $form['status']['widget']['value']['#default_value'][]=$value_status_default;

}

```

the result
> 3 votes

---
Tags: 8
---


title: Translate node with node fields

text:
# Question
Title: Translate node with node fields
I'm using the Node Field module. When I translate a node its respective node fields are not copied to the translation, forcing me to recreate them by hand. Is there a workaround to this?

# Answer
I ended up solving the problem by using hook\_node\_insert:

```
/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  // Only act if we are dealing with a content type supporting translations.

  if (translation_supported_type($node->type)) {

    if ($node->tnid != $node->nid) {

      $sql = "INSERT INTO node_field( nid, type ,title ,machine_name ,show_title ,hidden ,value ,weight ,settings)
          SELECT :new_node, type, title, machine_name, show_title, hidden, value, weight, settings
          FROM node_field
          WHERE nid=:old_node";

      db_query($sql, array(':new_node' => $node->nid, ':old_node' => $node->tnid));
    }
  }
}

```
> 0 votes

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


# Question
Title: Can I use same (machine) name for taxonomy and content type?
My question: Can I (or rather, should I) create a taxonomy and a custom content type that have the same machine name? I plan to 'link' those two together.

I tried to search around and could not find an answer, I found out that two custom fields cannot have the same name, even if they belong to two different content types for example. So that would lead me to suggest that the answer to my question is probably not (i.e. they would try to use the same table name). But I don't know if that's correct.

Say I create a site for a school, and want to have a custom content type 'staff' that will hold teachers, administrative staff, etc. I will also have a vocabulary that has these different staff categories (teachers, administrative staff etc), which I also thought of giving it the name 'staff'. Is this a bad idea?

PS: I'm using Drupal 8

# Answer
Technically you can have same name for taxonomy and content type as the underlying machine name is not the same and there is no confict.

Practically it might not be a good idea as it might confuse the end users but it depends on the problem you are trying to solve.

So based on your description `staff category` might be a better name for your category.
> 1 votes

# Answer
Ah .. I am careless. It must obviously be unique, I didn't pay enough attention, it mentions it under the field for the name of the custom content type. It says:

*The human-readable name of this content type. This text will be displayed as part of the list on the Add content page. **This name must be unique***

So I guess it cannot have the same name (machine\_name) as a vocabulary. I just write it here for reference...
> 0 votes

---
Tags: nodes, database
---


# Question
Title: How to remove "Drupal" from title of page?
Now I have this:

Here i found information how to change this text to anything else: https://www.drupal.org/forum/support/post-installation/2016-09-20/change-site-title-in-drupal-8

I tried:

But it doesn't help.

Drupal is 8.4.2

And it works on 8.0.6

# Answer
> 2 votes
Drupal by default will put the `site name` at the end of the page title but specific themes might change this.

if you want to override this your best bet is to use https://www.drupal.org/project/metatag module and override appropriate settings

There is a setting for first page or for all content types or specific content types; it very configurable.

Or you might do it programmatically in your THEMENAME.theme file:

```
function THEMENAME_preprocess_html(&$variables) {
    $variables['head_title']['name'] = "Another Name";
}

```

To take away the `|` you have to create a new `html.html.twig` template in your custom theme and modify (copy paste it from the theme you are overriding)

```
    <title>{{ head_title|safe_join(' | ') }}</title>

```

to something like this

```
    <title>{{ head_title|safe_join('  ') }}</title>

```

---
Tags: 8
---


# Question
Title: Reference a block plugin, or Form, from a Paragraph?
Is there a way for a Paragraph to reference either a custom Form (built with Form API) *or* a block plugin that renders the same form? I only see a way to have a field that references either custom blocks (content) or configuration blocks, but not both. How can this scenario be solved?

# Answer
> 3 votes
I haven't tried it, but the Dynamic Entity Reference module looks good. The 8.x-2.x branch, although currently in alpha, sounds like it has the functionality you're looking for:

> This version allows all content entities as referenceable entities. This version also allows all config entities as referenceable entities but it is only configurable programmatically. The content and config entities can be referenced in the same field as well.

It'll mean a bit of coding to get the config entity working, but a lot less code than writing the whole thing from scratch.

---
Tags: 8, entities, paragraphs
---


# Question
Title: Set a form element value to an empty string when it fails validation
I need to set the value of a form element to an empty string, when it doesn't pass validation.

I tried using the following code, but the form element still contains the last submitted value, when the form is re-built.

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  if ($values['myfield'] != 'something') {
    $form_state->setValue('myfield', '');
    $form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
  }
}

```

A workaround I found is using the following code.

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  if ($values['myfield'] != 'something') {
    $form['myfield']['#value'] = '';
    $form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
  }
}

```

Instead of calling `$form_state->setValue('myfield', '')`, it sets the value of `#value` in the `$form` array.

It doesn't seem the correct solution, though. How can I achieve what I want?

# Answer
Use `FormStateInterface::setValueForElement()`, which requires two arguments: the form element and the new value.

In your case, you would need to use code similar to the following one.

```
public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  if ($values['myfield'] != 'something') {
    $form_state->setValueForElement($form['myfield'], '');
    $form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
  }
}

```
> 3 votes

# Answer
In your `validateForm` you can use:

```
 public function validateForm(array &$form, FormStateInterface $form_state) {

    if($form_state->getValue('myfield')!='something') {

        $form['myfield']['#value']='';

        $form_state->setErrorByName('myfield', t('Sorry, this field value is not correct.'));
    }

  }

```
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to prevent display of specific paragraph types (bundles) on nodes
I have a content type with a paragraph field which has many paragraph types available. For one of these paragraph types, I do not want it displayed in the node because I am displaying it using a view in a different region. The view works great but I cannot figure out how to prevent the specific paragraph type from displaying on the node. I've tried to removeItem from the render array using various hooks in .theme, but this removes it from the view as well. I have also tried to remove the paragraph type from the paragraph field in the node template using a loop in twig. I feel like there has to be an easier way.

# Answer
Twig's `without` filter worked in my case.
> 1 votes

# Answer
You can use https://www.drupal.org/project/views\_field\_formatter.

Create a view that does what you want using contextual filter of the node id.

Than modify the node display settings to use that view.
> 0 votes

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


# Question
Title: Programmatically rearrange order of entity reference list on node
My content type has a node reference field that allows users to enter an unlimited amount of nodes in. I need to programmatically change what comes first in this list.

Using the code below I'm able to obtain the data from the field.

```
$node = \Drupal::entityTypeManager()->getStorage('node')->load($function);
$focus = $node->field_focus_area->getValue();

```

And it produces:

```
array(2) {
  [0]=>
  array(1) {
    ["target_id"]=>
    string(2) "31"
  }
  [1]=>
  array(1) {
    ["target_id"]=>
    string(3) "161"
  }
}

```

In order to rearrange it I tried doing

```
$newOrder[0] = ['target_id'=> 161];
$newOrder[1] = ['target_id'=> 31];

$focus->field_focus_area->rekey($newOrder);

```

But it was then when I realized that rekey was a protected function so I could use it. How would I programmatically rearrange the deltas (if that's what you'd call it) of an entity reference field programmatically?

# Answer
> 2 votes
After getting and rearranging the field data you can set it again:

```
$node->field_focus_area->setValue($newOrder);

```

---
Tags: 8, nodes, entities
---


# Question
Title: How do I add a custom textarea into the checkout screen?
I want to add 'Notes' textarea for adding addtional message by customer while placing the order.

I have added additional textarea in 'Order types' page (/admin/commerce/config/order-types/default/edit/fields). It is displaying in order page but not in checkout page.

Example: Customer is placing an order for Toys and they want to add message saying 'Please deliver in 2 days..'

Edit: I have seen same question in Drupal 7. But there is no 'Commerce Fieldgroup Panes' module in Drupal 8.

# Answer
You will need to write a custom checkout pane plugin, I'm afraid.

Docs here: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane
> 1 votes

# Answer
You can add custom fields using profile \> Customer by following path.

```
/admin/config/people/profiles/manage/customer/fields

```

You must have installed Profile module also with Commerce 2
> -1 votes

---
Tags: 8, commerce
---


# Question
Title: Leave Month (Date) Field blank (Optional)
I was wondering if it's possible to have Drupal (7), leave the Month field NULL (empty).

When someone sets a Date, sometimes they don't need to enter a Month along with it. When I try this by Default, Drupal says a Month is needed.

Thanks

# Answer
You can use Number field and do the validation if you just want to store only DD(Day).

Date picker is using to collect Day Month Year
> 0 votes

---
Tags: nodes, entities
---


title: How do I upgrade from 8.4.2 to 8.4.3?

text:
# Question
Title: How do I upgrade from 8.4.2 to 8.4.3?
I already have Drupal 8.4.2. Now I want to upgrade to 8.4.3 via commandline.

Via Drupal commands or Composer.

How to do that?

# Answer
> 1 votes
Easy way :

```
composer update
drush updb # or update.php via browser

```

# Answer
> 0 votes
**Using Drush:**

Update Drupal 8 core `drush up drupal`

Update a single module `drush up module_name`

Update only security updates `drush up --security-only`

**Manual Updation:**

http://www.zymphonies.com/blog/update-drupal8-core

# Answer
> 0 votes
If you are using Drupal Console, then have a look at following command:

```
drupal module:update [arguments] [options]
moup

```

Reference: https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/module-update.html

---
Tags: 8
---


title: Why does cron run as an anonymous user?

text:
# Question
Title: Why does cron run as an anonymous user?
I ran into an issue recently where my hook\_cron function was failing when triggered by cron. The problem was that I was calling EntityFieldQuery, which does access checks and since cron runs as an anonymous user, the query would to process correctly. Specifically, I was having this issue: EntityFieldQuery doesn't work correctly in hook\_cron

I am trying to understand **why** cron runs as an anonymous user. Cron clears the cache and so has at least some database access. When writing hook\_cron functions now, I have to bypass access checks so that they return results as expected. Does anyone understand why this is the intended behaviour?

Drupal 7

# Answer
A cronjob should not have to be run by a specific drupal user. It sounds just like a maintenance task that should run sometimes to do something (send a part of a mail queue, clear some part of cache or whatever).

In some installs (all of mine, for example) run crons via drush/linux cronjob. `cron_safe_threshold` is set to `0` (never).

> Typical tasks managed by hook\_cron() are database maintenance, backups, recalculation of settings or parameters, automated mailing, and retrieving remote data.
> 1 votes

---
Tags: 7, users, cron
---


# Question
Title: Should I use t() in a hook_menu's description?
I have always used t() for hook\_menus title and description like this:

```
$items['some-path'] = array(
    'title' => t('My Page Title'),
    'description' => t('This is a description about what my page is for'),
    'page callback' => 'profile_user_page',
);

```

This makes sense to me so users can translate the title and description into different languages if required.

However this comment on a module review on DO says:

No, that's wrong, don't do that - descriptions in hook\_menu() should never use t().

What is the reasoning for this and is this actually best practice?

Also if this is true then should we not use t() for the title as well?

# Answer
> 17 votes
See Strings at well-known places: built-in menus, permissions, log messages and .info files community documentation:

> The Drupal 6 and 7 menu system stores menu item titles and descriptions in English. This allows the system to cache the data, but display to users using various languages on demand. For this to work, **you should not use t() on the title or description of menu items** in your hook\_menu() implementation. Additionally, you should attempt to use a literal string (rather than a dynamic string) for these two keys, so the translation template extractor can find the string you used.

Emphasis mine.

# Answer
> 11 votes
If you see documentation of hook\_menu arguments..

* "title": Required. The untranslated title of the menu item.
* "title callback": Function to generate the title; defaults to t(). If you require only the raw string to be output, set this to FALSE.
* "title arguments": Arguments to send to t() or your custom callback, with path component substitution as described above.
* "description": The untranslated description of the menu item.

By default title callback is t function.. So it is always translated..

# Answer
> 7 votes
Since Drupal 6 is not needed anymore.

Please read https://drupal.org/node/140311. Quoting that:

> As of 6.x, Drupal internally handles the translation of menu titles and descriptions into the user's local language. Descriptions, if provided, are always translated with t(); there is no way to pass in additional data for placeholder substitution (in D5 and prior, passing in substitutions was a discouraged practice - with this change, the menu system enforces that rule directly). Titles are translated with t() by default, but t()-style string replacement is possible through the use of the new 'title arguments' property. You can also choose to replace t() with your own custom callback.

# Answer
> 6 votes
You should not use `t()` in `hook_menu()` implementations because `t()` is automatically called later on and doing so would cause double translation.

# Answer
> 0 votes
It clearly says on the documentation page for hook\_menu() i.e

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu/7.x

**"title": Required. The untranslated title of the menu item.**

**"description": The untranslated description of the menu item.**

So no need to use t() function for both above.

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


title: How to sort by a fields content?

text:
# Question
Title: How to sort by a fields content?
so I have a content-type called `"Team Member"` and I'd like to sort for the field `"last_name"`.

I currently get all the nodes using:

```
nids = db_select('node', 'n')
->fields('n', array('nid', 'field_last_name'))
->condition('type', 'team_member')
->orderBy('n.title','ASC')
->execute()
->fetchCol();

```

So currently, they are sorted using the title. How can I now tell it to sort using `"last_name"` field? I just don't see what exactly db\_select needs to know here.

Im on D7.

# Answer
You shouldn't query the database directly for entity data, there are APIs for that.

In this case you need an `EntityFieldQuery`:

```
$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'team_member')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_last_name', 'value');

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
}

```
> 3 votes

# Answer
Cannot test for now but this could work (considering field\_last\_name is a textfield) :

```
$nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->fields('last_name', array('field_last_name_value'));
        ->join('field_data_field_last_name', 'last_name', 'last_name.entity_id=n.nid');
        ->condition('n.type', 'team_member')
        ->orderBy('last_name.field_last_name_value','ASC')
        ->execute()
        ->fetchCol();

```
> 1 votes

---
Tags: 7, database
---


# Question
Title: How to save each array values in next line?
I am having a requirement that, automating the contributed module configurations via hook\_update. I have a text area, where i need to mention different URLs with one URL/line. For reference look into the image:

To achieve this I have to use `variable_set();` function. I tried something like below but not able to get all the values displayed.

```
$test = array('abc/*','xyz/*','ijk/*');
variable_set('boost_testing', $test);

```

This code is setting only first row, it will not come to next row.

So please suggest something I can do by using `<br>` or `\n` so that i can display each values next row. Any help will be appreciated.

# Answer
> 0 votes
You should pass paths as a string instead of array:

```
$test = "abc/*\nxyz/*\nijk/*\n";
variable_set('boost_testing', $test);

```

Remember to use double quotes for the $test string.

---
Tags: 7, theming, updating, caching
---


title: How to hide label if field is empty?

text:
# Question
Title: How to hide label if field is empty?
so I have a content-type `X` and some nodes of this type. If I go to the node page, I'd like to not see the label of an empty field. Where in the display options can I change that?

In my case ,the content of the fields are some check-boxes (from a vocabulary). I'm on D7.

# Answer
Try the settings in `/admin/structure/taxonomy/X/display` (label settings)

but it should be done automatically if there is no content
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Database field of timestamp type cannot be added to the database using hook_schema()
I have created a custom module in drupal 8. But in the .install file there is a field for created\_date which has a type of timestamp. When I try to enable that module it gives the below error.

```
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'created_date'' in

```

**.install file**

```
<?php
function golf_reservation_schema()
{
  $schema['golf_reservation'] = array(
   'fields' => array(
       'id' => array(
           'type'     => 'serial',
           'not null' => TRUE,
       ),
       'property_tid' => array(
           'type' => 'int',
           'not null' => TRUE,
       ),
       'property_name' => array(
           'type'     => 'varchar',
           'length'   => 100,
           'not null' => TRUE,
       ),
       'title' => array(
           'type'     => 'varchar',
           'length'   => 20,
           'not null' => FALSE,
       ),
       'full_name' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'tee_date' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'tee_time' => array(
           'type'     => 'varchar',
           'length'   => 255,
           'not null' => TRUE,
       ),
       'golfers' => array(
           'type'     => 'int',
           'not null' => TRUE,
       ),
       'no_of_carts' => array(
           'type'     => 'int',
           'not null' => TRUE,
       ),
       'special_request' => array(
           'type'     => 'text',
           'not null' => FALSE,
       ),
       'created_date' => array(
           'mysql_type' => 'timestamp',
           'not null' => true,
       ),
     ),
     'primary key' => array('id'),
   );

   return $schema;
}

```

But when I execute this query in database it does not give an error

```
CREATE TABLE eme_golf_reservation (
  `id` INT NOT NULL auto_increment,
  `property_tid` INT NOT NULL,
  `property_name` VARCHAR(100) NOT NULL,
  `title` VARCHAR(20) NULL DEFAULT NULL,
  `full_name` VARCHAR(255) NOT NULL,
  `tee_date` VARCHAR(255) NOT NULL,
  `tee_time` VARCHAR(255) NOT NULL,
  `golfers` INT NOT NULL,
  `no_of_carts` INT NOT NULL,
  `special_request` TEXT NULL DEFAULT NULL,
  `created_date` TIMESTAMP NOT NULL,
  PRIMARY KEY (`id`)
)

```

I am running the latest Drupal version with MySQL 5.6.30.

# Answer
> 3 votes
I believe you need to explicitly define the default value for those in the schema:

```
'created_date' => [
  'mysql_type' => 'timestamp',
  'not null' => FALSE,
  'default' => NULL,
],

```

For maximum portability, you can also define the types for other databases:

```
'created_date' => [
  'mysql_type' => 'timestamp',
  'pgsql_type' => 'timestamp',
  'sqlite_type' => 'datetime',
  'not null' => FALSE,
  'default' => NULL,
],

```

Look at `\Drupal\KernelTests\Core\Database\SchemaTest` for an example. FWIW, code doesn't use that for timestamp/created/updated. Those are field types and handled by the Field API.

---
Tags: 8, database, datetime
---