title: Base URL issue in Subdomain

text:
# Question
Title: Base URL issue in Subdomain
I have my main site as example.com and also I am running the below subdomains with help of subdomain module

1. one.example.com
2. two.example.com

I have created the html block(**admin/structure/block/add**) for footer to list my site links. This block is visible for main domain(example.com) and all subdomains(one.example.com,two.example.com)

But I have URL issues in that footer block in subdomains. For example I have `<a href="/suggestions">Suggestions</a>` in footer block, when I am in **main domain** it goes to `http://example.com/suggestions`. It goes to `http://one.example.com/suggestions` & `http://two.example.com/suggestions` when I am in **subdomains**.

BUT IT SHOULD GOES TO ONLY **http://example.com/suggestions** FOR ALL SUBDOAMINS

Any way to achieve this?

# Answer
> 1 votes
I like adding the redirect to sites/default/settings.php instead of .htaccess (just because Pantheon ignores .htaccess redirects and a lot of my sites are hosted on Pantheon). I'm also just more comfortable with the syntax.

The first example will redirect just /suggestions to example.com/suggestions. The second example redirects any path beneath /suggestions (e.g., /suggestions/submit or /suggestions/submit/thankyou) to that same path on the main domain (example.com).

In terms of wild-carding this solution for scenarios similar to 'suggestions', I don't think that would work. I mean you don't want to redirect everything so you have to check for a specific REQUEST\_URI.

But you could use this solution as a template for the other redirects you need. If you have a very large number of these (or anticipate a large number in the future), you might consider switching to the Domain Access module instead as it would handle this scenario without any redirects or custom coding.

You'll need to update 'example.com' to match your main domain and you may need to change 'http' to 'https' is you're using TLS.

```
// 301 Redirect from /suggestions to example.com/suggestions
if ($_SERVER['HTTP_HOST'] != 'example.com' &&
  $_SERVER['REQUEST_URI'] == 'suggestions' &&
  (php_sapi_name() != "cli")) {
    header('HTTP/1.0 301 Moved Permanently');
    header('Location: http://example.com/suggestions');
    exit();
  }

// 301 Redirect from /suggestions/* to example.com/suggestions/*
if ($_SERVER['HTTP_HOST'] != 'example.com' &&
    $_SERVER['REQUEST_URI'] == 'suggestions' &&
    (php_sapi_name() != "cli")) {
      $url = $_SERVER['REQUEST_URI'];
      $url = substr($url, 13); // stripping '/suggestions/' which is 13 chars
      header('HTTP/1.0 301 Moved Permanently');
      header('Location: http://example.com/suggestions/'. $url);
      exit();
  }

```

# Answer
> 0 votes
Here is the Rewrite Rule to be written in .htaccess file located in Drupal Root directory.

```
RewriteEngine on
# Rule for /suggestions.
RewriteCond %{REQUEST_URI} /suggestions
RewriteRule ^(.*) http://example.com/suggestions [L,R=301]

# Rule for /site-map.
RewriteCond %{REQUEST_URI} /site-map
RewriteRule ^(.*) http://example.com/site-map [L,R=301]

#Rule for more links.
...
...

```

---
Tags: 7, blocks, subsites
---


# Question
Title: hook_menu wildcard auto-loader for webform submission?
In `hook_menu()` array keys, you can specificy wildcard tokens to autoload certain objects, such as `%node` to get the node object.

Is there a wildcard autoloader token for webform submissions? Some googling I've done has returned no results.

I've also grepped the codebase of the webform module for `autoload`, also to no results.

# Answer
It is looking for a \_load() function. In the case of node, user, or taxonomy term arguments (eg `%node`), it is looking at `node_load`, `user_load`, etc.

If you passed `%mymodule_foo` as the wildcard, then it would look for `mymodule_foo_load()`.

Therefore, if there is a webform submission \_load function that loads a submission, thats what you want to use as the wildcard.

The wildcard you want to use is `%webform_menu_submission`. Webform has a corresponding \_load function for it:

```
/**
 * Menu loader callback. Load a webform submission if the given sid is a valid.
 */
function webform_menu_submission_load($sid, $nid) {
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission = webform_get_submission($nid, $sid);
  return empty($submission) ? FALSE : $submission;
}

```

Note that this function also needs a `$nid` argument to work.

> Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named mymodule\_abc\_load(). When a matching path is requested, **your load function will receive as its first argument the path component in the position of the wildcard**; load functions may also be passed additional arguments

See:
> 2 votes

---
Tags: 7, routes, webforms
---


# Question
Title: Create a custom template for a custom URL
I'm using the Webform module and need to redirect users to a custom URL (with replacement tokens) once they have completed a job application in order to track conversions in Google Analytics.

I've set the URL to `/application-completed/[job-ref-number]`. This redirect works but I really want a custom template to be rendered rather than the default Webform confirmation message on a 404 page.

I've tried the following in my template.php file but the issue here is that it's a completely blank template (not rendering html.tpl.php), whereas I'd prefer to render the page.tpl.php template and simply replace the `$page['content']` area with the custom template (would this be a node template?)

```
function MYTHEME_preprocess_page(&$vars) {
  if (drupal_match_path(drupal_get_path_alias(), 'application-completedy/*')) {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

```

# Answer
> 1 votes
You're on the right track. You just need to also create a file named page\__mycustomtemplate.tpl.php (place it in your mytheme/templates directory). The starting point for this file should either be the page.tpl.php in your mytheme/templates dir (if there is one), or the one in mysiteroot/modules/system. Simply open one of these and save it as page\__mycustomtemplate.tpl.php in your theme's templates dir. Then you can replace `<?php print render($page['content']); ?>` with your custom text/markup.

---
Tags: theming, webforms
---


# Question
Title: How to join 2 views block with a views page
Created a content type x. Fields: title, body, serviceareas. Added 5 nodes.

# View1

Created a views page:

1. Views path: house/%.
2. Contextual Filter: added nid.
3. Selected body field to display.

# View2

Created a views block:

4. Added nid. Excluded from display.
5. Added Title field. Output field as a link \> link path: house/\[nid\]

# Results:
6. When I click a title from the block, I get views page accordingly.

Addition:

# View3
7. I would like to add one more views block which will select serviceareas field for that node.
8. This block will only display in all the views page.

When I click the title link (step 5), I like to display the body field(it works now already). I also like to display serviceareas field (step 7) to views 1 and views 2. I am not sure how to join the views 3 to views 1 and views 2? So that I can see serviceareas related to the views page I am on.

# Example:

Node/1 Title: title1 Body: body1 Serviceareas: serviceareas1.

Node/2 Title: title2 Body: body2 Serviceareas: serviceareas2.

When I click the title 1(views 2), views page(views1) should display body1(works) and on the same page another region, views block(views 3) should display serviceareas1.

When I click the title 2(views 2), views page(views1) should display body2(works) and on the same page another region, views block(views 3) should display serviceareas2.

> > > ------------------------\<\<\<

I placed views2 and views3 block in the same region. Views 2 should display all the nodes titles(works). Views3 should display only field from the nid(does not work).

Views3 block: I added one field. Contextual filter: I added nid.

When I click a title link from views2, I get body from views1 page but I do not get the field from views3 block. Below is the view3 block -contextual section.

# Answer
If I understand your question correctly, you want to display the result of a View into another View. You can do this by using the contributed module Views Field View:

> views\_field\_view allows you to embed one view into another view and pass arguments along

By using this module you can add an extra field to your View1 and View2, which shows the result of your View3.

===

In your updated question, Views3 has become a separate block. Using a contextual filter you can limit the rows to be only from a specific node (id), the one that is being displayed. The answer on How to associate the current Node ID when running from Block layout? should point you in the right direction, your contextual filter should be similar to the one you used in View1.
> 2 votes

---
Tags: views
---


# Question
Title: Adding validation to widget settings form
I'm creating a new field in Drupal 8. I've created a class for the widget, extending `WidgetBase` and implementing `WidgetInterface`, and added the functions `defaultSettings()`, `settingsForm()` and `settingsSummary()`.

I want/need to validate the element I'm adding in `settingsForm()`, but I can't seem to figure out how to add validation to this. I tried adding a function `settingsFormValidate()`, but that doesn't seem to be called. I also tried adding `#element_validate` to the element I'm adding in `settingsForm()`, but that also does not seem to be called.

Note that I'm not looking to validate the widget (that is shown to the user), I'm looking to validate the element added in `settingsForm()` for the widget, that is on the Manage Form Display tab, when adding the field to Entities/content types.

Does anyone know how or whether it's even possible to add validation to the widget settings form?

# Answer
> 7 votes
Once again, I've found the solution to my issue. Although I said that I had tried #element\_validate in my original post, I must have messed something up, because that turned out to be the solution. Here is the code:

```
class SomeWidget extends WidgetBase implements WidgetInterface
{
  public function settingsForm(array $form, FormStateInterface $form_state)
  {
    $element['my_field'] = [
      '#type' => 'textfield',
      '#title' => t('My Field'),
      '#default_value' => $this->getSetting('my_field'),
      '#required' => TRUE,
      // Add your validation here
      '#element_validate' => [
        // settingsFormMyFieldValidate() is arbitrary. Choose something descriptive
        [$this, 'settingsFormMyFieldValidate'],
      ],
    ];

    return $element;
  }

  public function settingsFormMyFieldValidate($element, FormStateInterface $form_state)
  {
    $submitted_value = $form_state->getValue($element['#parents']);
    if($submitted_value != 'something it should equal')
    {
      $form_state->setError($element, t('You submitted a bad value'));
    }
  }
}

```

# Answer
> 4 votes
There is a field\_example module in the examples module. It includes a TextWidget and Text3Widget, both of which have a validation function on their formElement.

```
/**
 * Plugin implementation of the 'field_example_text' widget.
 *
 * @FieldWidget(
 *   id = "field_example_text",
 *   module = "field_example",
 *   label = @Translation("RGB value as #ffffff"),
 *   field_types = {
 *     "field_example_rgb"
 *   }
 * )
 */
class TextWidget extends WidgetBase {
  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $element += array(
      '#type' => 'textfield',
      '#default_value' => $value,
      '#size' => 7,
      '#maxlength' => 7,
      '#element_validate' => array(
        array($this, 'validate'),
      ),
    );
    return array('value' => $element);
  }

  /**
   * Validate the color text field.
   */
  public function validate($element, FormStateInterface $form_state) {
    $value = $element['#value'];
    if (strlen($value) == 0) {
      $form_state->setValueForElement($element, '');
      return;
    }
    if (!preg_match('/^#([a-f0-9]{6})$/iD', strtolower($value))) {
      $form_state->setError($element, t("Color must be a 6-digit hexadecimal value, suitable for CSS."));
    }
  }
}

```

I hope this points you to the right direction.

---
Tags: 8, entities
---


title: How to do join on Drupal dynamic query

text:
# Question
Title: How to do join on Drupal dynamic query
Following the documentation on https://www.drupal.org/docs/7/api/database-api/dynamic-queries/joins I have constructed a very simple dynamic query with join:

```
$query = db_select('node', 'n')
     ->condition('n.uid', $promoter, '=')
     ->condition('n.type', 'campaign', '=')
     ->condition('n.status', '1', '=')
     ->fields('n', array('nid'));
     $query->join('field_data_field_department', 'd', 'n.nid = d.entity_id');

  $result = $query->execute();
    foreach ($result as $record) {
      debug($record);
}

```

and it only returns nids whereas the expected results were nids together with the field\_data\_field\_department field values. What should the correct query.

# Answer
You're only selecting the `nid` field, you just need some more:

```
...
->fields('n', array('nid'))
->fields('d', array('fields', 'you', 'want'));

```
> 2 votes

---
Tags: database
---


title: How to show like and dislike on a View?

text:
# Question
Title: How to show like and dislike on a View?
How I can show Like & dislike button on a view in drupal 8?

If the view is of content type then Like & dislike show but with all fields of content.

If we select views as a field type then there is no option to add Like & dislike.

# Answer
> 1 votes
You can use this module https://www.drupal.org/project/like\_dislike. I just tested it with a view and it works perfectly.

---
Tags: views, 8
---


# Question
Title: Is it possible to show contents in a specific sites for multilingual site?
> Is it possible to show contents in a specific sites for multilingual site?

I have a site of multilingual support with english and bangla language. There is a content type blog. so Now I want to publish english content in a `en.demo.com` site and bangla content at `bn.demo.com` site and the different content will be visible at different site and it will generate different url. Is it possible and how ?

# Answer
> 1 votes
Go to `en/admin/config/regional/language/configure` and make sure `URL` is at the top. Press `configure` and select `Domain`. There you go.

---
Tags: 7, nodes, i18n-l10n, uri, redirection
---


title: Add Artwork to pushtape Player

text:
# Question
Title: Add Artwork to pushtape Player
I want to add artwork song cover(image) to pushtape player.

This will be shown in the *current playing song* inside pushtape player block.

The image will be loaded from Image Field in the content type **field\_image**

The module showing the current node title in the block and the module work in soundmanager2 library.

# Answer
The player uses JS to load the current track title into the pushtape player block based on the audio link for the current track. Basically all the script does is take the inner HTML of the original audio link and copies it to the global player block in .pt-current-track-title. Anything between the audio's link tag will show up as the current track title.

`<a href="pt-link" href="audiofile.mp3">Track title</a>`

So what you could do is find whatever is generating the .pt-link link markup and add a small img tag next to the track title and upon playback it would get copied to the global pushtape control block when it is the current track.

`<a href="pt-link" href="audiofile.mp3"> <img src="artwork-thumb.jpg"> Track title</a>`

You might want to add some additional span markup to make it easier to style.

Also if you want to learn more, check out the pushtape-player.js github page for more details about how the script works. The Drupal module is basically just a wrapper for it.
> 1 votes

---
Tags: 7, theming, entities
---


# Question
Title: The wrapper of Text field is changing after adding a new item in a field collection
I face a issue in my code in drupal 7. I alter a field\_collection module. I have unlimited field collection (field\_smart\_objectives) that has two field collections (field\_smart\_objective\_task and field\_tms\_task). field\_tms\_task is unlimited and has a select list that fire an ajax callback when the selection change and it will update a text field in field\_smart\_objective\_task. My form as in the image below

This is my code

```
function field_collection_form_alter(&$form, &$form_state, $form_id) {
global $user;

if($form_id == 'employee_performance_node_form') {

$weightCount=0;
$maxField=0;

 $delta_tn=0;
$delta_tn  =$form['field_smart_objectives']['und']['#max_delta'];

while($maxField<=$delta_tn){
    $delta_tn_ud=0;
    $delta_tn_ud = $form['field_smart_objectives']['und'][$maxField]['field_tms_task']['und']['#max_delta'];
    $delta = 0;
    $Count_progress=0;

    while ($delta <= $delta_tn_ud) {

           $content_type= $form_state['values']['field_smart_objectives']['und'][$maxField]['field_tms_task']['und'][$delta]['field_task_progress']['und'][0]['value'];

          if($content_type == "0")
           {
              $Count_progress= $Count_progress + ( 100 / $delta_tn_ud);
           }

    $form['field_smart_objectives']['und'][$maxField]['field_tms_task']['und'][$delta]['field_task_progress']['und']['#ajax'] = array(
          'callback' => '_user_ajax_check',
          'wrapper' => 'test_entity_callback'.$maxField,
          'method' => 'replace',
          'effect' => 'fade',
          'event' => 'change',
        );

        $delta++;
}

           if($delta_tn_ud==0)
          {
           $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und'][0]['field_so_progress']['und'][0]['value']['#value'] = $Count_progress;
         }
         else
        {
            $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und'][0]['field_so_progress']['und'][0]['value']['#value'] =$Count_progress;
        }

    $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#prefix'] = '<div id="test_entity_callback'.$maxField.'">';
    $form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#suffix'] = '</div>';

$maxField++;
}

function _user_ajax_check($form, &$form_state) {
 $delta_tn=0;

  $delta_tn  =$form['field_smart_objectives']['und']['#max_delta'];

  return $form['field_smart_objectives']['und'][$delta_tn]['field_smart_objective_task'];

}

```

We I change the select value of field\_tms\_task select list, it update the text field and it works fine. My issue is when I add another field\_smart\_objectives and try to change the select value of the first field\_smart\_objectives

`$form['field_smart_objectives']['und'][$maxField]['field_smart_objective_task']['und']['#prefix'] = '<div id="test_entity_callback'.$maxField.'">';`

$maxField should be zero, but it change to 1. Could Anyone tell me why it is happen?

Thank you

# Answer
> 0 votes
I have find a solution. I add this code to ajax function and it solves my issue.

```
$index=0;
    $index= $form_state['triggering_element']['#field_parents'][2];

  return $form['field_smart_objectives']['und'][$index]['field_smart_objective_task'];

```

Thank you

---
Tags: forms
---


title: Libraries API not working in my module

text:
# Question
Title: Libraries API not working in my module
I'm writing a module that will call some external php libraries. When I was searching for a way to import the library I found the Libraries API. After reading some documentation about the module and core features I found some example code.

When I implement it in my module nothing happens. My movies.module file contains:

```
/**
* Implements hook_libraries_info()
**/
function movies_libraries_info()
{

  // This array key lets Libraries API search for 'sites/all/libraries/example'
  // directory, which should contain the entire, original extracted library.
  $libraries['imdb'] = array(
    // Only used in administrative UI of Libraries API.
    'name' => 'imdb',
    'vendor url' => 'https://github.com/tboothman/imdbphp',
    'download url' => 'https://github.com/tboothman/imdbphp/releases',
     // Default list of files of the library to load. Important: Only specify
    // third-party files belonging to the library here, not integration files of
    // your module.
    'files' => array(
      // For PHP libraries, specify include files here, still relative to the
      // library path.
      'php' => array(
        'bootstrap.php',
      ),
    ),
    // Optional: Register files to auto-load for your module. All files must be
    // keyed by module, and follow the syntax of the 'files' property.
    'integration files' => array(
      'movies' => array(
        'php' => array('bootstrap.php'),
      ),
    ),
  );
  return $libraries;
}

```

No errors are thrown when enabling my module when the library is not installed.

How can my module load the external PHP library using the Libraries APi?

# Answer
1. Add a `composer.json` file to your `movies` module & name it your custom module's name:

```
{
  "name": "drupal/movies",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "require": {
    "imdbphp/imdbphp": "*"
  }
}

```
2. Add a new line to the merge-plugin include array in the `composer.json` of your Drupal ROOT with your module's composer file path:

```
"extra": {
  "merge-plugin": {
    "include": [
        "core/composer.json",
        "modules/custom/movies/composer.json"
    ]
  }
}

```
3. Enable the `movies` module
4. Run `composer update` & `composer dumpauto` in Drupal ROOT. This will install & autoload the new dependencies in your vendor directory.
5. Now you can use the classes provided by this library. In your case for example:

```
$title = new \Imdb\Title(335266);

```
> 4 votes

# Answer
You can load libraries from the Libaries API in Drupal 7 in two ways:

1) You can use the function libraries\_load()

2) You can use the #attached method of a render array as follows:

```
$form['myelement']['#attached']['libraries_load'][] = array('my_library');

```
> -3 votes

---
Tags: 8, theming
---


# Question
Title: Selecting taxonomy term in article and showing all articles titles associated with this term
I have a content type article and when editing an article there should be a field where you can select a taxonomy term of a specific vocabulary.

When viewing the article it should show a list of titles of all articles associated with the selected taxonomy term. I know how to make a select field and also a view to show the titles. But how do I send the selected term to the view and how do I display the view in the article?

# Answer
> 6 votes
**1)** Create a **View block**, when you create it use `Show: Content`.

**2)** Under Advanced **Contextual Filters** add `Has taxonomy term ID`

**3)** Select `provide default value` Type: `Taxonomy term ID from URL` (this will automatically grabs the term from your node) If you want, you can limit the terms by vocab.

Even if your tax term reference field is limited to 1, maybe you should set it up as if it was unlimited, in case your client later wants to allow more than 1 value.

Change the **multiple-value handling** option to the 2nd one, share any term.

Scroll down to MORE and check mark allow multiple values.

Click Apply, to save the settings.

---

Now you want to **exclude** the current Article (node) from the list. No point in showing the Article the visitor is already viewing/reading.

**4)** Add another **contextual filter** of `ID`

**5)** `Provide default value` Type: `Content ID from url` (automatically grabs the ID from your node).

**6)** Scroll all the way down, and click on MORE, and check mark `Exclude`.

So your Advanced section should look like this:

---

To place the block in your article, there are several ways.

Go to `admin/structure/block` and click on Place Block, search for your View Block and click on Place Block.

In the configuration, under Visibility settings, select Content Types and check mark your content type.

**Site Note:** There are other ways to insert/place your view:

* Through a template file.
* Using Panels and or Display Suite (Note: I am not 100% sure on this as I have not played much with these modules in D8, in D7 I know you can).

# Answer
> 0 votes
Regarding the placement of the block, I found another interesting thread: How to create a field that references a Views Block display in D8?

So I tried using the modules

1) "Views Reference Fields", so you can add a field to a node to insert a specific view, especially in conjunction with Paragraphs. Unfortunately it didn't show anything on my test site. Also with Paragraphs you have to save the node and reopen before you can select a display of the selected view.

2) "Block field", so you an add a field to a node to insert a block, which can also be a block of a view. It worked for me with and without paragraphs.

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


title: Send form result back to twig

text:
# Question
Title: Send form result back to twig
I created a module for searching values from external databases. My controller creates a form and send it to the custom twig page of my module.

The controller method that creates the form and send the data to the twig template looks like:

```
 public function customSearchPage($query, $results)
    {
         $searchForm = \Drupal::formBuilder()->getForm('Drupal\movies\Form\SearchForm');

        $searchForm['searchQuery']['#value'] = $query;

        return [
            '#theme' => 'insert_movie_page',
            '#form' => $searchForm,
            '#query' => $query,
            '#results' => $results,
        ];
    }

```

Now I created a Form using the Drupal 8 Form API. The submitForm method will send the inserted data to a compute class and gets a resultset back (array with multiple model objects). Now I need to send the resultset back to the twig template to show the results to the users. How can I achieve this behaviour?

SubmitForm method looks like:

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

      $search = $form_state->getValue('searchQuery');

      $SearchController = new SearchController;
      $results = $SearchController->searchMovies($search);
  }

```

# Answer
> 6 votes
In submit you have two choices.

**Rebuild**

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

  $form_state->setRebuild();
}

```

The form and the twig template the form is wrapped in will be rebuilt and you can display the result.

This is a great question from @AdrianCidAlmaguer to demonstrate how this works with a basic example how to display the sum of two numbers: How to show a string once you submit a form in a page reloading the page?

**Redirect**

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

  $form_state->setRedirect($route_name, $route_parameters, $options);
}

```

You redirect to a new page and can display the result there.

---
Tags: 8, forms
---


# Question
Title: How do I calculate the days difference between start and end date of a date range field in Views PHP?
I'm trying to get the total number of days in a date range field using Views PHP. Any help will be greatly appreciated.

I tried the code below first in "value code" then in "output code" but it didn't do anything.

```
$start = strtotime($row->field_start_and_end_date:value);
$stop = strtotime($row->field_start_and_end_date:value2);
$days = $stop-$start;
echo $days;

```

# Answer
Within Views PHP, there are 2 fields. The `value code` field and the `output code` field. The first is used to calculate the value (for filtering, sorting, etc). The second is used to display the value.

So in the first field you'll have to perform your calculations and `return` the final value. If your field is numeric, try to only calculate the number here. Prefixes and suffixes can be added in the output field. (So the value for this field could be `3`.)

In the output field you again have to `return` the final value. This can be the same value as calculated in the value field (there is a token for this value). But you can also append pre- and suffixes and return a string. (Here you can for instance append `days` to the value to have it display `3 days`.)
> 2 votes

---
Tags: datetime
---


# Question
Title: How to allow the user to change the language?
I think I must be missing something here.

I have enabled the multilingual modules and added a language. It all seems to be working with respect to translating content - an admin can easily translate an individual page. However I can't see how to give an anonymous user the ability to change their selected language. I was expecting the multilingual modules to create Blocks that would allow a user to change their default language and which would notify them if a particular page is available in another language. So my questions are:

1) How do I allow an anonymous user to change their preferred language?
2) How do I alert an anonymous user to the fact that a particular page is available in another language?

# Answer
> 5 votes
You can find a detailed answer in step 5 of this guide: 5 Steps to Build a Drupal 8 Multi-lingual Site.

Basically, this is what you need to do:

* Go to Admin \> Structure \> Blocks
* Click "Place blocks" on the desired region
* Click "Place block" next to the "Language Switcher" block
* Click "Save block"
* Go to a translated node and the Language Switcher will be working

As a sidenote mentioned in the comments of that guide: "You also need to have the url method enabled in the detection and selection page."

# Answer
> 2 votes
Regarding your first question, go to detection and selection at /admin/config/regional/language/detection, check the User box, and uncheck the rest. Then save the page. After this, users will be able to edit their profile, and select their language there.

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


# Question
Title: What might block the creation of thumbnails?
My Drupal 8 does not create thumbnail. I have set my files folder's permission to 775 and the folder 2016-10 is not there.

>

There is no error shown in the log, and the temporary directory is /tmp.

# Answer
> 2 votes
Perhaps you need to look for this file: /var/www/httpd-logs/your\_site.com.error.log

So, edit your sites/default/files/.htaccess

```
# Turn off all options we don't need.
#Options -Indexes -ExecCGI -Includes -MultiViews
Options -Indexes -ExecCGI -Includes

```

# Answer
> 1 votes
Please check your php error log, it may show you where the problem come from.

Probably it is related to the settings of temporary directory in configuration \> media \> file system. It can happen if you have no write permission on temporary directory.

---
Tags: 8, media
---


# Question
Title: Write drupal config in a profile installation
Here's my problem: I use profiler builder to generate a profile from an installation. But the fact is : the profile only list my modules.

What I want my profile to do is also to keep my Drupal configuration. For exemple, if I generate the profile of a drupal installation with a WYSIWYG installed and configured, I want the profile to keep this configuration and reload it to new instance (created with the profile).

Is it possible ? Thanks.

# Answer
Many configuration elements can be exported and imported using Features module.

> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

Problem is that it only accepts modules that exports their configurations with Chaos tools style, so you can't export blocks, but can export boxes, and so on. Wysiwyg has currently ctools commented out from it's requirements, so you will need to see if it can be exported or not, at it's current stage of development.

If configuration is kept in system variables, you could consider using Strongarm:

> Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.

As Clive pointed out, there is also Configuration Management module:

> For the most part this module provides the same functionality as a subset of the features module.

The main difference is - it packs only configuration, is smaller and easier to handle, and was written explicitly to deal with *"the shortcomings of using features module for configuration management"*. Still, you are moving whole page, so features with their broader goal might be the way. Your choice.

In all other cases you need to figure out how module stores it's configuration and data, and interact directly with database from your installation profile.
> 2 votes

# Answer
I) As mentioned before, you can use Features module, this is what I'm doing now. I have packed some configurations into a submodule of my profile which I enable automatically by declaring it as a dependency.

II) A second option is this one mentioned in Drupal.org: https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

In Configuration paragraph:

> Drupal 8 installation profiles can contain configuration files. You can start by taking the configuration directory (config folder) of an installed, configured site and copying it into the config/install folder in your profile.
>
> Once that's in place, there are some other required tasks (...)
>
> If you just want to grab an existing site's configuration, and don't need to end up with a formal installation profile (...), you can use the Configuration Installer installation profile to install a new site from the configuration of another site.
> 0 votes

---
Tags: installation-profiles
---


# Question
Title: How do I prevent rewritten views field output from having ":" stripped out of the <img> sizes attribute?
I'm working on advanced responsive images in a Drupal 8 view, designed to suggest showing different images at various screen sizes around the Bootstrap theme.

Is there a way I can prevent everything up to the ":" from being stripped/filtered out in my views field output sizes attribute?

My views field rewrite looks like this:

```
<img src="{{ field_product_images }}"
srcset="{{ field_product_images }} 735w,{{ field_product_images_1 }} 343w,{{ field_product_images_2 }} 210w,{{ field_product_images_3 }} 260w"
alt="{{ field_product_images_4 }}"
sizes="(min-width: 0px) 100vw, (min-width: 769px) 50vw, (min-width: 993px) 25vw"
class="img-responsive">

```

It renders for the most part. However, the resulting html looks like this:

```
<img src="/sites/default/files/styles/product_listing_lg/public/products/2017-01/IMG_0196.JPG?itok=pUdgY8n9"
srcset="/sites/default/files/styles/product_listing_lg/public/products/2017-01/IMG_0196.JPG?itok=pUdgY8n9 1w,/sites/default/files/styles/product_listing_md/public/products/2017-01/IMG_0196.JPG?itok=t7jNSmMk 769w,/sites/default/files/styles/product_listing_sm/public/products/2017-01/IMG_0196.JPG?itok=NH8p7qki 993w,/sites/default/files/styles/product_listing_xs/public/products/2017-01/IMG_0196.JPG?itok=feCEjmRl 1201w"
alt="black and gold variegated infinity scarf (wrapped, front)"
sizes=" 993px) 25vw"
class="img-responsive">

```

sizes attribute in rewrite:

```
sizes="(min-width: 0px) 100vw, (min-width: 769px) 50vw, (min-width: 993px) 25vw"

```

sizes attribute output:

```
sizes=" 993px) 25vw"

```

I seem to have the same challenge whether I'm rewriting an image field or specifying replacement patterns in a global text area.

I haven't explored any preprocess or twig template options yet. Is this something I need to resolve outside of views UI to prevent the filtering? What's the best way to proceed?

# Answer
Based on No Sssweat's comment suggestion, I was able to work out a views field template in my custom theme to resolve this question. As I used the twig tweak module to help apply multiple image styles in node templates, I also used it in my views field template in a similar way.

In views-view-field--\[view id\]--\[display id\]--\[field id\].html.twig (or views-view-field--products--page-1--nothing-2.html.twig in my case):

```
{#
/**
 * @file
 * Default theme implementation for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 *
 * @ingroup themeable
 */
#}
{% set href = path('entity.node.canonical', {'node': row._entity.id}) %}
{% set image = row._entity.field_product_images[0] %}
{% set product_listing_xs = image.entity.uri.value|image_style('product_listing_xs') %} {# requires twig tweak module #}
{% set product_listing_sm = image.entity.uri.value|image_style('product_listing_sm') %} {# requires twig tweak module #}
{% set product_listing_md = image.entity.uri.value|image_style('product_listing_md') %} {# requires twig tweak module #}
{% set product_listing_lg = image.entity.uri.value|image_style('product_listing_lg') %} {# requires twig tweak module #}
<a href="{{ href }}"><img src="{{ product_listing_lg }}" srcset="{{ product_listing_xs }} 735w,{{ product_listing_sm }} 343w,{{ product_listing_md }} 210w,{{ product_listing_lg }} 260w" sizes="(min-width: 0px) 100vw, (min-width: 769px) 50vw, (min-width: 993px) 25vw" alt="{{ image.alt }}" class="img-responsive"></a>

```

No ":" or other items were stripped from the final output.

As a result of the field template, I was also able to remove six hidden field items in the views settings that were used in the rewrite this template now handles.
> 2 votes

---
Tags: views, 8, entities
---


title: Using argument in title

text:
# Question
Title: Using argument in title
I am using a contextual filter for a view in Drupal 8. The contextual filter is a Taxonomy Term: name filter with a term relationship. It works correctly.

I'm now trying to override the title using this filter. In previous versions of Drupal, using %1 would have given me the argument. But not in Drupal 8. Is there a way to either get the argument or (even better) the term name into the title override?

# Answer
> or (even better) the term name into the title override?

1) Add `Taxonomy term: Name` as a field

* Check `Exclude from display`
* Uncheck `Link this field to its taxonomy term page`

2) Click on *Title:* and put `{{ name }}`
> 4 votes

---
Tags: 8, views
---


# Question
Title: Replace node tabs with user tabs on website
Unlike the author of https://stackoverflow.com/questions/3530756/how-to-hide-edit-view-tabs I'd like to totally replace node tabs with what users see on their user profile pages.

Users on this website won't be able to edit their nodes and admins can just type `node/%/edit` or be provided with a link on special block, so node tabs are useless for this project, but user tabs are essential as there are no community nodes, users are locked to their accounts and need to see all their nodes under user accounts.

I tried to use the hook\_menu\_local\_tasks\_alter, it correctly adds new tab items, but I don't know how to get rid of the existing ones. I tried to hide them with Tabtamer module, but unfortunately it gives:

```
Notice: Undefined index: count in menu_primary_local_tasks() (line 2240 of ../includes/menu.inc).

```

Thus the existing items must exists, so instead of adding new individual items with hook\_menu\_local\_tasks\_alter, I would like to just check `if arg(0) == 'node'` then replace the node tabs totally with what users usually see on their profile pages.

How could I totally replace node tabs with user tabs on node pages?

# Answer
> 2 votes
For Drupal 7, you should be able to do the following:

1) Implement hook\_menu(), and define new tabs as local tasks on the node path.

2) Set the callback for these tabs to redirect to the relevant user pages

3) Implement hook\_menu\_alter() to remove the tabs from the node pages.

## Step 1: Implement hook\_menu(), and define new tabs as local tasks on the node path.

```
function hook_menu()
{
  $menu['node/%node/user_view'] = array
  (
    'title' => 'View',
    'page callback' => 'node_user_redirect',
    'page arguments' => array('view'),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
  );

  $menu['node/%node/user_edit'] = array
  (
    'title' => 'Edit',
    'page callback' => 'node_user_redirect',
    'page arguments' => array('edit'),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
  );

  return $menu;
}

```

## Step 2: Set the callback for these tabs to redirect to the relevant user pages

```
function node_user_redirect($type)
{
  global $user;

  drupal_goto('user/' . $user->uid . '/' . $type);
}

```

## Step 3: Implement hook\_menu\_alter() to remove the tabs from the node pages.

```
function hook_menu_alter(&$menu)
{
  // Remove the view tab altogether
  unset($menu['node/%node/view']);
  // Set the edit page to not present a tab on node pages
  $menu['node/%node/edit']['#type'] = MENU_CALLBACK;
}

```

# Answer
> 0 votes
Sometimes so obvious solutions do not appear at once to average minds like mine ;) I just had to run check `if (arg(0) == 'admin' || arg(0) != 'node') { return; }` in my hook and everything works just as expected - I can add user tabs to nodes tabs.

---
Tags: 7, nodes, users, navigation
---


title: Theme twig files front page is empty

text:
# Question
Title: Theme twig files front page is empty
I am trying to build a custom theme in drupal. I have two page files:

```
page.html.twig
page--front.html.twig

```

both files have the same code:

```
<div class="container">
    {{ page.myheader }}
    <div class="row">
        <div class="col-md-3">
            {{ page.sitebrand }}
        </div>
        <div class="col-md-6">
        </div>
        <div class="col-md-3">

```

The Problem: I see the blocks in all the pages except the front page.

by the way: I did set my front page as this:  I created a simple page with 'front' alias.

Is this cousing a problem?

The question: What am I doing wrong? How can make different display in the front page?

full `page--front.html.twig`

```
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<div class="container">
    {{ page.myheader }}
    <div class="row">
        <div class="col-md-3">
            {{ page.sitebrand }}
        </div>
        <div class="col-md-6">
        </div>
        <div class="col-md-3">

xxx dagfv

            <button type="button" class="btn btn-lg btn-block">
                Default
            </button>
            <div class="btn-group">

                <button class="btn btn-default">
                    Action
                </button>
                <button data-toggle="dropdown" class="btn btn-default dropdown-toggle">
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li>
                        <a href="#">Action</a>
                    </li>
                    <li class="disabled">
                        <a href="#">Another action</a>
                    </li>
                    <li class="divider">
                    </li>
                    <li>
                        <a href="#">Something else here</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <nav class="navbar navbar-default" role="navigation">
                {{ page.mainmenu }}
            </nav>
        </div>
    </div>

    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-9">

        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
        </div>
        <div class="col-md-2">
        </div>
        <div class="col-md-2">
        </div>
        <div class="col-md-6">
        </div>
    </div>

    <div>
        {{ page.content }}
    </div>
</div>
</body>
</html>

```

# Answer
> 0 votes
You have two problem.

1. page--front.html.twig is special suggestion template for front page. Any url set to front page always use this template =\> You don't need set alias for this.Just set page you want to front page.
2. Don't add html tag to page template. The tree of template is html=\>page=\>region=\>block... Html tag exited in template html.html.twig.

And more you can setting twig debug to see current home page use template?

---
Tags: 8, theming
---


# Question
Title: Textarea for Drupal 8 text fields content types
Currently there is no option to select textarea as a widget for a *long* text field in a content type. What solutions are there? And why was this removed as this was in core Drupal 7.

# Answer
A long textfield is a textarea by default, there's no need to explicity configure it as such. For example here I created a textfield with label "Text" as `plain, long`:

And this is how it looks in the `node/add` page:
> 5 votes

---
Tags: 8, entities
---


title: Removing nodes using Feeds module

text:
# Question
Title: Removing nodes using Feeds module
I am using Feeds module (7.x-2.0-alpha8) to create nodes with CSV import.

Currently following patch Unpublish/Delete nodes not included in feed only provides the feature where if the entry is not there in the feed than delete the corresponding node.

However the above requirement doesn't seems to solve my problem. Following is my requirement

Under the CSV file I have one column called **Delete**, which stores Boolean value. If the entry has to be deleted than the value is 1 otherwise 0.

I wonder how it can be resolved. Any suggestions?

# Answer
You could use a hook that checks for this field (which you'd have to add to the content type that you're importing into) then delete the node if its set to 1. In order for this to work you would need to specify a field as unique otherwise feeds wouldn't know what item that already exists is to be deleted.
> 1 votes

# Answer
There is one thing you can do that doesn't require writing a custom module: map your `Delete` column with a custom field, and then use VBO to select all nodes with that `field == 1` and delete them.

If you don't want to create an extra field, you can use the default `Published status` field:

You'll need to change the value of the `Delete` column in your CSV to '0' for status Unpublished and '1' for Published. Use VBO to select all Unpublihsed nodes, and delete them.
> 1 votes

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


# Question
Title: How can we override view field template in drupal 8
How can we override single field from Views template files '`views-view-field.html.twig`' from location `themes/theme-name/templates/views/views-view-field.html.twig`.

# Answer
There is a detailed answer in this Q: Overriding views-view-field.html.twig for specific fields.

You can simply use `views-view-field--fieldname.html.twig`. Of course, don't forget to clear your cache after creating the new template.
> 4 votes

---
Tags: views, 8, entities
---


# Question
Title: Regular Drupal 7 site users do not see new tabs added by hook_menu_local_tasks_alter
I used hook\_menu\_local\_tasks\_alter to add new tab items for node pages like so:

```
function custom_module_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if (arg(0) == 'admin' || arg(0) != 'node') { return; }

  $href='user/'.arg(1).'/hobbies';
  $data['tabs'][0]['output'][] = array(
    '#theme' => 'menu_local_task',
    '#link' => array(
      'title' => t('Hobbies'),
      'href' => $href,
    ),
  );
  $href='user/'.arg(1).'/events';
  $data['tabs'][0]['output'][] = array(
    '#theme' => 'menu_local_task',
    '#link' => array(
      'title' => t('Events'),
      'href' => $href,
    ),
  );

```

However while admin can see the new tabs, regular users (Drupal 7) do not. Adding `'#access' => TRUE,` to item array does not help as hook\_menu\_local\_tasks\_alter doesn't have options for access argument.

And they appear normally if users are given node edit permission.

How can I make access to these new tabs without giving users permission to edit their nodes?

# Answer
> 0 votes
You have to use hook\_permission

So in your module file something like this will do the job. (taken from the hook's page).

```
function hook_permission() {
 return array(
  'administer my module' => array(
  'title' => t('Administer my module'),
  'description' => t('Perform administration tasks for my module.'),
  ),
 );
}

```

When you do that you will get a new entry in your permissions page (admin/people/permissions). Enable that for the anonymous users and it will show up ok.

---
Tags: nodes, users
---


# Question
Title: Filtering part of a multi-value field in a specific view
I have an entity with fields that allow an unlimited number of values.

In a view, I would like to display a subset of those values that match a particular condition (eg. numbers less than n, dates in the past, etc.)

From investigation, it seems that a field formatter plugin is not a good way to solve this. Sure, I can extend DateTimeFormatterBase and override ::viewElements(FieldItemListInterface $items) to apply my condition, but at the price of being able to choose an actual field formatter. The custom plugin would have to take over the rendering too.

On the other hand, the Field plugin in views has some very limited options for limiting multiple values (by picking an offset and a count), but that doesn't seem extendable with a custom plugin.

Am I going to have to hook into the view after query execution to strip out the values that don't match the condition, or is there a cleaner way using the plugin API?

Edit: I suppose I could create a field formatter plugin that contains an option for selecting an *actual* formatter, and then passes the values that should be displayed on to it. This seems very roundabout, though. And this logic would have to be reimplemented for each field type!

# Answer
In order to have full power over the filtering and sort order of the field inside each item, the best solution appears to be a sub-view using the views\_field\_view module.

https://drupal.org/project/views\_field\_view

1. Create a view that only shows the desired field (without a page display)
2. Add a contextual filter for the entity ID to be displayed
3. Add this to the parent view, setting the contextual filter to the entity ID of the current item.
> 1 votes

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


# Question
Title: Override image dimensions set by image style
I am trying to override the image dimensions set out by image style and can't seem to do that unless I select no image style for the field. I need that image style on another pages but I would like to override it only on the front page. The images the front page are from nodes loaded from simple view configuration. I tried `theme_image_style` to override the dimensions but it stops images from rendering on other pages. I tried `theme_preprocess_node` and even though the `image['width']` and `[height]` were changed it still loaded the image style dimension. Would really appreciate some help thank you.

# Answer
> 0 votes
The looked around images styles and this works for me so far, although it is not working on a custom image style I created, however it could be I have some configuration issues so I believe it should be work.

I created a renderable array on the node view template file.

```
//Loading the image field from the node object
$image_field = field_get_items('node',$node,'field_image');
$image_item = array(
'style_name' => 'my_medium_style',
'path' => $image_field[0]['uri'],
'width' => '',
'height' => '',
'alt' => $image_field[0]['alt'], // optional
'title' => $image_field[0]['title'], // optional
);
print theme('image_style',$image_item);

```

Although I am pretty sure there are better solutions, but for now I would like to mark this as the closest solution.

# Answer
> 1 votes
You could alter the width and height properties of your image(s) using CSS, it depends on the (base) theme you use in which file these CSS rules should be entered. However, the image produced by the image style is still used (so, this might not be quite mobile friendly).

Another option is to use the Image Style Selector (ISS) module, which provides an extra field on your node edit page that you can use to select an extra image style (to apply on the image on for instance your front page). When displaying the node on the front page you can hide the original image field and display the ISS field (the result is that your image will be shown using the style selected in the ISS field).

---
Tags: 7, theming, media
---


title: How do I get the form field value?

text:
# Question
Title: How do I get the form field value?
The question is clear from the title itself :

I have tried :

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
          $form_state->getValue('field_p_fqdn');
          $form['field_p_fqdn']['und']['#default_value'];
}

```

where **`field_p_fqdn`** is my field name .But both didnt worked . Any idea ??

# Answer
Depending the field type, it could be:

For exemple for plain text:

```
$form['field_p_cert_fqdn']['widget'][0]['value']['#default_value']

```

or

```
$form['field_p_cert_fqdn']['widget'][0]['#default_value'];

```

or

```
$form['field_p_cert_fqdn']['widget']['#default_value'][0];

```

or for entity reference:

```
$form['field_p_cert_fqdn']['widget'][0]['target_id']['#default_value'];

```

or some other thing

I would recommend you to use the devel module: https://www.drupal.org/project/devel (with the kint submodule enable). With this, you can add

```
dpm($form);

```

in you alter function to get the structure of the $form.
> 2 votes

---
Tags: forms
---


title: How do I import a module?

text:
# Question
Title: How do I import a module?
I am working on Drupal 8 and I have migrated my Drupal 7 website to Drupal 8 using the *Migrate Upgrade* module, but none of the modules is imported from my previous Drupal 7 site.

How do I import modules from Drupal 7 to Drupal 8 without using Drush commands? I'm not much familiar with Drush.

I have seen the article in which a process is given to import modules using *Drupal Module Upgrader*, but it's based on Drush.

Is there any simple method to port Drupal 7 modules to Drupal 8?

# Answer
> 3 votes
Perhaps, your question in **bold** needs to be reworded to `Is there any simple method to port D7 modules to D8?` Which is what you're really after.

**If you are referring to CUSTOM modules (not drupal.org contrib modules)** then the fastest / most simple way is to use Drupal Module Upgrader which you mentioned in your question. In module page they show you a video with all the steps.

There is no reason to be afraid of Drush. As a Drupal newbie, Drush can seem scary/daunting, I used to avoid it too, but once you learn Drush, which is not hard, you will discover that is super useful and a time saver. You will wish you learned it earlier.

It is important to note that while the Drupal Module Upgrader will port/rewrite some of the code, some of the code may not (depends on how complex your module is) and you will have to manually modify/rewrite certain parts by hand.

Other than using Drupal Module Upgrader, there is no other choice, but to manually re-write your entire module.

**If you are referring to Drupal.org Contrib Modules** then you will need to download the D8 version, if there is one.

# Answer
> 2 votes
You cannot.

There is a significant difference between the architecture of Drupal 7 and 8 modules, so they cannot be migrated. You'll have to reinstall them in your new site.

It might be that some of those modules (after installing) allow migration of settings. So it would be better to attempt the migration after installing all modules.

---
Tags: 8
---


# Question
Title: Can I Search an entity reference with search api db?
I am using the search api database backend together with a views (with exposed fulltext search field). I want to show a 'related field' that is related to a content type that is being indexed. When the entity reference field only holds 1 value, all is fine.

But when it holds unlimited values (in the field settings) it no longer works in the view :-(

Does search api db have a limitation on indexing multivalued fields?

**UPDATE**

My content types are as follows:

* Content type a

+ Field\_a = text
    + Field\_b = entity ref to content type b (allowed values unlimited!)
* Content type b

+ Field 1 = text
    + Field 2 = text

I have indexed all fields above and added the related fields 1 and 2 to my search index as related fields.

Then when i create a view that shows the indexed nodes for content type a, and want to show field 2's information of the node that is referenced it only works when field b is set to allowed values: 1

# Answer
SearchAPI does have this limitation: Note: This is a multi-valued relationship, which is currently not supported. Only the first related entity will be shown.

Here is the issue about this. https://www.drupal.org/node/1378656
> 0 votes

# Answer
> Does search api db have a limitation on indexing multivalued fields?

**NO**

Search Api DB & Solr allows you to indexing multivalued fields. You probably did not see the changes because you did not re-index your index.

**Edit:** To answer your question base on the comment below. My answer still **NO** does not have limitation on indexing entity reference.

> Can I Search an entity reference with search api db?

**Yes**

And here is an article that wunderkraut posted based on Entity Reference.

> **Benefits of Entity Reference:** Can reference any type of entity. Easy to implement – follows same patterns as Node/User reference. Has Views integration, even for reverse relationships. Has Entity API integration, **so it works well with Search API** and Rules.
> -1 votes

---
Tags: views, search
---


# Question
Title: Set Value to a select field by its key in webform
I'm trying to set a select field to one specific default value by it's key (one country, which i retrieve from another form), and then disable the field.

I implement hook\_form\_alter, i get the correct field inside the $form array, but, when i want to set the select field to one value, nothing happens. I'm trying this way:

```
 $form['#node']->webform['component'][91]['value']['#default_value'] = $country;

```

But, this does not work. Any guess on how i can achieved this, and if this is possible or the right way to do it?

Thanks

# Answer
> 0 votes
This is the way I do it and it works:

```
// set default value to a D7 form field
$form['FIELD_NAME']['und'][0]['value'] = $country;

// prevent user from changing the field value
$form['FIELD_NAME']['#access'] = false;

```

Hope this helps.

---
Tags: 7, webforms
---


# Question
Title: How to prevent userpoints from repeating
I need to grant points to users for updating their user profile with licensing info about their company. Right now I have the following rule:

```
Event: After updating an existing user account

Add event: NOT Data value is empty
Parameter: Data to check: [site:current-user:field_licensing]

Action:Grant reputation to a user
Parameter: User: [site:current-user], Reputation: 25, Reputation category: Reputation,
Operation: Insert, Moderate: Automatically approved

```

How can I stop Rules from adding points each time the user updates their profile? Since the rule checks if the field is not empty it currently awards 25 points with each update. How can I get Rules to check if the profile update added value for the field\_licensing, or merely updated the profile and field\_licensing has the same value?

# Answer
> 1 votes
You could put a field on the User entity called something like `field_points_attributed` and hide it from the authenticated users using Field Permissions.

Then set an action on your rule, so that as well as adding the user points, it also changes the value in the field to something like "yes" or "attributed".

Lastly, add a condition to check the value of that field, and ensure it doesn't say "yes" or "attributed".

# Answer
> 1 votes
Another solution is to use the Flag module and create a (global) flag with the purpose to flag users when they are awarded those 25 points.

Then extend your existing rule like so:

* Add an extra Rules Action to flag the user.
* Add an extra Rules Condition to check that the user has not been flagged (by this flag).

That's really it.

---
Tags: 7, userpoints
---


# Question
Title: Cannot change logo or colors of a scheme
Hello I use Open Atrium based on Drupal. I can use the standard Radix 7.x theme, but even with that I cannot change the color scheme by saving it via Colorize. If I then use another theme I cannot even get the logo to display or any submenu to appear. I am not sure if it is a question of permissions. The site is installed on a VM as part of a webmin set up. I have seem very nice sites in both Drupal and OA so I am sure I should be able to customize my site, but it just does not work. The colorize shows the result on Radix, but as soon as I save it it forgets it. In my experience this might either mean that the path to the new colors (CSS?) is not valid, reachable or has the wrong permissions. DO you have any idea of what I can try? I need nothing fancy, but I'd like to customize the logo and colours and have all the Radix menus in another there, e.g. Bartik....Thanks in advance for any help you can give me. Please note I am not a programmer...if you advise me to change something in the code I can do it but you have to give me the full instructions. Thank you so much. regards Enea

# Answer
> 1 votes
I'd check the folder/file permissions set on the "public files" folder for Drupal, especially the sub-folders (css, js, color) because if those aren't set right then the Color module can't write changes for custom CSS and logo uploads.

# Answer
> 0 votes
Check your permissions on the `sites/default/files` folder.

* The logo will be uploaded as `sites/default/files/yourlogo.png`
* The color will be uploaded as `sites/default/files/color`

You can check the permissions of this folder at `admin/reports/status`. Check the `File system` option. If it's not writable, you will see the following message:

> The directory sites/default/files is not writable.

You can adjust this setting at `admin/config/media/file-system`.

---
Tags: theming
---


title: Convert http to https on save

text:
# Question
Title: Convert http to https on save
While migrating our site, we have put them on 'SSL required'.

How can we best force, when editors save datas containing http link, a conversion to https ( or //).

# Answer
> 0 votes
i did a module with a custom text format filter :

```
function my_module_filter_info() {
   $filters ['to_https_compatible_converter'] = array (
        'title' => t ( 'HTTPS compatible convertible filter' ),
        'description' => t ( 'convert http:// to // for https  compatiblity' ),
        'process callback' => '_module_filter_process',
        'tips callback' => '_module_filter_tips'
   );
  return $filters;
 }

 function _module_filter_tips($filter, $format, $long = FALSE) {
switch ($filter->name) {
    case 'to_https_compatible_converter' :
        return t ( 'convert http:// to // for https  compatiblity' );
}
    }

  function _module_filter_process($text, $filter) {
      switch ($filter->name) {
    case 'to_https_compatible_converter' :

        $dom = new DOMDocument ();
        @$dom->loadHTML ( utf8_decode ( $text ) );

        $images = $dom->getElementsByTagName ( 'img' );
        foreach ( $images as $image ) {
            $image_src = $image->getAttribute ( 'src' );
            $image_src=str_replace(['http://','https://'],'//',$image_src);
            $image->setAttribute ( 'src' ,$image_src);

        }

        $links = $dom->getElementsByTagName ( 'a' );
        foreach ( $links as $link ) {
            $href = $link->getAttribute ( 'href' );
            $href=str_replace(['http://','https://'],'//',$href);
            $link->setAttribute ( 'href' ,$href);

        }

        $iframes = $dom->getElementsByTagName ( 'iframe' );
        foreach ( $iframes as $iframe ) {
            $src = $iframe->getAttribute ( 'src' );
            $src=str_replace(['http://','https://'],'//',$src);
            $iframe->setAttribute ( 'src' ,$src);
        }

        return $dom->saveHTML ();

}
 }

```

---
Tags: hooks, input-formats, ssl
---


title: Integrate TinyMCE

text:
# Question
Title: Integrate TinyMCE
I need to install Tinymce in Drupal 8 as default text editor.

I have searched for a solution but there is no much information.

I have deduced that the 'old' module wysywig (an RTE's manage module) is now called Text Editor, and within it, there is the CKEditor.

I can't find the way to make Tinymce works on Text Editor as is CKEditor at the moment.

I have tried to put the module files in `webroot/libraries/tinymce`, in `webroot/modules/contrib/tinymce` and even in `webroot/core/modules/tinymce` but it doesn't be displayed in the `Extend` tab as module.

After that, reading more articles I have supposed that it comes built-in with this module (Text Editor ~ former Wysiwyg) but I can't enable it in no way.

Can anyone help me?

# Answer
> 1 votes
As far as I know no one has integrated other editors as tight as CKEditor is in core.

The Editor module in the core is the 'new'/similar module to WYSIWYG from Drupal 7. It's API needs to be utilized to integrate your editor of choice to Drupal. It isn't just a matter of copying and pasting editor packages into a folder. You have to wire it up to Drupal.

It all starts at `core/modules/ckeditor/src/Plugin/Editor/CKEditor.php` where the `EditorBase` class is extended.

https://api.drupal.org/api/drupal/core!modules!editor!src!Plugin!EditorBase.php/class/EditorBase/8.2.x

See the API for more:

https://api.drupal.org/api/drupal/core%21modules%21editor%21src%21Annotation%21Editor.php/class/Editor/8.2.x

It is likely just easier to use CKEditor unless there is some specific functionality TinyMCE does that CKEditor does not.

---
Tags: 8, wysiwyg
---


title: Make my session non persistent

text:
# Question
Title: Make my session non persistent
I created a function to save the location (city, lat, long) of the user. So when he change the page, I don't need to convert his location again. So I've a problem. The session might be saved because when I close my computer, go to another place and reopen the page, my old location is still saved. How I can forget the location of the user when he leave my website ?

Here is a code example for how I store the user location :

```
function user_location_update($args) {
    drupal_session_start();
    if (isset($_GET['lat']) && isset($_GET['lng'])) {
        $_SESSION['user-location'] = array(
            'lat' => $_GET['lat'],
            'lng' => $_GET['lng'],
            'city' => $_GET['city'],
        );
    } else {
        $_SESSION['user-location'] = array(
            'city' => $_GET['city'],
        );
    }
}

```

Then here is an example how I use my data (I send them to JS by settings) :

```
drupal_add_js(array('userlocation' => (isset($_SESSION['user-location']) ? $_SESSION['user-location'] : array())), 'setting');

```

# Answer
> 1 votes
This is the best advice: https://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php

To put it in a Drupal context, you'd have to add a new column to the user table that tracked the last time a user was active and check that on a user hook.

# Answer
> 0 votes
It somewhat depends on your requirements... Drupal also controls sessions, but clearing that will for the user to login again. If that is no problem for you, you could consider changing Drupal's `settings.php` file and change `ini_set('session.gc_maxlifetime', 200000);`.

These 200000 seconds are about 23 days. If you would lower that to be 1800 (30\*60 seconds) it would last for half an hour.

From settings.php:

```
/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

```

If you want to clear the location, but keep the user logged in, you need to do implement a custom check.

A simple way to check this would be to add a timestamp in the session, and compare that every page load.

```
if ($_SESSION['user-location']['last-time'] < time() - 1800) { // Session older than 30 minutes
  // Recalculate location.
}
$_SESSION['user-location']['last-time'] = time(); // Update last accessed time.

```

---
Tags: 7, sessions
---


# Question
Title: Need CKEditor to encode special characters
I would like CKEditor to encode all special characters. Currently it only html escapes \>, \<, and & I believe.

I need the current **html markup** of this

`Let's take a "ride!"`

to become *something* like this

`Let’s take a “ride!”`

In this situation, the `Let's take a "ride!"` is still what would display to the user, but the html should reflect the encoding so my styling is properly applied.

I am seeing that Drupal 7 had a config.js file that could be modified to accommodate this; however, Drupal 8 does not have this by default and does not seem to recognize it when one is created.

Does anyone know how I can make this happen?

EDIT: our content authors are using the Basic HTML editor permissions.

# Answer
A clean solution would be to alter your twig template to include escape. There are plenty of examples in that guide.
> 0 votes

---
Tags: 8, wysiwyg
---


title: How do I pass a URL to a route?

text:
# Question
Title: How do I pass a URL to a route?
I need to send the URL of a Drupal 8 route to a template. I read some documentation on Drupal API, but when I implement this in my module, nothing happens.

My route in my routing file looks like the following.

```
movies.addMovie:
    path: /movies/add/{system}/{id}
    defaults:
        _controller: 'Drupal\movies\Controller\InsertController:addMovie'
        _title: 'Add Movie'
        system: ''
        id: ''
    requirements:
        _permission: 'create movies_movie'

```

This is the code I am using to get the URL from the route.

```
use Drupal\Core\Url;
Url::fromRoute('movies.addMovie')

```

When I put the URL in a variable, the code stops when calling `Url::fromRoute()`. Can someone tell me what I'm doing wrong?

# Answer
> 1 votes
Found a way to generate the url of my route using twig template.

I'm now using the url function of twig to generate the full url to my page:

```
{{ url('movies.addMovie')}}

```

# Answer
> 2 votes
should be: `InsertController::addMovie`

Needs a double-colon. Yours is single.

---
Tags: 8, routes, uri
---


title: How do I import a view?

text:
# Question
Title: How do I import a view?
Recently, I migrated Drupal 7 to Drupal 8 using the Migrate upgrade module, but the views aren't migrated.

Is there any method to import views from Drupal 7 to Drupal 8?

# Answer
> 2 votes
Unfortunately there is no upgrade path for views from D6/D7 to D8 and plans for this in core are postponed.

See the latest comment for this issue https://www.drupal.org/node/2500547#comment-11402389. There is a contrib project mentioned, but this is at very early stage.

# Answer
> 1 votes
There is a project named Views Tools that maybe will help you, I didn't test it, but here is the description of it (from its project page):

> Views Tools is very useful and comes handy with the following features:
>
> **Drupal 7 Release Features:**
>
> 1: View display(s) can be exported (same like you export a view).
>
> 2: View display(s) can be saved as new View.
>
> 3: Displays can be deleted without loading the whole view.
>
> To use this goto Structure \>\> Views Tools.
>
> **Drupal 8 Release Features:**
>
> 1: Backup of a View(export a single view to YAML).
>
> 2: View display(s) can be exported to a new view.
>
> 3: View display(s) can be saved as new View.
>
> 4: Displays can be deleted without loading the whole view.
>
> To use this goto Structure \>\> Views Tools.

---
Tags: views, 8
---


# Question
Title: drupal2dupal migration add a default taxonomy term
I want all of my imported data to have a default taxonomy term, since the source doesnt have this taxonomy term . I have adde the tid of the taxonomy term in the UI as attached, but the content is being imported without this taxonoy term . What am i doing wrong?

# Answer
> 1 votes
I was able to do it by typing in the name of the Taxonomy term , not the tid next to the field i wanted to import

---
Tags: 7, migrations
---


# Question
Title: Open Menu Link In New Browser Tab/Window
I am having a problem with opening a menu link defined in a `module.links.menu.yml` in a new browser tab or window. Code for the link:

```
mymodule.mm_google:
  url: 'https://google.com/'
  parent: mymodule.admin_mm.external_index
  description: 'Search Engine'
  title: 'Google'
  options:
    attributes:
      target: _blank

```

I am working with Drupal core 8.2.4 8.2.5 and the link currently works **except** for opening a new browser tab or window.

**Update**:
The links are opening in a new tab/window when rendered by the Toolbar/Admin Toolbar modules but not when rendered and displayed by admin overview controller `\Drupal\system\Controller\SystemController::overview`. The controller will also not render included classes for the anchor element.

# Answer
Doing a review of how `\Drupal\system\Controller\SystemController::overview` builds an Admin Overview page and I found that `template_preprocess_admin_block_content` was only constructing each link item as an array values that did not include a URL object. While menus built by the admin Toolbar did. The importance of the URL (Drupal\Core\Url) instance being generated is that it includes an Attributes (Drupal\Core\Template\Attribute) instance that Twig can use to render an item's HTML attributes.

**The fix**:

The `template_preprocess_admin_block_content` function can be located in a custom module but, there is the requirement to add an overriding template file in the admin theme so it is best to locate the function a custom admin theme. (It is important that you remember the difference between your front-end theme and your admin theme as they are not the same)

/themes/myadmintheme/myadmintheme.theme

```
/**
 * Implements template_preprocess_admin_block_content().
 */
function myadmintheme_preprocess_admin_block_content(&$variables) {
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $key => $item) {
      $variables['content'][$key]['attributes'] = new Attribute(empty($item['options']['attributes']) ? array() : $item['options']['attributes']);
    }
  }
}

```

/themes/myadmintheme/templates/admin-block-content.html.twig

```
{#
/**
 * @file
 * My admin theme implementation for the content of an administrative block.
 *
 * Uses unordered list markup in both compact and extended modes.
 *
 * Available variables:
 * - content: List of administrative menu items. Each menu item contains:
 *   - url: Path to the admin section.
 *   - title: Short name of the section.
 *   - description: Description of the administrative menu item.
 *   - attributes: HTML attributes of the administrative menu item.
 * - attributes: HTML attributes to be added to the element.
 * - compact: Boolean indicating whether compact mode is turned on or not.
 *
 * @see template_preprocess_admin_block_content()
 * @see seven_preprocess_admin_block_content()
 * @see myadmintheme_preprocess_admin_block_content()
 */
#}
{%
  set classes = [
    'admin-list',
    compact ? 'compact',
  ]
%}
{% if content %}
  <ul{{ attributes.addClass(classes) }}>
    {% for item in content %}
      <li><a href="{{ item.url }}"{{ item.attributes }}><span class="label">{{ item.title }}</span><div class="description">{{ item.description }}</div></a></li>
    {% endfor %}
  </ul>
{% endif %}

```

In the example code here the theme My Admin Theme (/themes/myadmintheme) is a child theme of Drupal's default admin theme Seven.
> 0 votes

---
Tags: theming, 8, routes, navigation
---


title: Export only non-default config

text:
# Question
Title: Export only non-default config
`drush config-export` dumps my entire site config into files.

What I want is to only export config which is non-default.

ie. if I haven't changed my "automated cron settings" since installing my Drupal site, leave it out of my config.

Is this possible with drush? Some other tool?

# Answer
> 2 votes
Such a concept doesn't really exist in the config system. There is no overridden status like in cools/entity exports in 7.x.

Default config is only default config as long as it is a file in config/install. Once it is installed, it just is your configuration, there isn't really a connection anymore to the original default config file.

There is a hash in those files, so you could technically write something that looks for the default config file and compares the hash or even compare every single value. But keep in mind that default config can actually change, deciding whether you'd want your unchanged existing value or the new default is something that is surprisingly hard to do.

Not sure what you would want this for, the only thing that I can think of would be config for an install profile.

---
Tags: 8, configuration
---


# Question
Title: Remove default configuration on uninstalling module
During install we create content types, field storages and vocabularies. When uninstalling none of these things are uninstalled.

I know that we can set all the configuration to have the module as dependency, but that is tedious to do; is there a better way to let Drupal uninstall all the configuration on the module in the `config/install` folder?

# Answer
> 3 votes
> I know that we can set all the configuration to have the module as dependency, but that is tedious to do; is there a better way to let Drupal uninstall all the configuration on the module in the config/install folder?

Not really. Deleting the configuration is just as tedious, as you need to know what's yours. you could solve it using a naming pattern and list all node types, fields, views, .. starting with yourmodule\_ I guess.

There's been some discussion to automatically add the module providing the configuration as an enforced dependency, but that's actually also not always what you want.

# Answer
> 1 votes
One of the answers here may be able to help:

How do I remove a configuration object from the active configuration?

At a starting point, you could add `hook_uninstall` and run through and delete config, although, you will want to test this to ensure other parts of your site are unaffected after uninstalling.

This answer in particular may also work for you: https://drupal.stackexchange.com/a/173898/57

---
Tags: 8, configuration
---


# Question
Title: How do I programmatically add a product reference to a commerce product node?
I am trying add a commerce product to a node when a person fills out a content node. I am generating the product, but can't add it back to the node.

When I try to add the data to the node, there is no product reference field data when *Do not show a widget* is selected in the content type \> Manage fields.

*Do not show a widget* seems to remove the field from the node completely.

If I try to load in hook\_node\_presave():

```
$product = commerce_product_load_by_sku($sku);

$field_studio_pass_product = array(
  LANGUAGE_NONE => array(
    0 => array(
      'product_id' => $product->product_id,
    )
  )
);

$node->field_studio_pass_product = $field_studio_pass_product;

```

It won't work since there is no current field. I don't want to show the field to editor as they can't change it.

Further. This above code does work if the *product field has a widget*, or the ideal code:

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_studio_pass_product->set($product->product_id);

```

Again, if you set the field type to *Do not show a widget* there is no property on the node object, and as a result no ability to add a value.

# Answer
> 0 votes
The following 'nice answer' works

```
$node_wrapped = entity_metadata_wrapper('node', $node);
$node_wrapped->field_studio_pass_product = $product->product_id;
field_attach_update('node', $node);

```

# Answer
> 1 votes
Your issue isn't that there wasn't a field available in the data model to edit but that you used the wrong array structure for the product reference. Instead of the "value" key you should've been using "product\_id".

I highly recommend *against* directly inserting field data like your answer proposes. The Entity / Field APIs should be allowed to perform their full jobs on this data when it's entered. For example, in your case you didn't put the necessary data into the field data revision table at the same time.

---
Tags: nodes, commerce
---


title: Twig - accessing node properties

text:
# Question
Title: Twig - accessing node properties
How can I access node property which name starts with # in twig template?

I have content type with field Category and I need to access value of that field inside of twig template?

Using dump(content.field\_category\[0\]) I get this

```
array (size=5)
  '#type' => string 'link' (length=4)
  '#title' => string 'Example' (length=5)

```

How to access #title ?

Thank you.

# Answer
You can add this line, `{{ content.field_category[0]['#title'] }}` to get value of title inside twig.
> 1 votes

---
Tags: theming, 8
---


title: Hook for adding values to add node page

text:
# Question
Title: Hook for adding values to add node page
I'm searching for a hook in Drupal 8 API for adding values to a add content form. What hook can I use to alter values from /node/add/movies\_movie page?

# Answer
Inside your module, there is a \[your-module\].module file where you can write `hook_form_alter()`.

```
/**
 * Implements hook_form_alter().
 */
 function module_name_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   if ($form_id == 'node_movies_movie_form') {
     // Your code goes here.
     ...
     ...
   }
 }

```
> 1 votes

# Answer
Think you are looking for the form alter hook here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook\_form\_alter/8.2.x
> 1 votes

---
Tags: nodes, 8, hooks
---


title: Change form list default value

text:
# Question
Title: Change form list default value
I want to change the default -select a value- from a text list to a something like -please select a choice-

This is what I have:

```
  function project_form_alter(&$form, &$form_state, $form_id){
    if($form['#id'] == 'edit-field-gen-list'){
    $form['field_gen_list']['#default_value'] = 'all';
    }
}

```

It's not picking up the value.

This is the HTML.

# Answer
> 4 votes
* In Drupal 8 type-hint `$form_state` with the FormStateInterface & do not pass it by reference:

```
hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

```

See hook\_form\_alter() for further reference.
* I see some confusion on your usage of the `$form_id` / `$form['#id']`. Dump your `$form_id` in the hook & see which is the correct form you want to alter. Because as others have mentioned already: `edit-field-gen-list` is not your form id but your `field_gen_list` field id. For example: the form id of the contact Website feedback is `contact_message_feedback_form`.
* Given the HTML in your question, your `$form['field_gen_list']['widget']['#options']` will not have a key for 'all'. So adding that as default value will not work unless you add such a key value to the options array

So instead try this:

```
function project_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    kint($form_id, 'Find correct form id');

    if ($form_id == 'contact_message_feedback_form') { // Change this

        // Add an 'all' key value option
        $form['field_gen_list']['widget']['#options']['all'] = '- All -';

        // Set newly added key 'all' as default value
        $form['field_gen_list']['widget']['#default_value'] = 'all';
    }

}

```

# Answer
> 1 votes
Try this:

```
function project_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'edit-field-gen-list') {
    $form['field_gen_list']['#default_value'] = 'all';
  }
}

```

I'm not quite sure if the form element is in `$form['field_gen_list']` though.

# Answer
> 1 votes
Can you try this:

```
$form['field_gen_list']['und']['#default_value'] = 'all';

```

Note: All is your key value on select list.

Hope this helps you.

# Answer
> 1 votes
In your code, replace the line $form\['field\_gen\_list'\]\['#default\_value'\] = 'all'; by:

```
// save the array of field options in a var.
$field_options = $form['field_gen_list']['und']['#options'];
// change the value of the '_none' key to the one you need.
$field_options['_none'] = '- please select a choice -';
// set the modified array of options as the options for this field
$form['field_gen_list']['und']['#options'] = $field_options;

```

That's it!!

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


# Question
Title: $(...).find(...).once is not a function Javascript error in Drupal
I am getting this error in my console which is causing some other JS items not to work

```
    Uncaught TypeError: $(...).find(...).once is not a function
        at Object.attach (eval at globalEval (jquery.min.js?v=2.2.3:2), <anonymous>:156:44)
        at Object.Drupal.attachBehaviors (drupal.js?v=8.2.5:168)
        at insert (ajax.js?v=8.2.5:1084)
        at Drupal.AjaxCommands.loadEditorsAjax.commands.insert (quickedit.js?v=8.2.5:523)
        at Drupal.Ajax.success (ajax.js?ojj3xe:155)
        at Object.success (ajax.js?v=8.2.5:505)
        at i (jquery.min.js?v=2.2.3:2)
        at Object.fireWith [as resolveWith] (jquery.min.js?v=2.2.3:2)
        at z (jquery.min.js?v=2.2.3:4)
        at XMLHttpRequest.<anonymous> (jquery.min.js?v=2.2.3:4)

```

My current Drupal version 8.2.5 is using jquery 2.2.3 so I am not sure what is going on here.

Any ideas? I tried updating jquery to 3.0.0 but that didn't work. Same error.

# Answer
> 6 votes
As suspected and confirmed this is an issue with the bootstrap theme. My advice would be to roll back to the previous working version and open a bug report in their issue queue on drupal.org.

---
Tags: 8, javascript
---


# Question
Title: How to alter/hide the label of the input element in form (create/edit)?
We can theme the label of any field in tpl or even simply by changing the manage display option but wondering how to do the same in form (while creating or editing a content) ?

I'm looking for the proper way to alter/hide the label especially with field collection fields when the content is created or edited.

# Answer
> 20 votes
You can do this with `hook_form_alter()` or `hook_form_FORM_ID_alter()` in your custom module or also in your theme's template.php file.

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form_id
  if ($form_id == 'YOUR_FORM_ID') {
    // To hide the label
    $form['your_form_element']['#title_display'] = 'invisible';
    // To alter the label
    $form['your_form_element']['#title'] = t('Your new title');
  }
}

```

If you use `hook_form_FORM_ID_alter()` instead, you don't need to check the form\_id.

You can find more information on the Form API Reference for the `#title` and `#title_display` attributes, and also all the other form elements and their attributes.

In case of Field Collection, it can be a bit complicated. Below is an example code:

```
function YOURMODULE_form_YOUR_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $your_field_collection = element_children($form['your_field_collection'][LANGUAGE_NONE];
  foreach ($your_field_collection as $key => $value) {
    if (is_numeric($value)) {
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title'] = t('Your new title');
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title_display'] = 'invisible';
    }
  }
}

```

Explanation of the above code:

First I assigned the field collection itself to a variable, to make it a bit readable. I used `LANGUAGE_NONE` for simplicity but a better practice would be to use `$form['your_field_collection']['#language']`, admittedly it makes the whole code more complicated to read.

Second, I used a `foreach`, since most of the time we use a field collection if we want to have multiple values of some collection of fields. So the `foreach` loop would take care of all instances of the field collection.

Third hack, is a dirty trick I learned from someone on Drupal.org, maybe there would be a better approach, but it just works so I didn't dig into. I check if the `$value` is numeric, to exclude all other meta attributes and loop only through the elements.

Then, finally, in each element I alter the field in the field collection.

# Answer
> 1 votes
This will help you.

```
/**
 * Implements hook_field_widget_form_alter().
 */
function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#entity_type']) && $element['#entity_type'] == 'field_collection_item' && $element['#bundle'] == 'YOUR FIELD COLLECTION') {
    $element['value']['#title_display'] = 'invisible';
  }
}

```

# Answer
> 1 votes
The field\_display\_label module solves this by adding a separate display label.

This way, the original field label appears exclusively on the create/edit form, while the display label (if set) appears exclusively on the view page. So by setting the original field label to nothing, you can remove the label in the create/edit form only.

# Answer
> 0 votes
Using hook\_form\_FORM\_ID\_alter() trying to act on the node edit form, this worked for me:

```
function MYMODULE_form_NODE_TYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_MY_FIELD']['und']['#title_display'] = 'invisible';
}

```

(Substitute your values for values in ALL CAPS.)

---
Tags: 7, entities
---