# Question
Title: How do I assign a template to the user edit form?
I am trying to create a twig template for user edit page.

I have tried

```
/**
 * Implements hook_theme_suggestions_alter().
 */
function my_module_user_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if($variables['element']['#type'] == 'form' && $variables['element']['#form_id'] == 'user_form') {
    $original_theme_hook = $variables['theme_hook_original'];
    $suggestions[] = $original_theme_hook . '__bs_' . str_replace('-', '_', $variables['element']['#id']);
  }
  return $suggestions;
}

```

I have added my template in my module under templates/form\__bs\_user\_form.html.twig

I have also added in my form\_alter:

```
$form['#theme'] = ['bs_user_form'];

```

and

```
function my_module_user_theme($existing, $type, $theme, $path) {
  return [
    'bs_user_form' => [
      'render element' => 'form',
      ],
  ];
}

```

It does retrieve this error: Argument 1 passed to Drupal\Core\Render\Element::setAttributes() must be of the type array, null given

How can I assign a template to the user edit form?

---

Solved, I removed my\_module\_user\_theme\_suggestions\_alter and I got it working. If anyone has a better solution feel free to add it to the answers.

# Answer
To add an additional template level to a form, add the `#theme` key to the form array:

```
$form['#theme'] = ['bs_user_form'];

```

and in *my\_module.module*:

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'bs_user_form' => [
      'render element' => 'form',
      ],
  ];
}

```

The template name is then `bs-user-form.html.twig`, where you can print the form with `{{ form }}` or theme it like for example:

*entity-moderation-form.html.twig*

```
<ul class="entity-moderation-form">
  <li>{{ form.current }}</li>
  <li>{{ form.new_state }}</li>
  <li>{{ form.revision_log }}</li>
  <li>{{ form.submit }}</li>
</ul>
{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

```

---

You can add theme suggestion to the theme name, but don't use `form__` as base hook, because this is already used for the Form element, which caused the error.
> 3 votes

---
Tags: theming, users
---


# Question
Title: How to delete all parent references of a taxonomy term?
How to delete references to parent terms?

I tried this:

```
$term->get('parent')->setValue(NULL);
$term->save();

```

Additional question: how to delete reference to a specific parent term?

# Answer
> 3 votes
Answering to myself. Taxonomy hierarchy is known to be *detached* from terms. For example when loading term you don't get its parents. This was confusing to me and I thought `setValue()` just doesn't work. But the truth is that it works perfectly.

To get the code from above working, only a minor edit is required - it's using `0`, not `NULL`:

```
$term->get('parent')->setValue(0);

```

This **deletes all the hierarchy the term has** and writes one record to the `taxonomy_term_hierarchy` table - with zero parent.

If you need to delete the hierarchy manually you can use `deleteTermHierarchy()`:

```
\Drupal::entityTypeManager()->getStorage('taxonomy_term');->deleteTermHierarchy($tid);

```

but be warned that the term will disappear from the lists on `/admin/structure/taxonomy/manage/<vocabulary>/overview` page since it's missing any hierarchy now. To *fix* this you need to add a record to the `taxonomy_term_hierarchy` table with zero parent. And that's exactly what `setValue(0)` does - deletes hierarchy and adds that record.

---
Tags: 8
---


# Question
Title: How to sort images in Views by their position?
If you have multiple images uploaded to your node, on the edit mode you can drag those images up and down and position them. How do I set that top image is shown first in Views?

Which sort option is that for the image field?

# Answer
> 2 votes
sort your view with field\_image:delta, ascending

---
Tags: 7, views, entities, media
---


# Question
Title: How to change/set/assign parameter's value for an entity query?
Say you have an entity query which you're going to use in a loop so that only parameter(s) value(s) changes on every iteration. Is there a way to prepare this query and change the value of the parameters?

# Answer
There are some nice examples in the comments on the api documention page for Entity queries https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x

One example assigns a value to a variable, then uses the variable in the query:

```
$value = 'some value';
$query = \Drupal::entityQuery('entity_type');
$query->condition('field', $value);
$entity_ids = $query->execute();

```

In your loop you could re-assign the value as needed before executing the query.

Another example sets up some functions, so that might be an option and then your loop could call the function.

```
function someFunction($value) {

  $query = \Drupal::entityQuery('entity_type');
  $query->condition('field', $value);
  $entity_ids = $query->execute();

}

```

Or you could clone the part that stays the same in your loop and alter the rest. Using your code as an example...

```
$base_query = \Drupal::entityQuery('taxonomy_term');
$base_query->condition('vid', 'some_vocabulary');

for ($i = 1; $i <= 10; $i++) {
  $query = clone $base_query;
  $query->condition('tid', $tids[$i]);
  $query->execute();
  //...
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: How to insert a View inside other View as the last row of the parent View?
I need to insert a View inside other View as the last row of the parent View.

**I know I can create a Attachtment but this will be shown before or after the rows of the parent view. I need it to be inserted as the last row of the parent view**

Let's say the parent view lists "basic pages" nodes and the inserted view lists "articles" nodes.

Then the results of what I need would be: 6 rows: the first five rows will be "basic pages" and the last one will an "article".

Is there any way to get this?

# Answer
> 1 votes
Use views\_field\_view module. This module help you to embed a view as a field in a view.

# Answer
> 1 votes
Below are the modules. I hope any of these help you to solve this :

1. Node Embed

> Node Embed provides an input filter for CKEditor integration allowing a content editor the ability to embed the rendering of nodes within the body/fields of another node. This uses a View to allow for the browsing/preview/selection of a node to embed and provides a set of template suggestions that allow for the detailed control of node rendering when in embedded mode.

2. Views Field View

> This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.
>
> This view handler can accept arguments from fields of the parent view using tokens and pass them into the child view for each row. Raw or rendered token values can be used, as well as static values.

Inserting Views \- Read the content & comments. I hope this may help.

# Answer
> 0 votes
in your view settings, middle column add in footer a Global: View (Views field view). Embed a views\_field\_view field in an area. This can also accept argument tokens. pick the view you desire to add, done.

---
Tags: views
---


# Question
Title: Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme?
I'm trying to learn how to use the Drupal Bootstrap theme to create my own subtheme. I've added the Bootstrap theme to my `drupal/themes` directory, and chosen SASS as my sub-theme starterkit (i.e. I've copied `drupal/themes/bootstrap/starterkits/sass` to `drupal/themes/mynewtheme`).

I understand the concept of how sub-themes work: the sub-theme inherits the parent theme's resources. But I don't understand how it works in the case of the Drupal Bootstrap theme. Once I install the bootstrap framework into my sub-theme (per the instructions on the Drupal Bootstrap sub-theming instructions page), what resources is the sub-theme inheriting from the main theme?

# Answer
> Why do I need to enable the Drupal Bootstrap theme when using a Bootstrap subtheme?

You don't. You simply have to define in your subtheme that you're making Drupal Bootstrap your parent theme.

> what resources is the sub-theme inheriting from the main theme?

The templates and anything tethered to it.

Templates that you don't override on your subtheme gets delegated to the parent theme, in this case, the Bootstrap theme. Anything that the Bootstrap theme doesn't override gets delegated to the core themes. If I remember correctly, the Bootstrap theme overrides a lot of the templates. If you turn on template debugging, you'll see the hierarchy of the template suggestions.

Since the templates also define additional things like favicons, extra CSS, HTML boilerplates, and that stuff (html and page templates especially), if you don't override them on your subtheme, you get Bootstrap's which loads whatever is in there.
> 0 votes

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


# Question
Title: How to use single search box (autocomplete) for users and content?
How can I use single search box with autocomplete for all the users on site and all the content of particular content type like blogs.

Thank you.

# Answer
No need to create two views this can be achieved by modifying the query if you are using views. You can easily alter the query, if you are using the custom form then you can use Form API with autocomplete and in autocomplete callback you can do whatever you want. I have solved this using the autocomplete and its callback using FAPI
> 4 votes

# Answer
If you are using Exposed filters you can use the Better Exposed Filters module, this allows you to combine serveral exposed filters into one filter.

How this works is described here: combine several exposed filters into one exposed (search) form?
> 0 votes

---
Tags: 7, views
---


# Question
Title: Setting link field in menu content item as not required
I am trying to make a field not required in drupal 8 through hook form alter in the following way, which does not seem to work:

```
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == "menu_link_content_menu_link_content_form") {
    $form['link']['#required'] = FALSE;
  }
}

```

# Answer
To get this working in the form alter hook you need to set #required to FALSE in the widget:

```
$form['link']['widget']['0']['uri']['#required'] = FALSE;

```

The red asterix mark for a required field is no longer there, but the form does not validate. To get the form validated you would need to do this in the field definition. Implement a hook hook\_entity\_base\_field\_info\_alter and set required to FALSE:

```
function mymodule_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content') {
    $fields['link']->setRequired(FALSE);
  }
}

```

But this doesn't help either, because there is code in the menu link content class that depends on `$this->link`, so even if you manage to pass the validation you get an error later, that the link is missing.
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Render exposed filter without creating block
Can we place/render exposed filter to some other region(sidebar second) without creating exposed filter in block because when we creating exposed filter with block its autosubmit functionality stopped working ,without creating exposed filter with block its autosubmit functionality working fine.

I am using better exposed filter module https://www.drupal.org/project/better\_exposed\_filters.

# Answer
> 3 votes
I found the solution. I created a custom block which uses the following code.

```
use Drupal\Core\Form\FormState;
use Drupal\views\Views;

$form = [];
$view_id = 'Your-view-id';
$display_id = 'your-display-id';
$view = Views::getView($view_id);
if ($view) {
  $view->setDisplay($display_id);
  $view->initHandlers();
  $form_state = (new FormState())->setStorage([
    'view' => $view,
    'display' => &$view->display_handler->display,
    'rerender' => TRUE,
  ])
    ->setMethod('get')
    ->setAlwaysProcess()
    ->disableRedirect();
  $form_state->set('rerender', NULL);
  $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
  print render($form);
}

```

You can create your own exposed filter in a block without requiring any third-party module.

---
Tags: 8
---


# Question
Title: Add a select list to the content of the view
Could we add a select list in a view content?

I have below view and I want to add a select list that has (Approve and Reject items) for each row under 'Status' column. Also, there will be a 'Save' button to save the changes in database.

Can we do this in view or there is another way? Please help..

# Answer
> 0 votes
Please read post Programmatically Creating Forms with Views in Drupal 7 which is very close to your requirement.

---
Tags: 7, views
---


# Question
Title: Displaying the csv file content in a view
We imported the content of the excel sheet into csv and generated a view using feeds importer(Feeds module). But we want show the csv file content onto a slidershow. How to display them on a revolution slider.

# Answer
> 0 votes
Change the said view's display format to "Slideshow". You also will have a whole bunch of settings to customize your slideshow.

PS: You only get this format when you install the Views Slideshow module

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


# Question
Title: How do I turn off the trimming of comments?
In D8, I'm just wanting the comments that follow the content on a node page to appear in a normal fashion, but the comment list that appears displays a trimmed comment.

The markup itself contains trimmed text:

```
<div class="comment-text">
    <div class="comment-arrow"></div>
      <h3><a href="/comment/711#comment-711" class="permalink" rel="bookmark" hreflang="en">Please make results of this</a></h3>
        <div class="content">
            <div></div>
        </div>
     </div>
</div>

```

and I note that the comment is contained in a h3 tag and the content tag is empty.

I've checked the comments type display settings for article, the content display settings for the comments, which is set to show a comment list (no other options), and see nothing set to trim.

Here is some additional information that might be useful:

Comment bodies ARE displayed IF the comment is a reply to another comment. If the comment is NOT a reply to another comment, the meta shows (author, date, etc.) but no body, even though the comments do have body text in comment\__comment\_body.

The twig entry that is used in either case seems kosher to me:

```
<div class="comment-text">
  <div class="comment-arrow"></div>
  {#{% if title %}#}
    {#{{ title_prefix }}#}
    {#<h3{{ title_attributes }}>{{ title }}</h3>#}
    {#{{ title_suffix }}#}
  {#{% endif %}#}
  <div {{ content_attributes.addClass('content') }}>
    {{ content.comment_body }}
  </div>
</div>

```

# Answer
> 0 votes
Have you looked if the format is not set to "trimmed" on the comment display page (/admin/structure/comment/manage/comment/display) ?

---
Tags: 8, comments
---


# Question
Title: Unable to retrieve value from settings file inside custom module
I have some specific values that will never change. I could use `define` and set them as constants but having a `module_name.settings.yml` file seems more appropriate.

The problem is that I can't seem to get the values from that file. It always ends up in `null`.

I have a module `my_module` in `docroot/modules/custom', it's installed. Inside the root of the module I've created a`my\_module.settings.yml`file with a single entry of`hello: 'world'\`.

I've tried retrieving it using:

```
(\Drupal::config('my_module.settings'))->get('hello')

```

But the returned value is `null`. According to the documentation it should be working fine.

I'm using Drupal 8.

What am I missing here?

# Answer
You need to put this file into

> myModule/config/install/my\_module.settings.yml

Then uninstall and reinstall.

You ll get your value.
> 2 votes

---
Tags: 8
---


title: SQL queries with AND/OR conditions

text:
# Question
Title: SQL queries with AND/OR conditions
I'm transferring SQL statements from a Drupal 5 installation to Drupal 8, and struggling with And/Or condtions. eg given the original SQL:

```
    SELECT .....
    WHERE .....
          AND classes.description = "Photographer"
          AND (classoptions.description = "Name of photographer here"
           OR classoptions.description = "Not assigned").

```

I've translated it to:

```
$query = $this->dbConnection->select('classes');
....etc....
$query->condition('classes.description', 'Photographer');

```

So far, so good. Then I need an OR condition for

```
$query->condition('classoptions.description', 'Name of photographer here');
$query->condition('classoptions.description', 'Not assigned');

```

Looking at documentation on-line, using db\_or() is suggested, as in :

```
$query->condition(db_or()
 ->condition('classoptions.description', 'Name of photographer here');
 ->condition('classoptions.description', 'Not assigned'));

```

..but this is a) deprecated, b) gives error 'db\_or function not found' The replacement for db\_or() is to obtain a new Condition object, but what am I supposed to do with it? The function

```
 $query->orConditionGroup();

```

Will return a new Condition object, and the code

```
$query->condition(orConditionGroup()
 ->condition('classoptions.description', 'Name of photographer here');
 ->condition('classoptions.description', 'Not assigned'));

```

Formats a Condition object with the conditions to be ORed just fine.But again, how do I incorporate this into the query?

# Answer
Have a look how `orConditionGroup()` is used in core. For example, in `ConfigEntityQueryTest` it is used this way:

```
$query = $this->factory->get('config_query_test', 'AND');
$and_condition_1 = $query->orConditionGroup()
  ->condition('id', '2')
  ->condition('label', $this->entities[0]->label);
$and_condition_2 = $query->orConditionGroup()
  ->condition('id', 1)
  ->condition('label', $this->entities[3]->label);
$this->queryResults = $query
  ->condition($and_condition_1)
  ->condition($and_condition_2)
  ->execute();

```

I am sure you can apply this to your problem.
> 13 votes

# Answer
For the sake of completeness, this worked for me (thanks to the original poster):

```
$query = \Drupal::entityQuery('taxonomy_term')
  ->condition('vid', 'surface');
$group = $query->orConditionGroup()
  ->condition('field_surface_exclude', NULL, 'IS NULL')
  ->condition('field_surface_exclude', 0);
$tids = $query->condition($group)->execute();

```
> 10 votes

---
Tags: 8, database
---


# Question
Title: "You cannot send more than 5 messages in 1 hour"
I have several contact forms, but I don't want to limit the users to submit the form. I've tried form unblock with smart IP; it doesn't work for me.

Do you have any idea to release the IP and unset the limit?

# Answer
> 6 votes
Change it using drush config-set.

To get the default settings use:

```
drush config-get contact.settings

```

To change the limit to 100 instead of 5, use:

```
drush config-set contact.settings flood.limit 100

```

# Answer
> 1 votes
The flood setting is a configuration value, but it isn't exposed in the administration interface, so you can't easily change it in the site. Changing the `config/install/contact.settings.yml` file will not work (unless you then reinstall the module), and editing core files is always a bad idea. But you can set configuration values using the drush or drupal console command-line tools, eg. `drupal config:edit contact.settings`.

---
Tags: emails
---


title: Microkernel with low bootstrap level?

text:
# Question
Title: Microkernel with low bootstrap level?
Drupal 7 had a neat feature of different bootstrap levels that allowed to write really fast micro services that didn't require to fully bootstrap Drupal.

Drupal bootstrap levels no longer exists in Drupal 8, but what would be the best approach to build some kind of microkernel to handle simple database queries? I'd like to initialize the database and configuration to do some SQL queries and send a JSON response.

# Answer
> 7 votes
A lot of the bootstrap process happens now implicitly as services are requested.

If nothing requests the database service then Drupal won't open the connection to it and so on.

The minimal amount of code to do a custom php file that bootstraps Drupal and does some queries can be seen in statistics.php:

```
$autoloader = require_once 'autoload.php';

$kernel = DrupalKernel::createFromRequest(Request::createFromGlobals(), $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$views = $container
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    $container->get('request_stack')->push(Request::createFromGlobals());
    $container->get('statistics.storage.node')->recordView($nid);
  }
}

```

Depending on what it is for, you could also do a normal controller and return a cacheable JsonResponse with the right cache tags and contexts, then Drupal will automatically cache that in the internal and dynamic page cache. Which, depending on your queries, might not be much or not at all slower.

---
Tags: 8, performance
---


# Question
Title: How can I print a views exposed form into a custom block?
I have a page view with exposed filters and would like to print said filters into a custom block in order to add extra html markup above the actual form. This block will be used on other pages using Context.

I know I can create a block by setting 'exposed filters in block' to yes, however that's not the solution I am looking for.

# Answer
Hours and hours of searching and nothing was working. Several minutes after posting this question, I figured it out. The following code can be used in template files or blocks.

```
<?php
  $block = module_invoke('views', 'block_view', '-exp-VIEW_NAME-DISPLAY_NAME');
  print render($block['content']);
?>

```
> 8 votes

# Answer
Its simple take a look at the screenshot.
> 1 votes

# Answer
For Drupal 7:

```
$view = views_get_view('view_name');
$display_id = 'page'; // Display: page/block
$view->set_display($display_id);
$view->init_handlers();
$form_state = array(
    'view' => $view,
    'display' => $view->display_handler->display,
    'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
    'method' => 'get',
    'rerender' => TRUE,
    'no_redirect' => TRUE,
    'always_process' => TRUE, // This is important for handle the form status.
);
$form = drupal_build_form('views_exposed_form', $form_state);
print drupal_render($form);

```

'always\_process' is main form state argument for handle the exposed filter form status.

From https://www.drupal.org/node/2854114
> 1 votes

---
Tags: views, blocks
---


# Question
Title: How to make menu link show for certain roles?
I want to add "Login" and "Logout" to the same menu but only for the right role. In previous versions of Drupal, you would just add /user/login and /user/logout to a menu and it would only render one or the other based on if they actually were logged in or not.

However in D8, it looks like the Logout link shows regardless... is there a way to replicate this without creating multiple menus?

# Answer
> 1 votes
In D8 this is a menu link class, which you can add to a menu in \*.links.menu.yml:

*mymodule.links.menu.yml*

```
mymodule.logout:
  weight: 10
  menu_name: mymenu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

```

This class shows *Log in* or *Log out* for user roles authenticated or not:

```
  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('Log out');
    }
    else {
      return $this->t('Log in');
    }
  }

```

and links it to the corresponding route:

```
  public function getRouteName() {
    if ($this->currentUser->isAuthenticated()) {
      return 'user.logout';
    }
    else {
      return 'user.login';
    }
  }

```

---
Tags: 8, navigation
---


# Question
Title: How to make a content visible only in the corresponding language it has been created on a multilingual website
I am buiding a website on **drupal 7** in french and english.

I made **french** the default language because most users are french speaking at first. So **English** became the second language.

I am using **Entity Translation**.

In that website, people who have an account can create content. **But I want the content not to be translatable** apart from menus and some other stuff.

What I want is the content that is writen in french (in the french version) to be displayed only in the french version. And the content that is written in english (in the english version) to be displayed only in English.

I've tried that for days. But all the content is **still showing in both languages**.

**Can you help me please ?**

# Answer
> 0 votes
Entity Translations can be configured so that when it doesn't find content for a field in a language, it uses the content of the default language if any is available. If you're in an English page and a field is missing content, it may pick up the French content.

*This can be disabled* in `/admin/config/regional/entity_translation` by unchecking the "Enable language fallback" checkbox. When disabled, fields that have no content will simply not appear and won't fall back to the default language's content.

---
Tags: nodes, i18n-l10n
---


# Question
Title: How to get field values in node template in Twig
I have an image field named **Gallery**. You can add multiple images in this field. It’s in a content type named **Gallery with Captions**.

I have a twig template named `field--node--field-gallery--gallery-with-captions.html.twig`. Within that, I have the following, so that I can use the `title` and `alt` fields as content:

```
{% for item in items %}
<div{{ item.attributes }}> {{ item.content }} <h2>{{ item.content['#item'].title }}</h2> <p>{{ item.content['#item'].alt }}</p></div>
{% endfor %}

```

This all works great! Except when I want to use a different Display for this where it’s related to another entity type. There are two template hints I can use there:

```
node--gallery-with-captions--teaser-complementary.html.twig

field--node--field-gallery--gallery-with-captions.html.twig

```

I don’t want to use the latter, because I've already configured that for the full gallery/node page and in this case a) I only want to output the first image as a thumbnail to link to the gallery and b) I don’t want the title or alt. The node template has the right display type, but I’m struggling with digging into a) the first image in the gallery and b) the fields I want.

Any suggestions on zeroing in on the first image in this field displaying it as just the image linked to the entry? The template debug suggestions aren't suggesting a field template by display type, which is where this would ideally reside.

# Answer
A teaser image linked to the content is the standard configuration for the teaser view mode. You only need to limit it to one image. This is a feature request for core, see this issue https://www.drupal.org/node/1234624. Until then you can use this sandbox project: https://www.drupal.org/node/1234624#comment-11868691.

If you want to do this in a node twig you can get the first field item with the delta 0:

```
{{ content.field_image.0 }}

```

and then remove the field from the main content to avoid double content:

```
{{ content|without('field_image') }}

```
> 2 votes

---
Tags: theming, 8, nodes, entities, media
---


# Question
Title: How can I link css/js from main bootstrap theme to subtheme?
I'm kinda a newbie to web development and web coding languages. I recently installed Drupal 7.54 on localhost (xampp), then loaded it with Bootstrap 3.13 theme but when I come to creating a subtheme, It does not resemble the main theme though I've followed instructions here: https://www.gaslampmedia.com/tutorial-drupal-bootstrap-3-4-subtheme-with-less/

My subtheme looks like this:

Can anyone configure this? thanks

# Answer
The fact that you've got the Drupal Bootstrap site logo means the theme was correctly enabled. However, this is a symptom of the browser not finding your CSS file.

And you don't actually use the Bootstrap CSS that comes with the parent theme. You actually have to import Bootstrap into your SASS/LESS. That's why you need to download Bootstrap to your subtheme (Step 4).

If you're using the SASS/LESS starterkit, you will actually need to compile your CSS (that's steps 4 and 5 of the Overview). Once you've got it compiling, you need to tell your subtheme the path of the compiled CSS by adding it to the info file (step 3 of the Overview).

```
stylesheets[all][] = path/to/compiled/styles.css

```
> 0 votes

---
Tags: theming
---


title: Import CSV file from S3 Bucket

text:
# Question
Title: Import CSV file from S3 Bucket
Using s3 file system & feed import module. Issue is the fetching of csv file from s3 working... says no file or folder detected ... have the folder under s3://public/repo.csv and had read/write permission.

When running import, it will have a no file / directory found.

# Answer
> 0 votes
To detect folders created and files added to an S3 bucket, you need to Flush s3 media file metadata cache.

To do it, Configuration \> Media \> S3 File System \> Actions \> File Metadata Cache \> Refresh File Metadata Cache

The file metadata cache keeps track of every file that S3 File System writes to (and deletes from) the S3 bucket, so that queries for data about those files (checks for existence, filetype, etc.) don't have to hit S3. This speeds up many operations, most noticeably anything related to images and their derivatives.

This button queries S3 for the metadata of all the files in your site's bucket (unless you use the Root Folder option), and saves it to the database. This may take a while for buckets with many thousands of files. It should only be necessary to use this button if you've just installed S3 File System and you need to cache all the pre-existing files in your bucket, or if you need to restore your metadata cache from scratch for some other reason.

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


# Question
Title: Redirect example.com to example.com/node
Currently I am facing ERR\_TOO\_MANY\_REDIRECTS problem in chrome when I try to visit `example.com`. Since `example.com/node` is working fine, I want to redirect all the traffic to `example.com/node` for now.

How do I achieve this ?

# Answer
> 1 votes
Do you have any redirect module enabled? Might be because of that maybe Global redirect or something.

Otherwise you can redirect your homepage to pick up example.com/node by adding the path here: Default front page: URL(admin/config/system/site-information).

---
Tags: redirection
---


title: Custom preview page on Webform

text:
# Question
Title: Custom preview page on Webform
I want to theming only preview pages on Webform. Is it possible?

# Answer
> 1 votes
I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

```
function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

```

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.

See similar issue here.

# Answer
> 0 votes
You fill find it very hard to do this in a tpl.

Use a form\_alter hook and check if you are on the preview step:

```
$page_count = $form_state['webform']['page_count'];
$page_num = $form_state['webform']['page_num'];
$preview = $form_state['webform']['preview'];
if ($preview && $page_num === $page_count) {
   ...
}

```

---
Tags: 7, webforms
---


# Question
Title: How do I place a block in a region, programatically?
Why isn't my custom block rendering in the region I want? It shows in the *content* region, not my custom *content\_right* region.

```
function bootstrap_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'some.path') {
    $block = \Drupal::entityManager()->getStorage('block_content')->load(12);
//kint($block);
    $block_view = \Drupal::entityManager()->getViewBuilder('block_content')->view($block);
    $variables['page']['content_right']['custom_block'] = $block_view;
  }
}

```

What am I missing?

# Answer
You can try this, create an instance of a block plugin on the fly for the block content:

```
$block_content = \Drupal::entityTypeManager()->getStorage('block_content')->load(12);

$plugin_id = 'block_content:' . $block_content->uuid();
$block_view = \Drupal::service('plugin.manager.block')
  ->createInstance($plugin_id, [])
  ->build();

$variables['page']['content_right']['custom_block'] = $block_view;

```

But it's better to configure the block plugin in UI and build the configured block instead. For more info see this question Programatically render a block in a twig template
> 0 votes

---
Tags: blocks, theming
---


# Question
Title: Specified template file for user-profile-form based on role
I use drupal 7.x and field\_group and nultiple registration module. How I can use a template file (.tpl) for user-profile-form only based on roles. in other words when a user with A role login to site and go to user/%/edit page see a specified form with specified fields. and When user loged on with B role have another form for edit information.field permissions control fields but field groups is visible yet because field\_group module have a bug with field\_group\_multiple module.

So , I want to use specified tpl file for user-profile-form (no registration page or profile page - only user-profile-form ) by role . Can you help me ?

# Answer
You can simply load $user variable in your template file and check which role current user is having and simply based on the role print your form. for e.g

```
if ($user->roles[4] == 'role1') {
  print render $form['form_field1'];
  print render $form['form_field2'];
}
if ($user->roles[5] == 'role2') {
  print render $form['form_field_field1'];
  print render $form['form_field_field2'];
}

```

In the end don't forget to print the following

```
print drupal_render_children($form);

```
> 0 votes

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


title: add mime type for js file

text:
# Question
Title: add mime type for js file
I want to add mime type for js file 'youtube.js' which helps to pause and play the youtube video.I have included in info file as `scripts[] = js/YoutubeVideo.js`. I caught the error

> The resource from “http://test.com/themes/sample/js/youtubeVideo.js?oqctd7” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

I have inspected the source file this file is included as `<script type="text/javascript" src="http://test.com/themes/sample/js/youtubeVideo.js?oqctd7"></script>`

I want to change the mime type application/javasccript.How can I do it

# Answer
You can make you own tag with drupal\_add\_html\_head

Something like this: (not tested )

```
$element = array(
  '#tag' => 'script', // The #tag is the html tag -
  '#attributes' => array( // Set up an array of attributes inside the tag
    'href' => 'http://test.com/themes/sample/js/youtubeVideo.js?oqctd7',
    'type' => 'application/javasccript',
  ),
);
drupal_add_html_head($element, 'youtube_video');

```

Put this code in the YOUR\_THEME\_NAME\_preprocess\_html function.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to apply .diff and .patch file by SSH?
I use Drupal 7 and I read every article about applying patches, but I don't understand how to apply patches to Drupal files using SSH. I am administrator of a Linux server that hosts a Drupal site.

Can anybody help me?

# Answer
> 1 votes
After logging in to your site with SSH, in order to apply patches, you should have or install a program on your server. `patch` is the most widespread one, but you can also use `git` for it.

You can find more documentation on applying patches in the Drupal site: https://www.drupal.org/patch/apply

---
Tags: version-control, ssh
---


# Question
Title: How do I change the top picture for blueprint theme?
I just need to change the top image of the website to another image. The website is using Drupal 6 and the Blueprint theme. I am able to get to the theme building page, is that the right place to start?

# Answer
First of all: You shuldn't use Drupal 6 anymore as it has reached EOL (https://www.drupal.org/drupal-6-eol).

The regular way to replace the page logo is through the admin interface. You should have an logo file field on your theme settings page.

Another way is to check out the logo path with with firebug (or F12 for the regular browser console) and replace it directly with your ftp client.

Edit: If "Top Image" means something else then the logo, you can also use the second method, but make sure the determined image is not processed through imagecache, otherwise it will be overridden after the next cache clear.
> 0 votes

---
Tags: theming, 6
---


# Question
Title: How can I promote content by number of hits (reads)?
I would like to create some kind of an algorithm to my website like Reddit might have or even other websites. The algorithm, probably powered by the Rules module, should be able to promote content to the front page by number of hits (reads or visits), or comments a node receives. I can't seem to find any solution with the Rules module. Any help?!

# Answer
> 2 votes
The near defacto solution for this is the **Radioactivity** module:

> This module provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.

As opposed to straight pageviews, this uses an algorithm to take activity-over-time into account. With straight statistics / counts, an old page with low activity per day can perpetually stay at the top of lists because it slowly accumulates statistics.

**Radioactivity** takes time into account, so that your newer pages can appear at the top when appropriate, and then roll off at the appropriate time. It relies on **Rules**, but integrates nicely with **Views**, for building the lists of things (either pages or blocks).

# Answer
> 1 votes
The Weight module might help you for this. Some details about it (from its community documentation):

> The Weight module adds a weight option to enabled node types. Nodes with lower weight will float to the top of lists, while heavier items will sink to the bottom of lists. This is useful for sorting non-chronological nodes like bios, e-commerce products, or whatever you would like and for ordering nodes on the front page.
>
> The "standard" Drupal sort order for nodes is by sticky, then by created date. Weight uses the node table's 'sticky' column to store weights as well as sticky information (so that feature is not lost). So then nodes will be sorted first by stickiness, then by weight, then by creation date.
>
> This is a simple module with a simple purpose that can add a lot of value to your site with very little overhead.

It has over 48K of reported installs, and an official release for anything between D5 and D8.

To actually use it in combination with the Rules module, you may have to create your own custom Rules Action(s). For that you can start from the patch attached to this issue.

If you're in for even more Node ordering modules, then checkout Comparison of Node/Entity Ordering Modules.

---
Tags: 7, rules
---


title: Create custom theme for module

text:
# Question
Title: Create custom theme for module
I've creating an intranet module for Drupal 8 and I want to use a custom theme for it, like an admin theme(with page/node/field templates) where I can map region like menu, header, footer... but only for my module.

I didn't find any specific doc about this.

Thanks for your help!

# Answer
Another option would require creating a theme (in addition to your module). Then have your module indicate it uses that theme. Here is a nice article on how to do this https://speedandfunction.com/switching-themes-programmatically-drupal-8/

In this scenario, you would have your main theme and the theme used by your module. You could indicate that the theme used by your module was a sub-theme (https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme) of your main theme which could reduce some theme coding management.
> 1 votes

# Answer
You cannot specify region on your module, but you can custom your page or your block.

Regions are specify into main theme.

First, you need to create a folder on your module root directory :

> myModule/templates

Inside, you ll put all your custom template.

For example :

> page1.html.twig
>
> page2.html.twig

Then you need to declare all your templates :

> In myModule.module :

```
/**
 * Implements hook_theme().
 */
function myModule_theme() {
  return [
    'page1' => [
      'template' => 'test',
      'variables'=>array('test'=>NULL),
      'render element' => 'children',
    ],

      'page2' => [
          'template' => 'page2',
          'render element' => 'form',
      ],

  ];
}

```

And after, in your controller or your form :

```
return $build +  [
  '#theme'=>'page1',
  '#test'=>"its content for my variable inside my template",
];

```
> 1 votes

# Answer
If u want custom theme for module u just need to use template suggestions, output content from php and then render it in twig files.
> 0 votes

---
Tags: theming, 8
---


# Question
Title: "View unpublished content" permission for non-author
I googled a bit to see if there's a permission-level way to allow a logged-in (but non-admin) user see unpublished content (marked with the CSS node-unpublished class). This appears to be scheduled for Drupal 8 only. But maybe someone was clever enough to do a workaround?

I have a role named `Content Editor` which should be able to see all unpublished content, regardless of whether they were the author or not.

# Answer
> 18 votes
If you're ok writing a very small custom module you could use a combination of `hook_permission()` and `hook_node_access()` to do this:

```
function MYMODULE_permission() {
  return array(
    'unconditionally view unpublished content' => array(
      'title' => t('Unconditionally View Unpublished Content'),
      'restrict access' => TRUE
    )
  );
}

function MYMODULE_node_access($node, $op, $account) {
  // We're only bothered about the 'view' operation at the moment
  if ($op == 'view') {
    // If the user has access to our new permission, let 'em at it
    if (user_access('unconditionally view unpublished content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

  // For everything else let the system decide.
  return NODE_ACCESS_IGNORE;
}

```

Any role you assign the new permission to should now be able to view any node, regardless of whether it's published or not.

# Answer
> 6 votes
I first tried the code above, which is great. But after giving rights onto unpublished content to a role, that role still couldn't see unpublished content in views, and this can be very useful for some editors roles...

I solved it using the module view\_unpublished.

# Answer
> 3 votes
I use the Revisioning module for this. Upon installation, it creates the following permissions for each content type:

* *Content type*: View revisions of own content
* *Content type*: View revisions of anyone's content
* *Content type*: Publish revisions of own content
* *Content type*: Publish revisions of anyone's content

By giving my editors permission to view revisions of anyone's content, they are able to access and publish all nodes that have been created or revised by other users.

# Answer
> 1 votes
This is what I ended up making....

It creates a 'view any content permission' for each node type. It's pretty much the same as what the node module does, but adds the extra option.

```
/**
 * Implements hook_permission().
 */
function MODULE_permission() {
  $perms = array();
  foreach (node_permissions_get_configured_types() as $type) {
    $info = node_type_get_type($type);
    $perms += array(
      "view $type content" => array(
        'title' => t('%type_name: View any content', array('%type_name' => $info->name)),
      )
    );
  }
  return $perms;
}

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
    if ($op == 'view' && user_access('view ' . $type . ' content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 1 votes
There is a module for Drupal 7 and Drupal 8 for that:

View\_unpublished

> This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.

EDIT: Since Drupal 8.6 I guess, the permission "view any unpublished content" is part of the `content moderation` module. Which is included in Drupal core.

# Answer
> 0 votes
Refering to the official Administration guide: https://drupal.org/node/1106606 the module view\_unpublished suggested by Kojo is a quick and easy solution.

# Answer
> 0 votes
A simple, reasonable work-around is to use the 'promote to frontpage' flag on nodes.

If you have no other use for this flag, filter your views on 'promoted to frontpage'. Your content editors can work on the node before it is promoted (by using a direct link). But it will not yet appear to site visitors, potentially.

We got that inspiration from Youtube's 'unlisted video' approach.

# Answer
> 0 votes
If you only need to see the content in a view, disable `SQL rewriting` in `Query Settings` under `Other` in the Views UI.

This works for me as I only want users to be able to unflag unpublished content.

---
Tags: users, nodes
---


# Question
Title: Drupal Elysia Cron Max execution time error, in select.inc
> PHP Fatal error: Maximum execution time of 120 seconds exceeded in /var/www/domainname.com/public/includes/database/select.inc on line 1309

I have an elysia cron command that takes perhaps 10-15 minutes, in the night. The script also starts some jobs with beanstalk, so it takes a while to execute.

When it runs automatically at night I get that above error message. It doesnt make sense, because when I run the command from the terminal it works:

```
drush elysia-cron run elysia_cron_job_name --verbose --ignore-disable --ignore-running --ignore-time

```

And on line 1309 in select.inc is this:

```
public function addField($table_alias, $field, $alias = NULL) {
    // If no alias is specified, first try the field name itself.
    if (empty($alias)) {
      $alias = $field;
    }

    // If that's already in use, try the table name and field name.
    if (!empty($this->fields[$alias])) {
      $alias = $table_alias . '_' . $field;
    }

    // If that is already used, just add a counter until we find an unused alias.
    $alias_candidate = $alias;
    $count = 2;
    while (!empty($this->fields[$alias_candidate])) {
      $alias_candidate = $alias . '_' . $count++;
    }
    $alias = $alias_candidate;

    $this->fields[$alias] = array(
      'field' => $field,
      'table' => $table_alias,
      'alias' => $alias,
    );

    return $alias;
  }

```

Exactly 1309 is: `'table' => $table_alias,`

I've searched the web, and I have no idea where the 120 seconds comes from. I feel like I tried everything. Can someone help?

# Answer
Please note that Drush can use different PHP configuration file for CLI than your Apache, so you need to increase your time in there (`max_execution_time`).

To find where is your PHP config file, run: `drush status`, e.g.

```
$ drush status
...
 PHP configuration               :  /etc/php/7.0/cli/php.ini
...

```

then edit the file and increase your `max_execution_time` to higher value.

Alternatively add the following line in your PHP function which expect to be run by cron for longer time:

```
ini_set('max_execution_time', 0);

```
> 1 votes

---
Tags: database, cron
---


# Question
Title: Reasons for subsequent Broken/missing handler in Views?
In the process of upgrading Drupal 6.x to 7.x I'm facing a problem that makes all my views show nothing relevant. (I believe the problem is here but I'm not sure, I don't know. That's why I'm asking):

After using the migrate field from CCK module in Drupal 7.x most of my views end up with *Broken/missing handler* whether it is in *Field*, *Filters Criteria* or *Relationships*.

On the other side, when using the migrate field module, most of the fields have a message similar to this attached with them. (The field names change.)

> Missing formatter: The 'hidden' formatter used in 3 view modes for the field\_phone field is not available, these displays will be reset to the default formatter.

Or I get this message.

> Changed field type: The 'field\_source\_file' field type will be changed from 'filefield' to 'file'.

Or I get this message one too.

> The field uses the view list\_of\_project\_for\_captain\_log to determine referenceable nodes. You will need to manually edit the view and add a display of type 'References'.

Is this the reason why most the views have a Broken/missing handler than makes them not work properly? If yes, what can I do, if not what else could be the reason for such problems and what should be done?

# Answer
Please follow the following guides:

Also:

* Make sure that you've enabled all the field modules such as image and views related
* *Changed field type: The 'field\_source\_file' field type will be changed from 'filefield' to 'file'* is just information; it's nothing to worry about
* To fix the *Broken/missing handler* message, you have to identify the right modules which provide these handlers and enable them
> 1 votes

# Answer
The simplest thing is that while migration to Drupal 7 you have to maintain the machine names as same. If they change during the migration or don't get migrated due to some reason, you will for sure find views or fields as broken.

You need to be careful while migration for fields those don't migrate. Note them down, either manually create them first on D7 and then run migration or create some custom plugin files for migration of those fields.
> 0 votes

---
Tags: 7, views, upgrading
---


# Question
Title: How can a view in DrupalGap, which is used by a custom module, NOT be cached but instead be called each and every time?
I am using a Local Task Menu as demonstrated in the docs to present one more tab named `members` next to `View` and `Edit`. This tab is showed only to group nodes and i have connected a custom view inside Drupal which fetches the members of this group. Works good. Fetches, displays and links the members in the appropriate page.
But the problem is that this view is called only the first time. In other words, if a user subscribes or unsubscribes from this group after the first call, then this change won't be updated and showed.
In Views `Caching:None` and `Block caching:Do not cache` but i think this is a matter of drupalgap menu cache.
Is there a way i can make this specific view not to be cached but instead be called every time the menu tab is clicked?

# Answer
DrupalGap 7 is a multi-page application, which means as you navigate around, pages that you previously visited remain in the DOM. Then when you navigate back to that page, it is already in the DOM, so it isn't rebuilt.

All you need to do is add the `reloadPage` option to your link and that'll force the page to be reloaded upon navigation: http://docs.drupalgap.org/7/Pages/Reloading\_Pages

```
/**
 * Implements hook_menu().
 */
function my_module_menu() {
  var items = {};
  items['foo'] = {
    title: 'Foo',
    path: 'foo-bar',
    options: {
      reloadPage: true
    }
  };
  return items;
}

```
> 1 votes

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


# Question
Title: How do I check if a node is an organic group in an access callback of a custom module?
In Drupal 7 with Drupalgap, I have created a custom module in order to make a block. I have defined `hook_block_info()` and `hook_block_view()` as it is necessary.
What I want is making this block visible only in organic group nodes. So I need an access callback inside my groups\_menu\_module\_block.js
Below you can see the function but it doesn't seem to work.

```
    function groups_menu_module_block_access_callback(options) {
        return og_is_group('node', Drupal.node.nid);
    }

```

# Answer
You've stumbled across an early design flaw on my part, I didn't realize how important it would be to be able to make `async` calls when determining access to elements (pages, blocks, etc). To get around this (and other related issues), I added some helper functions to DrupalGap core.

The idea behind it is that the built in pages in DrupalGap are there for very simple applications, and more complex applications should build their own pages.

More info: http://docs.drupalgap.org/7/Entities/Rendering\_Entities

The general idea is that you build a custom page(s), which will have a fully loaded entity delivered to its `page_callback` (which under the hood is actually a `pageshow` callback masquerading as a `page_callback`: http://docs.drupalgap.org/7/Pages/Page\_Events).

Then in your `page_callback` when you are building the `content` object you already have access to the fully loaded entity, so you can make intelligent decisions about what is displayed.

With your example (and using the first link above), I'd recommend making a page with a path of `group/%`, and in your `page_callback` you can use custom widgets to simulate the block you are looking to render:

```
function my_module_group_page(node) {
  var content = {};
  content['my_nav_block'] = {
    theme: 'my_module_nav_block',
    node: node
  };
  content['foo'] = { /* ... */ };
  content['bar'] = { /* ... */ };
  content['etc'] = { /* ... */ };
  return content;
}

function theme_my_module_nav_block(variables) {
  var html = '';
  var node = variables.node;
  html += node.title;
  return html;
}

```

In hindsight it was silly of me to try and replicate Drupal's built in pages within DrupalGap (besides the user login/registration pages, etc) because every application should be unique. I now stricly use this approach and no longer use the vast majority of the built-in pages within DrupalGap.

So to answer your actual question, I would recommend building a Views JSON page display which only returns Group nodes, then your app can feed off of that and display a list of Group nodes, that when clicked go to your custom Group page.
> 1 votes

---
Tags: 7, organic-groups, javascript
---


title: Getting the first field item in Twig

text:
# Question
Title: Getting the first field item in Twig
Why does this work in Twig:

```
{{ content.field_image.0 }}

```

but this does not?

```
{% for item in content.field_gallery|slice(0, 1) %}
<div>{{ item }}</div>
{% endfor %}

```

# Answer
At a guess...

`field_gallery`, and other fields, are render arrays; that means they have extra elements in them for the meta data (so called `#` properties). `slice` doesn't know the difference between a render array child element, and a `#` property, so it just chops the array up the same way it would any other. The first item in the array is probably a `#` property, hence nothing is being rendered.

The first example works because you're referencing a specific child of the render array by key, which is then rendered immediately.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How can I pass a query string from the url to a hidden user form field?
I'm building a conference registration site in Drupal 8. I've set up a register link for a custom user role that includes a query string (`/register?reg-id=custom-id`) and would like to pass this value (`custom-id`) back to a hidden field when my form is displayed to my user so that I can have users that are of the same role but with varying `reg-id` depending what they signed up for.

Ideally I would like to set it up using the user fields available under account settings and not through the template settings as more than one template may be used in the future (on a per conference basis). Alternatively a module might work, but I can't seem to find a starting point for this in Drupal 8. As a side note the `custom-id` is generated from a taxonomy term field on the referring page - just in case there an option to feed the form the variable another way.

I have looked at the following, and numerous others, but they don't quite meet the requirements for my use case:
How to retrieve GET parameter in Twig template
https://www.drupal.org/project/userreference\_url (seems ideal but not ported to D8)
How do I pass a value from the url to a custom field in the registration form? (for D7)

Any assistance would be greatly appreciated.

# Answer
You may be able to do a `hook_form_alter()` and call `\Drupal::request()->query->all()` (or `\Drupal::request()->query->get('reg-id')`) to access the query parameters to pass it to your hidden form field.

See https://api.drupal.org/api/drupal/vendor%21symfony%21http-foundation%21Request.php/property/Request%3A%3Aquery/8.2.x and https://www.drupal.org/node/2150267.

For example:

```
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, FormStateInterface $form_state) {
  // Get the query parameter with 'reg-id' if it exists.
  if ($custom_id = \Drupal::request()->query->get('reg-id')) {
    $form['hidden_field'] = // Do whatever you need here;
  }
}

```
> 2 votes

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


title: Use CONVERT(AES_ENCRYPT()) in query

text:
# Question
Title: Use CONVERT(AES_ENCRYPT()) in query
I am trying to enter a query with a field 'Convert (aes\_encrypt ())' and also use it as a variable in a subquery.

```
$string = 'CONVERT(AES_DECRYPT(d.column, "key")USING utf8)';
$query = db_select('demo' 'd');
$query->field('d', $string);

```

And use this at once as a sub query

```
$query->condition($string, $subquery, 'IN');

```

Thank you

# Answer
> 0 votes
You want an expression for the selected field:

```
$query = db_select('demo' 'd');
$query->addExpression($string, 'd');

```

I'm not sure what you're going for with the sub query bit, if you update the question with the desired SQL it should be straightforward to tell you whether it's possible with a `SelectQuery`.

---
Tags: database
---


# Question
Title: Imageapi Optimize - enabled libraries exec
I'm investigating Imageapi Optimize module and everything is quite clear except one thing. There is a list of internal libraries on UI which can be enabled and set the order of it. So, for example if first library is set to pngquant and second is optipng and both are enabled, what does the second one do?

I assume, when the image is being displayed pngquant process the image and it's being compressed. After the compression the image already have the desired size, so what does the second one do? I've searched through all the web and the module code and I can't really find out what is the logic behind it. I suppose it should be radio buttons rather then checkboxes.

# Answer
> so what does the second one do?

It'll optimise the already-optimised image from the previous plugin as best as it can. Which won't be much.

> I suppose it should be radio buttons rather then checkboxes.

Perhaps; but that would remove the ability to have combinations of different kinds of plugins (not just file size optimisers) in the future, so it might be a bit short-sighted to say that.
> 1 votes

---
Tags: 7, media
---


# Question
Title: Put blocks, views, etc in git for other developers
Keep in mind that I'm fairly inexperienced with drupal!

I use a docker based setup for my development environment for docker 7. I'm building a site that involves a front page that will be changed infrequently but I still want the key users to change what's necessary.

I'm firing up the drupal docker with `my_theme` mapped to `/var/www/sites/all/themes/my_theme` and the following is executed in the docker container:

```
# Install zen theme (needed for the sub-theme)
/usr/local/bin/drush -r /var/www en zen -y
# Install base modules
/usr/local/bin/drush -r /var/www en views, entity, pathauto, devel_node_access, backup_migrate, imce, link_css, jquery_update, ckeditor, farmmix -y
# Set our theme as default
/usr/local/bin/drush -r /var/www vset theme_default farmmix
# Disable old theme
/usr/local/bin/drush -r /var/www dis bartik -y
# Enable/Install permissions
/usr/local/bin/drush -r /var/www en views_ui, entity_token, views_content, admin_devel, color, contextual, dashboard, field_ui, file, image, list, locale, number, options, overlay, search, shortcut, taxonomy -y

```

This installs and enables the modules I need for development. What this does **NOT** do is create content types, blocks, views, etc that might be necessary for this site.

It would be ridiculous to recreate these essentials for the site each time a new instance is spun up (e.g: another developer starts to work on it). How can I put content types, blocks, views etc in git so if another developer checks it out, he can continue where I just left off?

Only backup and migrate helps?

# Answer
> 1 votes
You have several modules that allow to export configuration changes (like views, blocks, content types etc) into code. One is features and the other is configuration Features is much more heavily used and configuration isn't supported by the security team, so I tend to use Features. There are a number of good tutorials on using Features, like this one. Once you create a feature, it will exported into a code-based collection of files under custom modules, which you can then share with git.

The one caveat is that using Features (or any config changes module for that matter) in a collaborative environment can become tricky: team members have to be mindful of the branches and feature versions they are working with. For example, switching from a branch where feature was installed to a branch that does not have that feature can throw fatal errors because GIT will remove the feature files according to the branch but the database will still look for the feature. In such a case you can disable the feature before switching branches or install the feature in all the branches you are working in.

---
Tags: 7, views, blocks, version-control
---


# Question
Title: Make URL from 1 field available to another field [Drupal 8]
Drupal 8 Twig question:

I have 2 fields: textfield and a linkfield.

When the linkfield is filled, the text entered in the textfield should become the link. I cannot edit the node.html.twig for this, I want to do this in the field--textfield.html.twig to include the URL (if it is set).

But I don't know how to make the URL from "field--linkfield.html.twig" available in "field--textfield.html.twig"

*(Needed because the link module is still a little bit broken in Drupal 8 (no optional URL possible)).*

# Answer
> 0 votes
If you want to get a field value from another field in a field template you have to use the parent entity (in your case a node) `element['#object']`:

```
{{ element['#object'].field_textfield.value }}

```

or a url from a link field:

```
{{ element['#object'].field_linkfield.0.url }}

```

---
Tags: theming, 8
---


title: How do I add a hash link in menus?

text:
# Question
Title: How do I add a hash link in menus?
Is there a way to add a hashed link in the menu under drupal menu to just make a menu item that jumps down to an anchor or id on the page?

# Answer
> 16 votes
Unfortunately Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.

> Special menu items is a Drupal module that provides placeholder and separator menu items.
>
> A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it. A separator menu item is something like "-------" which is not linking anywhere but merely a mean to structure menus and "separate" menu items visually.

The module has a Drupal 7 release, created on July 18, 2019. Its functionality has been incorporated in Drupal 8, which means it's not necessary to install it, on a Drupal 8 site.

# Answer
> 16 votes
Follow what reported in a comment for the `l()` documentation.

> To create a link to a named anchor (e.g. "#namedanchor"), you will need to use a small work-around.
>
> ```
> l('linktext', '', array('fragment' => 'namedanchor', 'external' => TRUE));
>
> ```
>
> To create a hash-only link (to "#"), you'll need to adapt it to:
>
> ```
> l('linktext', '', array('fragment' => ' ', 'external' => TRUE));
>
> ```
>
> (Note that the fragment does contain a space.)

In Drupal 7, set "HTML" to `TRUE`, then append the hash character.

# Answer
> 15 votes
http://drupal.org/node/123103#comment-4955236

> node/16#gohere
>
> the auto url will change it to be like
>
> about-us#gohere

# Answer
> 7 votes
Try use module Void Menu:

> Void menu allows you to configure special values to tags for use in the Drupal 7 menu system. You can customize up to 10 different void tags with any value you wish and use them freely inside the Drupal menu system.
> ...
> As an added bonus, and because of the functionality of this module, you are also able to use actual anchors as menu items that serve no other purpose than placeholders. This is accomplished with a void tag that is set to javascript: void(0); or even a simple hash tag #. The benefit to using this module over special\_menu\_items for this is that your menus will not require any additional styling to account for the added span tags used by special\_menu\_items, and will be W3C valid because every anchor must have an href attribute.

It's a very nice solution!

# Answer
> 2 votes
Just encountered the same problem. I needed to programmatically add menu-items with hash-links. My code:

```
// the URL with hash in it is in the form  'normal_part_of_url'#'hash_part_of_url'
$item = array(
  'link_path' => %normal_part_of_url%,
  'link_title' => %your_link_title%,
  'menu_name' => %menu_where_to_add_links%,
  'options' => array('fragment'=>%hash_part_of_url%)
);
menu_link_save($item);

```

# Answer
> 2 votes
Just setting `external` to `TRUE` does it for me. Tested in Druapl 7.32.

`l('Some Name', '#', array('external' => TRUE));`

# Answer
> 1 votes
Using Drupals translation functions also works.

```
/**
 * Implements hook_menu().
 *
 * Defines a valid link to use when creating menu items.
 */
function greenacorn_menu() {
  $items['<main-content>'] = array(
    'page callback' => 'drupal_not_found',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Implements hook_menu_link_alter().
 *
 * Flags the link to be altered at runtime.
 *
 * Note: Changes here would be saved back to the database.
 */
function greenacorn_menu_link_alter(&$item, $menu) {
  if ($item['link_path'] == '<main-content>') {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Implements hook_translated_menu_link_alter().
 *
 * Refactors the link to go to the fragment #main-content.
 */
function greenacorn_translated_menu_link_alter(&$item, $map) {
  if ($item['link_path'] == '<main-content>') {
    $item['href'] = '';
    $item['localized_options']['fragment'] = 'main-content';
  }
}

```

# Answer
> 1 votes
```
function test_menu() {
  $items = array();
  $items['sample'] = array(
   'title' => t('Sample page'),
   'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'page callback' => 'samplepage',
    'access callback' => TRUE,
    'options' => array('fragment' => 'sampleHash'),
  );
  return $items;
}

```

You can add hash link to menu using above code.

# Answer
> 1 votes
```
/**
 * Implements hook_module_implements_alter().
 */
function MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'url_outbound_alter') {
    $stored = $implementations['MODULE'];
    unset($implementations['MODULE']);
    $implementations['MODULE'] = $stored;
  }
}

/**
 * Implements hook_url_outbound_alter().
 */
function MODULE_url_outbound_alter(&$path, &$options, $original_path) {
  if (strpos($path, '#') !== FALSE) {
    $fragment = substr($path, strpos($path, "#") + 1);
    $path = str_replace('#' . $fragment, '', $path);
    $options['fragment'] = $fragment;
  }
}

```

# Answer
> 1 votes
**install Special menu items and DHTML Menu for hierarchical menus then:**

* add your x-example vocabulary and add to it your terms
* click modify x-example than in taxonomy menu section set menu location
* go to the blocs set the menu to a bloc
* in the menu admin modification you see the terms added automatically
* click on modify a menu item then past this `<void>` in the target

> now back to your home page and you will see that the menu item that we have modify in the click those not go anywhere

---
Tags: 7, routes
---


title: Loading mixed content

text:
# Question
Title: Loading mixed content
I have a site loading over https. However, two items are being picked up in Chrome as targeting http, and I can't figure out where to look to change them. They are:

1. GSS search form: we are using Google Site Search module, and it's posting to http.
2. Drupal Views are posting to http, rather than https. Not sure how to override this.

Any help would be greatly appreciated. Thanks!

# Answer
If you force https, then these search forms and views should load properly. There are several ways to do this:

1) If you have access to server config, this tutorial covers Apache, Nginex and Ubunto.

2) You can also use .htaccess to force https as described in this codekarate tutorial.

3) Also you can use a module like securelogin to further protect your login forms from mixed http/https cookie hijacking.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Form fields created via Ajax are missing element attributes
I have a custom form with a date field and a series of textfields and number fields. The textfields and number fields are dynamically re-created via an ajax callback function that runs whenever the date field changes, because the default values of the textfields and number fields will depend on the value of the date field.

The form runs this function once upon loading, which works fine, it returns the $form object with all expected values in the fields.

However, whenever that same function is called again by the ajax trigger, almost all of the attributes of the dynamic fields are missing. The `data-drupal-selector`, `id`, `name`, and `value` attributes are gone. The default values do not appear. The `for` attribute of labels also disappears.

I have noticed that this is not true of `table` form API elements and only seems to affect input elements and labels.

Is this the expected behaviour? Is it avoidable?

Example:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['date'] = array(
        '#type' => 'date',
        '#ajax' => [
            'callback' => '::dateCallback',
            'wrapper' => 'wrapper',
        ],
        '#default_value' => date("Y-m-d")
    );
    $form['wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'wrapper'],
    ];
    $this->dateCallback($form, $form_state);
    return $form;
}

/**
 * Implements callback for Ajax event on date selection.
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Date selection section of the form.
 */
public function dateCallback(array &$form, FormStateInterface $form_state) {
    //insert logic to determine value of a variable called $field1

    $form['wrapper']['options'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('options'))
    );
    $form['wrapper']['options']['field1'] = array(
        '#type' => 'textfield',
        '#title' => "Field 1",
        '#default_value' => $field1
    );
    $form['wrapper']['table'] = array(
        '#type' => 'table',
        '#title' => t('Table'),
        '#header' => array("H1", "H2", "H3"),
        '#attributes' => array('class' => array('custom-table'))
    );
    //insert logic to generate table rows
    return $form['wrapper'];
}

```

(Note: In order to get ajax to work with date fields, as per my previous question, I had to apply a Drupal patch. However, I am pretty sure this issue is not related to this patch, as the problem persists even if I attach the callback to another form APi element like a Select dropdown.)

# Answer
It seems like a good idea to invoke the callback in the form build to include the form elements of the callback in $form to allow the form builder to process these elements. But then you overwrite the same form elements that the form builder has processed with the unprocessed form elements when the ajax triggers the callback.

Solution: Move all form elements in buildForm(). Leave the callback empty, only return the wrapper part of the form.
> 1 votes

---
Tags: 8, forms
---


title: Style Views without preprocess

text:
# Question
Title: Style Views without preprocess
I created basic custom - made layout in Drupal 7 by setting up ( layout.info html.tpl.php page.tpl.php style.css )

I have also created Views in order to filter some certain content (text and photo). Is there a way to theme the Views but without preprocess functions. So no coding in the template.php ? How to do that if it is possible?

# Answer
> 0 votes
Well you could always assign custom CSS classes to each field and target them for styling. Template.php file should be used more for a data manipulation purpose anyway, rather than styling.

# Answer
> 0 votes
> Is there a way to theme the Views but without preprocess functions.

Views usually provides handy CSS classes and wrappers by default. You can configure them in the format and field settings.

In addition, you can also override the templates of views in the same way you override other parts of Drupal with templates. Under the Advanced pane, there should be a theme information link. Click that and it will show you the template filename suggestions for the different parts of the view. They're listed lowest to highest with the actively used one in bold.

Like in regular templates, create a file with the suggested file name, modify the suggested template, clear the cache, and view your... view.

---
Tags: views
---


title: How do I uninstall RSS?

text:
# Question
Title: How do I uninstall RSS?
I would like to uninstall RSS completely from Drupal 8, not only hide it from pages, but also disable the core logic behind it.

How do I achieve it?

# Answer
I am not sure where you encounter RSS, but I am only aware of it being on the front page. That feed is generated from a second display on the frontpage view:

Other modules might define their own feeds in a similar fashion, but I have not found them yet.

There is no such thing as 'disable RSS', so you cannot disable it globally.
> 0 votes

---
Tags: feeds, installation
---


# Question
Title: Ajax InvokeCommand with custom Callback Primary tabs View(active tab)
I tried to do a what described in https://api.drupal.org/comment/56868#comment-56868, but for Drupal 8.

```
Drupal.behaviors.corsFileAutoUpload = {
  attach: function (context) {
    $(context).find('input[type="file"].s3fs-cors-upload').once('auto-s3file-upload').on('uploadToS3', Drupal.s3fs_cors.uploadToS3);
    },
}

```

To invoke this from PHP, I used the following code.

```
$response->addCommand(new InvokeCommand($selector, 'uploadToS3');

```

But I got an error from core/misc/ajax.js line number of 1266, as the method for the element is not available. On inspecting eventlistener in Chrome, it was very well visible and I was also able to fire it from Browser Console. I am missing something here. How do we call a custom jQuery function using `InvokeCommand`?

# Answer
> 3 votes
In the JS side try with this:

```
(function($) {
  $.fn.uploadToS3 = function() {
    // Your code here.
  };
})(jQuery);

```

the PHP part looks ok to me.

# Answer
> -1 votes
What's your selector, where you're trying to trigger the method ?? This won't be available according to your error. I guess you have an event/method mixup.

To trigger a custom event do something like:

```
new InvokeCommand('html', 'trigger', array(
  'your_bound_event',
  array('param1', 'param2'),
)));

```

And in your behavoir:

```
$(document).on('your_bound_event', function(ev, param1, param2) {
  console.log('hit');
});

```

---
Tags: 8, javascript
---


# Question
Title: A line feed gets added in the "Let's Encrypt Challenge"
I am using the Let's Encrypt module for Drupal 7, trying to follow the instructions outlined here by Redfin Solutions, to install free SSL on Acquia's servers, but I've run into a curious problem:

Each time I generate the challenge using the certbot manual mode (using `sudo certbot certonly --manual -d example.com`), It tells me the key authorization file from the server does not match the challenge.

> Failed authorization procedure. example.com (http-01): urn:acme:error:unauthorized :: The client lacks sufficient authorization :: The key authorization file from the server did not match this challenge
> \[TBgi6LPQfn7SJOTMcA67Crjrb\_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI\] != \[ TBgi6LPQfn7SJOTMcA67Crjrb\_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI\]
>
> IMPORTANT NOTES:
>
> * The following errors were reported by the server:
> Domain: example.com
> Type: unauthorized
> Detail: The key authorization file from the server did not match this challenge \[TBgi6LPQfn7SJOTMcA67Crjrb\_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI\] != \[TBgi6LPQfn7SJOTMcA67Crjrb\_wGI9WKL4XAE-a17io.x6url1PIuenF6WDlPejYYJM2E4fg3wOFn8t4ghXDAGI\]
>
> To fix these errors, please make sure that your domain name was entered correctly and the DNS A record(s) for that domain contain(s) the right IP address.

As you can see, the second one (which is the one in the server), shows with a linefeed at the start. I am baffled by this, I went into the module and it just displays the value saved in a system variable, which I verified in the database. Other than that they seem to be identical, I have not been able to go further. Has anybody experienced anything similar? Any suggestions on how to fix this?

# Answer
> 0 votes
Turns out the module works like a charm, the problem was theme related, sending out a blank line at the top of the page: this was enough to confuse Let's Encrypt when running the validation of the site.

---
Tags: 7, ssl, acquia-cloud
---


# Question
Title: Drupal 7 Commerce Stock - Setup stock rules on purchase success for all line items?
Currently im trying to setup the stock rules for drupal 7 commerce, but I'm not sure how to go about setting up the rules to deduct stock on purchase success. I have the following: http://prntscr.com/24d0b5

As for the following action: Decrease the product stock level, given a line item

I have this: http://prntscr.com/24d0u8

Currently it only applies to line-item:0 , But how do I make it apply to all line items? Can someone take a snapshot of how their configuration is for this stock rules setup?

thanks

# Answer
Firstly, make sure there is a Line items loop(Data Selector -\> commerce-order:commerce-line-items). Then While adding the action, please make sure it is added to the already added Line item Loop(you will find under the 'operations' tab) and NOT as a new 'Add action' at the bottom.
> 0 votes

---
Tags: 7, rules, commerce
---


# Question
Title: How can I tell which Feature something belongs to?
I am working on a site that has maybe 100 different Features. I am editing a block, which I assume is attached to a Feature.

Without looking through each Feature individually, how can I tell which Feature this block belongs to (or even if it is Featured at all?

# Answer
You can search in your editor or your repository for your 'block\_machine\_name'. It must have been referenced in the respective feature.
> 0 votes

---
Tags: 7, features
---


# Question
Title: How Can I send full content body field by simplenews_content_selection?
I use the drupal 7 and simple news content selection module for simplenews.

When select an existing content for send by simplenews only the title of its content add to simplenews sent mail.

I want to send whole content (the full body field) of selected content by simplenews.have any idea?

thanks before hand

# Answer
> 0 votes
I have found my solution.

In content type **manage display** setting , for `simplenews content selection` view mode the `body` field must be visible .

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


# Question
Title: Add node reference to Product field with rules
I am working on a rule to create a node based on a commerce product after it is purchased. So far I've been successful in creating the entity and filling in fields from the product fields. I am having trouble updating a field within the product to reference the node created by it's sale. I'm not receiving an error, but the product field is not updating. I've tried multiple configurations. Here's the rule exported:

```
{ "rules_create_projects_from_sold_instrumentals" : {
"LABEL" : "Create Projects from Sold Instrumentals",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_order", "rules_conditional", "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"IF" : [
  { "commerce_order_contains_product_type" : {
      "commerce_order" : [ "commerce_order" ],
      "product_type" : { "value" : { "instrumental" : "instrumental" } },
      "operator" : "\u003E=",
      "value" : "1"
    }
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "CONDITIONAL" : [
            {
              "IF" : { "entity_has_field" : { "entity" : [ "list-item" ], "field" : "commerce_product" } },
              "DO" : [
                { "CONDITIONAL" : [
                    {
                      "IF" : { "data_is" : {
                          "data" : [ "list-item:commerce-product:type" ],
                          "value" : "instrumental"
                        }
                      },
                      "DO" : [
                        { "entity_create" : {
                            "USING" : {
                              "type" : "node",
                              "param_type" : "recording",
                              "param_title" : [ "list-item:commerce-product:title" ],
                              "param_author" : [ "commerce-order:owner" ]
                            },
                            "PROVIDE" : { "entity_created" : { "pr_created" : "PR Created By Instr Order" } }
                          }
                        },
                        { "data_set" : {
                            "data" : [ "pr-created:field-recording-cover-art" ],
                            "value" : [ "list-item:commerce-product:field-cover-art" ]
                          }
                        },
                        { "data_set" : {
                            "data" : [ "pr-created:field-pr-producer" ],
                            "value" : [ "list-item:commerce-product:field-producer" ]
                          }
                        },
                        { "entity_save" : { "data" : [ "list-item:commerce-product" ], "immediate" : "1" } },
                        { "CONDITIONAL" : [
                            {
                              "IF" : { "entity_has_field" : { "entity" : [ "list-item:commerce-product" ], "field" : "field_project" } },
                              "DO" : [
                                { "list_add" : {
                                    "list" : [ "list-item:commerce-product:field-project" ],
                                    "item" : [ "pr-created" ],
                                    "unique" : "1"
                                  }
                                },
                                { "entity_save" : { "data" : [ "list-item:commerce-product" ], "immediate" : "1" } }
                              ]
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  }
]

```

Any ideas?

# Answer
> 1 votes
You rule seems to be using the Conditional Rules module ... which does not play well with saving entities like your rule seems to be doing.

You should rework those parts of your Rules Actions to performing equivalent Rules Components. After doing so, you have taken away a possible reason why your rule does not seem to behave as you would expect ... and possibly also solved your issue. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

*Debugging is the art of taking away all possible reasons why something doesn't work as you'd expect it to work ...*

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

---
Tags: commerce
---


title: Why won't my batch finish?

text:
# Question
Title: Why won't my batch finish?
I have setup a Batch work which looks the following (dump at run time).

The method called for each batch is a public static method, so that is not a problem.

All operations performs perfectly, my nodes are imported in the system, this I'm sure.

The problem is that the Batch progress bar never reaches the 100% and after a few seconds, goes back and forth forever. This clearly happens after all my nodes are processed.

My *finished* callback is never called and I'm stuck on the Batch API progress bar for years :-)

Any idea on what I could be missing?

Thank you.

# Answer
So, nothing was wrong with my batch definition, but I tried to disable the web profiler module and everything gets back to normal!
> 0 votes

---
Tags: 8, batch-operations
---


# Question
Title: Form implemented using form_alter not always showing the changed contents in select list
I have created a module to alter a select dropdown of a view's exposed filter like this

```
function myform_form_alter(&$form, &$form_state, $form_id) {

   if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-staff-page") {
$form['field_department_tid']['#type'] = "select";
    $form['field_department_tid']['#size'] = null;
    $form['field_department_tid']['#default_value'] = $form['field_department_tid']['#options']['All'];
    $form['field_department_tid']['#options'] = array(
      'All' => t('All Offices'),
      '6' => t("Office of the Chairman"),

'Administration & Financial Affairs Department' => array(
            '2'=> t('Administration'),
            '3' => t('Finance'),
            '4' => t('HR'),

         ),

    );
 }

```

But occasionally it is showing the original unaltered select list instead of the new select list and in such cases, I need to clear cache every time to display the changed dropdown.

What is the problem with my code?

# Answer
> 0 votes
Try this way

Change

`$form['field_department_tid']['#default_value'] = $form['field_department_tid']['#options']['All'];`

to

`$form['field_department_tid']['#default_value'] = t('All Offices');`

---
Tags: views, forms, hooks
---


title: Webform + Translations

text:
# Question
Title: Webform + Translations
I have a website where 80% of it are Webforms. Admins can create webforms themselves and registered users can fill them in. ( A PDF will be created etc etc...).

Now I have to make this website in 3 other languages then the default.

I Found already the following module:

https://www.drupal.org/project/webform\_localization

**Now my initial question:**

Imagine you have a webform in the wizard with a label, and a textarea and a default value as type or static text. What is the best way to get the 'default' values in the context translated?

**Example** https://i.stack.imgur.com/t4uLi.png

Note: This is text which got changed for every webform generated on the website.

# Answer
This is content - not static text; your only options are to translate it manually yourself or use one of the contrib modules like Lingotek or Cloudwords.
> 1 votes

# Answer
If you use Entity Translation (recommended), you can use the Webform Translation module.
> 0 votes

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


# Question
Title: Custom (cck) fields are being ignored during the migration using migration-tools 4.x. Only title and body is imported. How do I fix this?
I'm running a migration from Drupal 6 to Drupal 8, following roughly the advices in the http://pnijjar.freeshell.org/2017/drupal8-migrate/ guide.

At the moment, only title and body for each node is being imported for each node, despite definitions being correctly put into the .yml files generated by `drush migrate-upgrade --configure-only` . See an example `migrate_plus.migration.d6_node_event.yml` below.

I can't figure out what is wrong.

```
uuid: 51bc9a5e-6caf-4b7a-9b08-e34312467c89
langcode: en
status: true
dependencies: {  }
id: d6_node_event
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 6'
migration_group: migrate_drupal_6
label: 'Nodes (event)'
source:
  plugin: d6_node
  node_type: event
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration_lookup
    migration: d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_organization:
    plugin: iterator
    source: field_organization
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format
  field_startend:
    plugin: iterator
    source: field_startend
    process:
      value:
        plugin: format_date
        from_format: U
        to_format: U
        source: value
  field_event_venue:
    plugin: iterator
    source: field_event_venue
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format
  field_event_speakers:
    plugin: iterator
    source: field_event_speakers
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format

...

```

# Answer
> 0 votes
What version of migrate\_upgrade are you using? I see things like

```
      plugin: migration
      migration:
        - d6_filter_format
        - d7_filter_format

```

there, but --configure-only should have generated

```
      plugin: migration
      migration:
        - upgrade_d6_filter_format
        - upgrade_d7_filter_format

```

# Answer
> 0 votes
Solved. I've made a wrong assumption that the import of nodes of one individual node type will have the fields setup as its dependency. But it's not so.

When I run the entire migration group it creates the fields as expected.

Now I'm facing another issue - terms are not being assigned https://www.drupal.org/node/2653984

---
Tags: 8, migrations
---


# Question
Title: Hide Uploaded Files in File Field in Node Edit Form
I have a custom content type, Contacts. Under contacts I have a custom File field, Contracts.

I want to hide the any file that have been uploaded under the File Field, Contracts in the node edit form. It should be view-able only by the admin.

I want to display the upload option in the field to all the users, however, not the files that have already been uploaded under the node.

Please advice

Thanks

The modified code:

MODULE NAME = Hide\_Uploaded\_Files.

CONTENT TYPE = Candidates.

CUSTOM fIELD = field\_resume.

```
<?php
function Hide_Uploaded_Files_form_alter(&$form, &$form_state, $form_id) {
global $user;
if ($form_id === 'Candidates_node_form' && !in_array('administrator', $user-
>roles) && $form['field_resume']['und'][0]['#default_value']['fid'] > 0) {
$form['field_resume']['#access'] = FALSE;
}
}
?>

```

# Answer
> 1 votes
Create a custom module and implements `hooK_form_alter().` and set field access to false for other user except administrator.

```

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id === 'CONTENTTYPE_node_form' && !in_array('administrator', $user->roles) && $form['field_image']['und'][0]['#default_value']['fid'] > 0) {
    $form['field_image']['#access'] = FALSE;
  }
}

```

# MODULENAME = Your costom module machine name.

# CONTENTTYPE = Your content type machine name.

# field\_image = Your custom file field machine name.

---
Tags: 7, files
---


title: Clearing the cache_block in Drupal 8.x

text:
# Question
Title: Clearing the cache_block in Drupal 8.x
I'm currently porting a Drupal module from 6.x -\> 8.x. One of the lines in that module:

> cache\_clear\_all('##NAME\_OF\_THE\_BLOCK##', 'cache\_block', TRUE);

The cache\_clear\_all method does no longer exist in Drupal 8.x. I cannot find now where the 'cache\_block' is situated. I'm looking for a way to flush this cache - and I don't want to flush 'all' cache ...

Any idea's what the D8 equivalent of this line is?

# Answer
The D8 equivalent is cache tags and it kind of works in the reversed way.

What exactly is changing that requires you to invalidate the cache? Identify that, if it has a cache tag (e.g. a config object or an entity) then just make sure your block adds the cache tag for it and you're done.

To figure out if a cache tag invalidation happens, you can truncate the cachetags table, then make the change and check that table for new entries.

If there is no cache tag yet for that event, then you can define one yourself, add it to the render array or getCacheTags() of the block plugin and invalidate it with Cache::invalidateTags().

I would not recommend to do what @Clive suggested because unlike 7.x, your block plugin (assuming it is a plugin not just one specific block instance) can be re-used many times, even with page\_manager/panels.
> 1 votes

---
Tags: 8, caching
---


title: Cannot manage footer menu

text:
# Question
Title: Cannot manage footer menu
I want to manage my footer menu, but I get this error:

```
The website encountered an unexpected error. Please try again later.

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "contact.site_page" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of core/lib/Drupal/Core/Routing/RouteProvider.php).
Drupal\Core\Routing\UrlGenerator->getRoute('contact.site_page') (Line: 269)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('contact.site_page', Array, Array, 1) (Line: 105)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('contact.site_page', Array, Array, 1) (Line: 753)
Drupal\Core\Url->toString(1) (Line: 167)
Drupal\Core\Utility\LinkGenerator->generate('Contact', Object) (Line: 94)
Drupal\Core\Render\Element\Link::preRenderLink(Array)
call_user_func(Array, Array) (Line: 376)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 183)
__TwigTemplate_c1bdd8f86c8cc62844cbb93f33c11d8a2e27610acf3c1abe4f7e3e1886bfcf45->doDisplay(Array, Array) (Line: 379)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 347)
Twig_Template->display(Array) (Line: 358)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/themes/classy/templates/dataset/table.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('table', Array) (Line: 435)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 149)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

```

Maybe it's caused by contact module, but I hav uninstalled it.

# Answer
> 0 votes
Yes it is because you uninstalled the contact module. Try to install it again, then reset/delete that menu link from it and then uninstall it again.

---
Tags: 8, navigation
---