# Question
Title: How do I resolve a merge conflict with features?
This might seem basic, but I am new to Drupal (and, to and extent, git).

I've made some changes to a Feature and downloaded its files to be pushed up to the remote server with git. However, I get the following merge conflict:

```
<<<<<<< HEAD
  $pane->uuid = '992af322-74c5-4a5c-a261-1e73677d3645';
  $display->content['new-992af322-74c5-4a5c-a261-1e73677d3645'] = $pane;
  $display->panels['content'][2] = 'new-992af322-74c5-4a5c-a261-1e73677d3645';
=======
  $pane->uuid = 'bf806592-c85c-4155-a97c-516f72427e4e';
  $display->content['new-bf806592-c85c-4155-a97c-516f72427e4e'] = $pane;
  $display->panels['content'][2] = 'new-bf806592-c85c-4155-a97c-516f72427e4e';
  $pane = new stdClass();
>>>>>>> refs/heads/my-branch

```

I would know what to do with a conflict with other code, but this is all very foreign to me and I don't want to break anything.

Would anyone know the best course of action here?

# Answer
> 1 votes
Check the panes with the following uuid "bf806592-c85c-4155-a97c-516f72427e4e" and "992af322-74c5-4a5c-a261-1e73677d3645". Check which one should not be there and remove it from the code.

# Answer
> 0 votes
You just have to decide which one you will keep. If there are more that one person working on the feature then it is a good idea to wait for the other person to finish his/her modification and pull that later when he/she is done.

---
Tags: 7, features
---


# Question
Title: How can we uninstall a module directly from the database?
I am trying to find a way to uninstall a Drupal 8 module directly from database.

How can I achieve this?

# Answer
> 0 votes
You can use

1. `drush pm-uninstall`.
2. If you have entities in your module, write a query in your module to first delete all entities of your particular entity type. Once deleted, remove that file where you have written annotation for your entity, create a backup for use later. Except `.info.yml` file and `.install file`, remove all files.

Now you can easily un-install that module. Once un-installed, put all your backed up files into your module folder again, install your module and go!

---
Tags: installation
---


title: How can I use hook_views_query_alter()?

text:
# Question
Title: How can I use hook_views_query_alter()?
How can I implement `hook_views_query_alter()` in Drupal 8?

In Drupal 7, I could use the following code.

```
$args = arg;
$node = menu_get_object();

if ($args[0] === 'my_view') {
  $query->orderBy('node_field_data_created','ASC');
  if (!empty($node) && $node->type == 'category') {
        $filters = $query->getFilters();
        $first_filter = $filters[0];
        if ($first_filter['#value'] == "(category) AND node_field_data.status:(1)") {
            $query->condition('field_category', $node->nid, '=');
        }

```

In Drupal 8, this code doesn't work.

Can anyone help me out?

# Answer
According to the documentation page for `hook_views_query_alter()`, this hook works in Drupal 8, but (as you can see in comments for the referenced article) you should place it in mymodule.views\_execution.inc, not in mymodule.module.
> 1 votes

# Answer
Use it in .module file and change any query as you like

```
/**
     * Implements hook_views_query_alter().
     */
    function module-name_views_query_alter(\Drupal\views\ViewExecutable $view, $query) {

      if ($view->id() == 'example' && $view->current_display == 'example') {
        if (!empty($view->exposed_raw_input['company_name'])) {
          foreach ($query->where as &$condition_group) {
            foreach ($condition_group['conditions'] as &$condition) {
              if ($condition['field'] == 'node_field_data.type') {
                $condition = array(
                  'field' => 'node_field_data.type',
                  'value' => 'abc',
                  'operator' => '=',
                );
              }
            }
          }
        }
      }
    }

```
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to get firstname in autocomplete when adding new members in og group?
I have created the group in og.

When adding the user for the group, In autocomplete its been displaying the user's email ID.

```
function custom_form_alter($form,&$form_state){ if($form['#id']== 'og-ui-add-users'){
     $form['og_user']['name']['#autocomplete_path'] = 'user/autocomplete';
}

```

}

But I want to get the name instead of email ID.

I have tried to change the user/autocomplete in hook\_form\_alter,but its displaying email id only

Is there any way to get name instead of email ID ?

Tell me how to sort out this problem?

# Answer
I didn't get a clear idea, anyway please Check This.
> 0 votes

---
Tags: 7, organic-groups, ajax
---


title: How can I get node creation date?

text:
# Question
Title: How can I get node creation date?
How can I get node creation date and convert it to custom format in my theme, I tried to make some operations on node date in "MyTheme.theme" file and in `preprocess_node` section.

# Answer
> 11 votes
Code for getting node created date.

```
$date = $variables['node']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom PHP date formatting.
  $variables['date'] = \Drupal::service('date.formatter')->format($date, '$format');// enter date format in $format.

```

# Answer
> 2 votes
Thanks for your answer. If you want to use a custom date format, you have to declare it this way:

```
$variables['date'] = \Drupal::service('date.formatter')->format($date, 'custom', '$format'); // Where $format is a PHP date string like 'M Y'

```

---
Tags: theming, 8, nodes, datetime
---


title: jQuery.ajax() results in a 403 error

text:
# Question
Title: jQuery.ajax() results in a 403 error
I created a custom block and I was trying to use the ajax method of jQuery, but it seems that whenever I access the method of the controller, it returns a 403 error.

This is my contoller (custom\_blocks/src/Controller/CustomBlocksController.php)

```
namespace Drupal\custom_blocks\Controller;
use Drupal\Core\Controller\ControllerBase;

class CustomBlocksController extends ControllerBase
{
  // $variable is the wildcard from the route
  public function ajaxCallback($variable)
  {
    return ucwords($variable);
  }
}

```

This is my routing file (custom\_blocks/custom\_blocks.routing.yml).

```
my.route:
  path: '/sample-page/{variable}'
  _defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
    _permission: 'access content'
    _access: 'TRUE'

```

This is my custom JavaScript code (custom\_blocks/js/command.js).

```
(function($, Drupal) {
     $('#custom-button').click(function(){
        var name = 'john doe';
        $.ajax({
             type : "POST",
             url: '/sample-page/' + name,
             success : function(response){
                  console.log(response);
             },
        }, 'html');
     });
})(jQuery, Drupal);

```

Hope someone can help me.

# Answer
That's because by default Drupal only allows GET request on default controllers. In your case you should create a custom resource.

Using resources has multiple advantages:

1. No custom paths per request method
2. Access control
3. CSRF protection
4. Using the API that the REST module in Drupal 8 provides

It basically comes down to creating a class with an annotation:

```
             /**
              * @RestResource(
              *   id = "my_resource",
              *   label = @Translation("Resource label"),
              *   uri_paths = {
              *     "canonical" = "/sample-page"
              *   }
              * )
              */
             class CustomResource extends ResourceBase {
                public function post($data) {
                  // Do stuff with the posted data.
                }
             }

```

Some more elaborate examples:

Example one

Example two

You will have to alter your jQuery POST request to something like:

```
 $.ajax({
         type : "POST",
         url: '/sample-page/',
         data: {'uid':2},
         success : function(response){
              console.log(response);
         },
    });

```

The data you post in your jQuery request will be available in $data of your resource class.
> 1 votes

# Answer
You've got three issues in your routing file. The first is that items relating to permissions, in this case `_permission` and `_access`, should be under `requirements`, not under `defaults`. Also, it's supposed to be `defaults` not `_defaults`.

So this:

```
my.route:
  path: '/sample-page/{variable}'
  _defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
    _permission: 'access content'
    _access: 'TRUE'

```

Should be this (allow access to users with 'access content' permission):

```
my.route:
  path: '/sample-page/{variable}'
  defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
  requirements:
    _permission: 'access content'

```

Or this (give access to anyone):

```
my.route:
  path: '/sample-page/{variable}'
  defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
  requirements:
    _access: 'TRUE'

```
> 0 votes

# Answer
The controller must return right answer. I recommend to use json response. Add `use Symfony\Component\HttpFoundation\JsonResponse;` to your controller.

```
 public function ajaxCallback($variable)
      {
        return new JsonResponse(['variable' => ucwords($variable)]);
      }

```

And in your JS file `console.log(response.variable);`.

**And indicate method in your route!!**

Also i recommend to pass variables not in url.

In route file:

```
my.route:
  path: '/sample-page/'
  defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
  requirements:
    _access: 'TRUE'
    _method: 'POST'

```

in js:

```
 (function($) {
     $('#custom-button').click(function(){
        var name = 'john doe';
      var sentdata = new Object();
      sentdata.name=name;
        $.ajax({
             type : "POST",
              data:sentdata,
             url: '/sample-page/',
             success : function(response){
                  console.log(response.name);
             },
        });
     });
})(jQuery);

```

in controller:

```
//...
use Symfony\Component\HttpFoundation\JsonResponse;
//...
public function ajaxCallback()
      {
      $name = \Drupal::request()->get('name');
        return new JsonResponse(['name' => ucwords($name)]);
      }

```

PS. Instead of drupal service wrapper (\Drupal::request()) a right way is to use dependency injection
> -1 votes

---
Tags: 8, ajax
---


# Question
Title: hook_feeds_processor_targets_alter - how to set a value not in the feeds source?
I need to import a csv that has only two fields (**date** and **name**) to a content type that has 3 fields:

* date
* name
* file

The **file** field should be set as the name of the file being imported.

My code until now is this:

```
function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['my_feed'] = array(
    'name' => t('field_filename'),
    'description' => t('This field has the csv file name.'),
    'callback' => 'mymodule_import_filename',
  );
}

function MYMODULE_import_filename($source, $entity, $target, $value, $mapping) {
    $my_filename ='file.csv';
    $entity->{'field_'.$target}[$entity->language][]['target_id'] = $my_filename;
}

```

Where am I doing a mistake? Is this the way to import a value outside the file being imported?

Thanks.

# Answer
I managed to get the answer to this question.

In MYMODULE\_import\_filename() we can get the data we want to import, in my case is just a simple text: 'file.csv'.

The simple way to do it is like this:

```
function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['my_feed'] = array(
    'name' => t('field_filename'),
    'description' => t('This field has the csv file name.'),
    'callback' => 'mymodule_import_filename',
    'real_target' => 'field_filename',
  );
}

function MYMODULE_import_filename($source, $entity, $target, $value, $mapping) {
    $my_filename ='file.csv';
    $wrapper = entity_metadata_wrapper('node', $entity);
    $wrapper->field_filename->set($my_filename);
}

```
> 2 votes

---
Tags: feeds
---


title: Cache Exclude functionality in Drupal 8

text:
# Question
Title: Cache Exclude functionality in Drupal 8
How can I prevent a specific node - or a list of specific nodes - being cached server-side in Drupal 8?

I have page that pulls a value out of a $\_SESSION variable using a PHP text block, and it is being cached, which is obviously not what I want.

# Answer
> 0 votes
I fixed this by doing the following:

* I appended a cache buster querystring parameter to the link to the page that needed to be kept out of cache (using the timestamp token + random number token)
* Added the `'url.query_args'` cache context to the `required_cache_contexts` in services.yml

It puts a bit more strain on the memory use of the cache than just keeping it out of cache altogether, but the `\Drupal::service('page_cache_kill_switch')->trigger();` line did not do anything for me at all.

I think it makes sense for the querystring to be part of the default cache context anyway.

---
Tags: 8, caching
---


# Question
Title: Why is hook_update not fully taken into account?
I have a custom content entity created with
`public static function baseFieldDefinitions(EntityTypeInterface $entity_type)`.
I just added a field to that entity with
\- adding a new `$fields['courriel'] = BaseFieldDefinition::create('email')`
\- creating hook.install file with

```
function association_update_8101()
{
  \Drupal::entityDefinitionUpdateManager()->applyUpdates();
}

```

Running update.php has indeed added the field to the corresponding database table and I can access it with my code (for example, I store in that field a copy of user-\>mail.
But when I use CRUD forms for my Entity (i.e. canonical, add-form, edit-form or collection), I don't see the new field.
What did I miss?

\[Edit\] my hook.install is now:

```
function association_update_8101()
{
  $storage_definition = BaseFieldDefinition::create('email')
    ->setLabel(t('Courriel'))
    ->setDescription(t('The email address of the Personne entity.'))
    ->setDefaultValue('')
    ->setReadOnly(TRUE);
  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('courriel', 'association_personne', 'association_personne', $storage_definition);
}

```

I managed to run again update.php with success (at least with no errors): the table has now the new column (Courriel) but I still don't have my CRUD forms showing 'Courriel'.
Is there anything else I need to add to hook\_update\_8101 to have that done?

# Answer
It seems I was looking at the wrong place.
Once hook\_update\_8101 executed, I should have updated myEntityListBuilder.php to be consistent.
The other forms (canonical, add-form, edit-form) were effectively updated.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Is it good idea to install modules, which require server config, locally? How?
There are few modules which require server side config to work. If you have a hosting and domain, it is not a big problem, but if you are developing locally, then I guess it is a problem.

If you somehow install and use these type of modules on local environment to test, you have to change the config once you move to production. For example Node.js integration, Twitter and other modules which require a setup before you can use them.

I am using acquia dev. I want to test some modules before going live as I mentioned above, but my question is how I can do that?

Note: Using such local environment is for me a way to reduce the cost of testing, since I wouldn't have to purchase hosting for that during a few months. In some cases, nobody would want to purchase a hosting and waste few months or a year for just testing.

# Answer
> 1 votes
The problem is having different configuration in in different environments (production, staging, local dev, etc).

Usually you have production. This is the main site. You have to move it to staging or development environment. Moving implies usually to get the production database with all new added content. But in dev environments you need some changes:

* Enable development modules like devel, https://www.drupal.org/project/reroute\_email, etc.
* Change settings. For example, if your site uses a webservice you may change the endpoint URL to a dev webservice URL. Those settings sometimes are jsut Druipal variables but they may be custom settings stored in a module's custom tables.
* Clean sensible data: user emails, user personal data like medical data, confidential content that should not be leaked, etc.

You can:

# Override variable in settings.php

As @Jaypan said in comments override $conf\['VARNAME'\] in settings.php. This allows to easy variable override per environment.

To have more flexibility you can use Drupa 8 strategy: have acommon settings.php in source code control with all common config for all environments and at the end of the settings.php file load a settings.local.php wuth the per environment settings. Typically here you can a have BD config, config to access other service like your node.js, etc.

To do this add this code in your settigns.php.

```
# Load environment managed conf.
$conf_path = conf_path();
if (file_exists(DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php')) {
  include DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php';
}

```

# Modify environment

Previous solution works but sometimes you need to change more than internal Drupal variables. In that case you should set up a mechanism to execute setup code in your environment. For example you may want to make sure that in your staging or local environment Stage File Proxy is enabled. You can't enable a module directly in settings.php. Also, you may need to execute a query to sanitize data.

In this case there are several options to change things according to environment:

## Using hook\_init implementation

hook\_init is a Drupal hook that is called on every non-cached request. Here you can place code that checks some condition in your environment and changes it if needed. This solution is simple to implement, but because the hook implementation is called on every non-cached request the checks performed should be very also simple or you may hit a performance penalty.

Also, you can use hook\_boot, that's executed on every request, cached or not. You have to be very carefully with this hook because of performance and because is called during Drupal bootstrap and before the theme, modules, or most include files are loaded into memory.

## Creating a custom drush command

Drush allows to create custom commands. At the end, they are just PHP code executed in the Drupal context, so all Drupal functions are available. You can create a custom drush commands that performs the environment check. From here you can enable modules, perform sql queries or any other action Drupal allows.

This command should be executed when the database is loaded into the dev environment, just once. Because of this, there's no problem if the command is resource intensive as it's only executed once.

## Extending drush sql-sanitize

This drush command sanitizes the database, setting same password for all users and modifying their address. You can extend it to make more tasks like executing SQL queries.

## Script with drush commands

Write a custom sfript with drush commands that modifies the environment. This soltuions is simple but alloww you to make any modification done by a drush command.

For example:

```
drush en devel -y
drush vset myconf my_dev_value
drush sql-query "MY AWESOME QUERY"

```

---
Tags: 7, testing, acquia-dev-desktop
---


title: How to make my validateForm working?

text:
# Question
Title: How to make my validateForm working?
In a custom module of mine, I have two custom entities A and B with a one to many relationship from A to B.
This is Edit form for EntityB:

I want to have this check in validateForm: if 'Contact' (boolean) is checked, 'Adhérent' (entity\_reference to EntityA) shouldn't be empty.

Here is my validateForm:

```
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values=$form_state->getValues();
ksm($values);
    if ($values['estlecontact']['value']==1 && $values['adherentid']['target_id']==NULL) {
      $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
    }
  }

```

In this case, I should not have the error message and still...
What am I doing wrong?
Here is the result of ksm:

# Answer
I figured it out!
this works:

```
$values=$form_state->getValues();
if ($values['estlecontact']['value']==1 && $values['adherentid'][0]['target_id']==NULL) {
  $form_state->setErrorByName('estlecontact', t('L\'Adhérent est obligatoire quand la Personne est désignée comme Contact.'));
}

```

Note that `$values['adherentid']` is a mutliple value field. I was missing an array level. Adding `[0]` before accesing `target_id` solves the problem.
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to create a custom design of an existing view block?
I have a block I created via views ui. It is in a table format. It has 3 columns with 3 fields. Every field shows in a separate column.

Now I want to change the design of this block in an easy way to my likings.

For example here is the screenshot of one of the blocks to explain what I mean.

This shot is showing user-pic, username and follow-flag resp. As indicated in the snapshot, I want to show follow-flag below the username.

How to easily change the design of my view or block? The best would be a drag & drop. I guess this is an easiest way.

# Answer
By pressing "settings" next to the table format, you can alter which column the fields are shown in.

Then using the "Separator" on the parent column (in your case the username field) you can inject what separats them.

Alternative you can adjust the styling of the "Follow" field to be a block element (div).
> 1 votes

# Answer
By modifying the view templates the views can be altered. You can add custom html design and styles to modify design.

From **Page: Theming information** select the template. For eg: views-view--sample--page.tpl.php, template for the view named Sample.
> 1 votes

---
Tags: 7, views, blocks
---


# Question
Title: Why we need hook_cron if the cron job requires a path?
In drupal we have a `hook_cron()` which runs on cron.

But in cron job we have to specify a path, the cron will access that path and will run the code in the `page callback` function of that path.

So my question is that why then we need `hook_cron()` if we can do this by creating path using `hook_menu` with a `page callback` and use that path in the cronjob?

Can someone explain this to me?

# Answer
> 2 votes
Using `hook_cron()` Drupal can run all the cron tasks using a single entry point (http://your.site/cron.php) and bootstrap code that is very specific for cron tasks, different from the normal bootstrap code used from Drupal.
This simplifies handling cron tasks since only a single URL is necessary to run them, and the code that runs them is faster compared to the normal code.

If I had the need to run groups of cron tasks at different times, then I could create different *cron.php* files to execute those specific groups. I would not implement different routes for executing cron tasks for the same reason Drupal 7 doesn't: The code that runs the routes is more complex than the code running the cron tasks and involves more hooks being invoked.
At least that was the reason for doing so when Drupal 7 was first released. With PHP 7, that is probably not a reason enough to prefer custom bootstrapping code to a route handler. As for Drupal 8, cron tasks are executed from a controller associated with a route.

In short, normally cron.php is enough, but it is also rare to even need a different route handler/controller for each cron task modules could.

---
Tags: 7, cron
---


# Question
Title: Why is the CSS for my theme not loading while the JS is?
Theme `mytheme` is placed under `/sites/all/themes/`

Content of `mytheme.info.yml` :

```
name: My Theme
type: theme
description: Custom theme.
core: 8.x
base theme: classy
version: 8.x-1.0
libraries:
  - mytheme/global-styling
regions:
  logo: 'Logo'
  navigation: 'Navigation'
  page_header: 'Page Header'
  content: Content  # the content region is required
  page_sidebar: 'Page Sidebar'
  contact_first: 'Contact (First column)'
  contact_second: 'Contact (Second column)'
  contact_third: 'Contact (Third column)'
  footer_logo: 'Footer logo'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'
  footer_copyright: 'Footer Copyright'
regions_hidden:
  - sidebar_first

```

Content of `mytheme.libraries.yml` :

```
global-styling:
  version: 1.x
  css:
    theme:
      assets/plugins/bootstrap/css/bootstrap.min.css: { minified: true }
      assets/plugins/font-awesome/css/font-awesome.min.css: { minified: true }
      assets/css/style.css: {}
      assets/fonts/montserrat/montserrat.css: {}
  js:
    assets/plugins/jquery-1.11.1.min.js: { minified: true }
    assets/plugins/bootstrap/js/bootstrap.min.js: { minified: true }
    assets/plugins/moderniz.js: {}
    assets/js/app.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

The JS is loading but the CSS isn't. How come?

# Answer
try wrapping the google fonts entry in quotes like this:

```
'//fonts.googleapis.com/css?
family=Open+Sans:400,300,600⊂=latin,cyrillic': { type: external }

```

Maybe there is a problem with the url using yaml special characters https://stackoverflow.com/questions/19109912/do-i-need-quotes-for-strings-in-yaml#22235064
> 0 votes

---
Tags: theming, 8, .info
---


title: Pseudo "subdirectory subsite"

text:
# Question
Title: Pseudo "subdirectory subsite"
While a real subdirectory subsite has a URL of `example.com/site1`, and shares codebase with `example.com`, I was wondering if it's possible to create a separate Drupal installation (in a separate docroot) for site1 and still use the URL `example.com/site1`. In my case, they are two completely different Drupal installations with nothing to share, well, except the somehow 'related' URL part.

I know I can just use a sub domain and make the whole thing a lot easier but am wondering if the pseudo 'subdirectory subsite' is an option.

# Answer
I think you could use an alias in your apache virtual host, something like this

```
Alias /site1 /path/to/your/site1
<Directory /path/to/your/site1>
  Options +Indexes
  AllowOverride All
</Directory>

```

Like it is suggested here https://stackoverflow.com/questions/19055372/redirect-to-a-subfolder-in-apache-virtual-host-file#19055573
> 1 votes

---
Tags: 7
---


title: media->save gives erros

text:
# Question
Title: media->save gives erros
I am able to create a media object with the below code

```
 $static_media = Media::create([
'bundle' => 'document',
'uid' => $current_userid ,
'langcode' => "en",
'status' => 1,
 'name' => [
    'target_id' =>$title,

  ],
$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

```

but when I try to do `$result=$static_media->save();` I get the error

```
Error: `Call to a member function isEmpty() on null in Drupal\media_entity_document\Plugin\MediaEntity\Type\Document->getField() (line 43 of profiles\lightning\modules\contrib\media_entity_document\src\Plugin\MediaEntity\Type\Document.php).

```

How can I debug this to find out what is missing? I tried putting an echo at that point of the code in the plugin but cannot see anything . What would you suggest to try to see what field it is looking for at that point?

Thank you .

# Answer
instead of this part of the array

```
$file_name => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

```

i had to put the field name , not the file name.

```
'field_document' => [ 'target_id' => $fid, 'alt' => $title, 'title' => $title, ], ]);

```
> 2 votes

---
Tags: 8, media
---


title: Conditional on Header on a View Page?

text:
# Question
Title: Conditional on Header on a View Page?
How can I put a condition on the Header in a View to not display the Header if the View has content?

There's an option to display a Header/Footer absent any content, but I'm looking for the opposite effect.

# Answer
To do this without using preprocess functions in `template.php` as @ Andrew said, Click on the `add` in header section and select `Global: PHP` and use this code

```
<?php
      if(count($results) > 0)
           return;
       else
           print "THIS IS YOUR HEADER";
?>

```

I mean you must do the following

Then in the `Global: PHP`

**You can do the same for footer and ...**
> 1 votes

# Answer
You can user template\_preprocess\_views\_view function to do it

```
function mymodule_preprocess_views_view(&$variables) {
  if ($variables['view']->name == 'my_view') {
    if ($variables['view']->current_display == 'my_display' && !empty($variables['rows'])) {
      $variables['header'] = '';
      $variables['footer'] = '';
    }
  }
}

```
> 1 votes

# Answer
I like Drupal(8), but it encourages some bad practices. Giving more than one way of doing something is good, but some of those should not be there. Namely, Header and Footer in the Views. It may seem like an easy solution. But there's a catch! Where is this information stored? In the database. Can you easily import/export/reuse these "settings"? Nope. So hope that'll save some one hours of confusion and wasted time, as personally my first Drupal-based site used a lot of those as I thought, well since they're there it must be good idea to use them.

Also avoid using preprocess functions, unless you absolutely must. Also source of wasted time later on.

So where can you put the header/footer? In your overwritten View twig file. For example: **views-view.html.twig** will cover all your views but you can put it in a specific one if you're overwriting it differently depending on a view.

Variable you can use there to give total results: {{ view.total\_rows }}
> -1 votes

---
Tags: views
---


# Question
Title: Taxonomy term title as page title in custom view
I have a custom view where I show a list of nodes by taxonomy term. Since there are many terms in dictionary, I can't describe every view page manually. Is there any way to set the page title as a taxonomy term title?

# Answer
> 5 votes
You can use the argument added into the filter and there will be option to override the title, there you can pass %1 which will automatically replace the title with the Taxonomy term title.

# Answer
> 2 votes
For **Drupal 8** this would be `{{ arguments.name }}`.

---
Tags: views
---


# Question
Title: How to resend same newsletter from Simplenews?
I'm using simplenews module in Drupal 7. Also I have working mailing system as well as Cron system. I want to resend the newsletter that has been sent previously. I don't want to edit the database every time for resending. I want to send newsletter using user interface itself.

I tried editing **simplenews.module** and **simplenews.admin.inc** files.

I edited **simplenews.module**

```
/**
* NEWSLETTER SENT STATUS
*/
define('SIMPLENEWS_STATUS_SEND_NOT', 0);
define('SIMPLENEWS_STATUS_SEND_PENDING', 1);
define('SIMPLENEWS_STATUS_SEND_READY', 0);
define('SIMPLENEWS_STATUS_SEND_PUBLISH', 3);

```

But as I edited for SIMPLENEWS\_STATUS\_SEND\_READY, it started giving me notice in the admin panel stating:

> Notice: Undefined offset: 2 theme\_simplenews\_status() (/home/#####/public\_html/#######/sites/all/modules/simplenews/includes/simplenews.admin.inc file row number 1776 ).

But I couldn't edit **simplenews.admin.inc** file. And in the newsletter sending option it shows following message but don't send message when I run Cron:

> This newsletter is pending

Please help if someone has faced the same issue.

# Answer
Perhaps easier to clone and then resend the newsletter node with the node\_clone module.

```
The clone module allows users to make a copy of an existing item of site content (a node) and then edit that copy.

```
> 1 votes

# Answer
This is a old issue but it may help anybody looking for quick solution. I was looking for the same functionality and end up with Simplenews Status Reset module..(posted on August 1, 2015) it's allows to reset the sent status of an already send node/news so that you can send it again.
> 0 votes

---
Tags: commerce, emails
---


title: Prohibit CSS files in specific pages

text:
# Question
Title: Prohibit CSS files in specific pages
I am using a custom theme in Drupal and the jquery and bootstrap version in pretty outdated. Old pages in are in that version but I want to design few new pages where I want to include the latest version of bootstrap and jQuery. Now whenever I design a new page, Drupal itself adds certain wrappers to it and includes the previous bootstrap, jQuery version in the aggregate JavaScript file. I just want it to be plain HTML and not include any other CSS/JavaScript files, or make any other modification.

I have added CSS and JavaScript files in link and script tags. Few elements also have inline CSS styles. I just want it to render as simple HTML page.

Currently this is my theme.inc file.

```
 foreach ($stylesheets as $stylesheet) {
   drupal_add_css($stylesheet, array('group' => CSS_THEME, 'every_page' => TRUE, 'media' => $media));
  }

```

# Answer
I think you're looking for hook\_js\_alter and hook\_css\_alter. Using these hooks you can remove any CSS and/or JS file.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to see changes inside Paragraphs or Field Collections with Diff
I have read and checked that Paragraphs and Field Collections revisions are tracked. But when I make a change to the node and then look at the Revisions tab, no changes done with fields inside Paragraphs or FC are displayed. Does Diff support display of those changes? If yes, how can I see them?

Things I checked:

1. Enable the Revisions page for this content type is checked.
2. Standard comparison preview is Full Content and it has paragraphs field displayed.
3. Diff module is installed and enabled.
4. On page admin/config/content/diff/fields in Global settings for Paragraphs Markdown callback is set to "Drupal HTML to text", as well as for those field types that are inside paragraph.

I can see field changes for my content type, but the comparison page does not show changes for fields that are inside paragraph. What is missing?

# Answer
> 1 votes
You have to install and enable the Diff module.

> This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

Nothing else is needed.

Given a simple paragraph with a boolean field and a text field, if oyu change the textfield uou will get someting like this:

---
Tags: 7, entities, paragraphs
---


# Question
Title: Does changing the order of questions reflected in past quiz results too?
I have two quick questions about implementing the quiz module:\]

1. I have the questions in a particular order and about 100 people have taken the quiz. We have implemented the quiz results download module. If I CHANGE THE ORDER of the questions (make question #3 the new question #1) will the results (old one in particular) automatically UPDATE or will we have ‘MIXED’ data – some with the old question numbers and some with the new ones?
2. As you know, there is an option to present responses (answer choices) in random order. We had NOT checked that box. If we now check that box, will the old data get automatically updated?

# Answer
> 1 votes
Here is a copy/past from the answer to issue # 2862591

> It depends on your revisioning configuration.
>
> Out of the box, Quiz will version changes so that your old results are not affected.
>
> If you were to change the Quiz/Questions in any way, you may see issues with reporting since the quiz and question version IDs have changed, so new users will be taking a different version of the Quiz. But, this means that all data is preserved.
>
> If you turned revisioning off, reordering the questions or selecting "random order" should not affect old results or reporting as the question IDs remain the same. But you have to be more careful since changing something like removing an answer or question will definitely affect old results.
>
> I'd suggest trying on a test copy of your DB just to make sure.

I'm posting this as a wiki answer, hoping for it to marked as accepted, so that this question is no longer considered as unanswered also.

---
Tags: 7, quiz
---


# Question
Title: How do I repack an existing site into Open Source repo with bundled content and configuration?
I have been tasked to repack an existing live Drupal 7 site, that will go out of commission, to make it available as Open Source on Github so anyone interested may find some use of it.

This will require that the repository comes with a database dump containing an example configuration and content.

What I need to do is to first anonymize the database from usernames/passwords, and also remove any not needed old revisions of existing content to compact the dump.

* Is there any best practice strategies for how this can be done as simple as possible, and in the documentation provide a simple step-by-step guide on how to install it using the database dump?

**Please note**: While a Drupal Distribution would be optimal, in this case the wast amount of extra work, and testing, required is not possible.

# Answer
> 1 votes
You can anonymize some content using drush and the `sql-sanitize` command found in Drush by default: https://drushcommands.com/drush-8x/sql/sql-sanitize/

If that doesn't clean up enough of your content to be suitable for Open Source release, you can use the underlying hook drush exposes for this task and implement it for your site as seen in this blog post, https://www.codeenigma.com/support/blog/doing-more-drush-sql-sanitize, found on google. An excerpt of the additional sanitation examples you could do from the blog post are:

```
/**
* Implements hook_drush_sql_sync_sanitize.
*/
function my_module_drush_sql_sync_sanitize($source) {
  // The query to sanitise field_data_field_profile_linkedin_page
  $linkedin_page_query = "UPDATE field_data_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  // The query to sanitise field_revision_field_profile_linkedin_page
  $linkedin_page_query .= "UPDATE field_revision_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  drush_sql_register_post_sync_op('sanitise_linkedin_page', dt('Sanitise field_profile_linkedin_page'), $linkedin_page_query);

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query = "UPDATE field_data_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query .= "UPDATE field_revision_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  drush_sql_register_post_sync_op('sanitise_telephone_number', dt('Sanitise field_profile_telephone_number'), $telephone_number_query);

  // The query to sanitise field_data_field_profile_twitter_handle
  $twitter_query = "UPDATE field_data_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  // The query to sanitise field_revision_field_profile_twitter_handle
  $twitter_query .= "UPDATE field_revision_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  drush_sql_register_post_sync_op('sanitise_twitter_handle', dt('Sanitise field_profile_twitter_handle'), $twitter_query);
}

```

If you dont want to attempt to delete revisions manually yourself, in packing the site for git (make a backup first), I would look at the following module: https://www.drupal.org/project/field\_sql\_norevisions

Once the above steps are done. I would simply provide a drush archive-dump (or the contents thereof) in a GIT repo and instruct users to use Drush and the provided zip (or place the contents of the git repo into a zip) to use drush archive-restore to install the site. The only gotcha with this approach is to assure they use the same database engine on their system as the live site expects (that I can think of).

---
Tags: nodes, database
---


# Question
Title: Drupal 7 Breaks CSS Rule Ordering Standards when CSS Aggregation is Turned On
Drupal 7 has an interesting bug (some may consider this a feature) when rules are included before an external CSS document is included using `@import`. The CSS Aggregation engine will let you "bend the rules" by declaring CSS before calling external stylesheets with `@import`. While there are very different solutions provided here, they both solve the issue.

**Example CSS:**

This example works with CSS Aggregation turned *ON* but will not work if CSS Aggregation is *OFF*.

```
* { margin: 0; padding: 0; box-sizing: border-box; }
@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';

```

My assumption is that Drupal 7 CSS Aggregation engine actually fetches the contents of the `@import` calls and appends the contents to the main file as a subroutine.

---

**Solution:**

The solution was to follow the CSS standards by moving all of the `@import` calls to the top of the document, before declaring rules internally.

```
@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';
* { margin: 0; padding: 0; box-sizing: border-box; }

```

While this question was originally marked as "off-topic", I think *it's still important to illustrate how CSS is interpreted by the Drupal 7 CSS Aggregation Engine*. It should be understood that these two different methods are VERY DIFFERENT in the way they are interpreted since CSS is sensitive to rule ordering.

---

**More Accurate Solution:**

The more accurate solution to this problem would be to include the first line in another CSS document, for instance `reset.css`.

```
@import 'reset.css';
@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';

```

---

I hope this helps other people understand the nuances of the Drupal 7 CSS Aggregation engine.

# Answer
> 1 votes
Solved my own question. There were rules that came before the @import. So this wasn't a Drupal 7 issue, it was a CSS interpretation error.

---
Tags: theming, performance, css-js-aggregation
---


# Question
Title: Why isn't my composer installation working?
I followed the instructions on docs.drush.org for installing Drush, proceeded by the recommended steps for installing Composer and a new Drupal 8 project. My project (cfbtv) is located at ~/sites/cfbtv and it appears the composer template (whatever that is) installed Drupal in the web directory.

When I try the recommended Composer commands they fail. `composer update devel` outputs the following.

> Package "devel" listed for update is not installed. Ignoring.
> Loading composer repositories with package information Updating dependencies (including require-dev) Nothing to install or update
> Generating autoload files

When I run `composer require devel`, I get this message.

> \[InvalidArgumentException\]
> Could not find package devel at any version for your minimum-stability (stable).
> Check the package spelling or your minimum-stability.
>
> ```
> require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...
>
> ```

So what is the problem here?
Composer seems to have installed properly, but I'm surprised these commands aren't working. Maybe it works and I'm not using it correctly.

# Answer
As shown in the example reported in the documentation page you linked, you need to add `drupal/` to the machine name of the module you want to install. The given example is exactly for the Devel module.

```
composer require drupal/devel:~1.0

```

The name of the packages handled from Packagist has the format vendor/package, so if you simply use the machine name of the module, Composer will not be able to find the package you meant.

Remember to run the commands from the directory containing the composer.json and the composer.lock files, not from the *core* directory.
> 3 votes

---
Tags: 8, composer
---


# Question
Title: TinyMCE Custom plugin -- button doesn't appear
I am trying to create a custom plugin for TinyMCE 3.5.9. I have a module that is adding it to the WYSIWYG profile, which can be checked. That works. But when I load a page, the custom button does not appear on the WYSIWYG.

The plugin is there in the background though, and I can even fire it in the console using this command: tinyMCE.activeEditor.execCommand('mcePullQuotes');

So the code is being loaded and initialized. Just the button is not appearing. Been banging my head.

This code is pretty much cribbed from the example code in the Jscript/plugins example, and I don't see much different going on in other plugins. There are no console errors.

```
(function() {
  tinymce.PluginManager.requireLangPack('pullquotes');
  tinymce.create('tinymce.plugins.PullQuotesPlugin', {
    init : function(ed, url) {

      tinyMCE.activeEditor.execCommand('mcePullQuote');
      ed.addCommand('mcePullQuotes', function() {
        ed.windowManager.open({
          file : url + '/dialog.htm',
          width : 480 + parseInt(ed.getLang('style.delta_width', 0)),
          height : 340 + parseInt(ed.getLang('style.delta_height', 0)),
          inline : 1
        }, {
          plugin_url : url, // Plugin absolute URL
          some_custom_arg : 'custom arg' // Custom argument
        });
      });

      ed.addButton('pullquotes', {
        title : 'PullQuotes',
        text: 'PQ',
        cmd : 'mcePullQuotes',
        icon: false,
        image : url + '/img/example.gif'
      });

    },

    getInfo : function() {
      return {
        longname : 'Pull Quotes plugin',
        author : 'Adrian Cotter',
        authorurl : 'adrian.cotter@sierraclub.org',
        infourl : 'http://www.sierraclub.org',
        version : "1.0"
      };
    }
  });

  tinymce.PluginManager.add('pullquotes', tinymce.plugins.PullQuotesPlugin);
})();

```

UPDATE:

So one problem was this... I had this in my module code, which is where the button was showing up in config from, and how the code was being loaded.

```
'extensions' => array(
  'internal_name_of_myplugin' => t('Example'),
),

```

BUT... I removed that and replaced it with this

```
'buttons' => array('pullquotes' => t('Pull Quotes')),

```

This appears in the profile config -- but nothing is loading now. No button, and no JS this time. Path does not seem to be an issue.

# Answer
I was able to get the button working. Through 2 things in my module.

1. `'buttons' => array('pullquotes' => t('Pull Quotes')),`
2. `'path' => 'sites/all/libraries/tinymce_plugins/pullquotes',`

It seems that the various methods I was using to get the path, were giving the whole URL /sites/all/libraries/tinymce\_plugins/pullquotes So when I put it in as an absolute, and then removed the proceeding / everything worked.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Use single values added by field-collection module in Views?
I've already found this question, but it doesn't really help me out, maybe I just don't understand it (I've got the latest version of the module). How to integrate Field collection module in Views?

I have my own content type called "Gallery", for this, I created a field-collection which consists of an image and caption. Now I try to create my own view, first one, only to show the thumbs, and then one, showing the big image and the caption.

But how can I access only one field of the field-collection? I can find this field:
Content: Gallery and caption
or this one: Content: Gallery and caption:delta (Gallery and caption (field\_gallery\_and\_caption:delta))

but how do I access only the image field? and which type of display should I select?

# Answer
> 1 votes
I've recently done this before. It's really easy, you can create a Node type view. Then you just add the field collection field that's attached to your node as a Relationship, in your case "Content: Gallery and caption".

Then after you've added the relationship, when you click "Add" on the fields, your field collection fields will be available to select. Their names will start with "Field collection item: \*".

If you're using Node reference field inside your field collection then you need to add one more relationship. See this issue and #2 comment for solution.

# Answer
> 0 votes
Did you add the field\_collection relationship to the view?

You will need the relationship to access collections as individual fields.

# Answer
> 0 votes
To add to the answer, when you add the FieldCollection as a relationship, you choose the FieldCollection's **name** from the list of relationships. I had thought I was looking for something saying "field\_collection" and couldn't find any reference to "collection".

Once I realized that I just had to pick my FieldCollection by name it all worked as described. I lost many hours chasing that tiny distinction. Hope this helps someone else like me.

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


title: Custom messages for user_pass_reset

text:
# Question
Title: Custom messages for user_pass_reset
I would like to customize the messages for one time login links (i.e. password reset links). In some cases, I redirect the user to the login page. In these cases, it does not make sense to have "Please request a new one using the form below."

Is there a hook or module I can use to add some logic to that message? (I can do a global override with String Overrides, but am looking for more conditional messages.)

I am using Drupal 7.

# Answer
If you mean the email message for a password reset. You can use `hook_mail_alter` to change the email contents before it's sent out to the user.

If you mean the form the user sees on the webpage, then you can use `hook_form_alter` to change the verbiage shown on the screen.

## Edit

override the displayed form with the reset button to goto your own form\_submit action. In your custom module action, simply copy and paste user\_pass\_reset function body into your own function and tweak it as needed to change the messages (careful).
> 1 votes

# Answer
Those messages are pretty harcoded in user module in the file `user.pages.inc`, `user_pass_reset` function.

There's no hook to alter drupal set messages, but if you want to suppress certain messages you have luck with the module Disable Messages:

> Gives a site owner options to disable specific messages shown to end users.

Features:

* Filter out messages that match a full text string exactly.
* Filter out messages that match a regular expression.
* Permissions to specifically hide all messages of a given type from any role.
* Disable all filtering for specific users.
* Disable all filtering for specific paths.
* Apply filtering only for specific paths.
* Debug system to get messages in the HTML without showing it to the end users.

# About using rules

There is an issue about this: Is it possible to unset or override system messages with Rules?
> 0 votes

---
Tags: 7, hooks, status-messages
---


# Question
Title: How can I retrieve the query parameters passed from the URL?
In Drupal 8, `$_GET` does not return the query parameter I am expecting to get. With the following code, I get `1` all the times, even when I expect to get `2`.

```
namespace Drupal\newday\Controller;

use Drupal\Core\Controller\ControllerBase;

class NewdayController extends ControllerBase {

  public function new() {
    $day = [
      "#markup" => \Drupal::request()->query->get('id'),
    ];

    return $day;
  }

}

```

How do I get the correct query parameter?

# Answer
> 10 votes
The request is being cached, you need to tell the system to vary by the query arg:

```
$day = [
    '#markup' => \Drupal::request()->query->get('id'),
    '#cache' => [
        'contexts' => ['url.query_args:id'],
    ],
];

```

You need to rebuild cache after altering the render array to see the effects.

If you're not familiar with it already, Cacheability of render arrays is worth a read.

---
Tags: 8
---


# Question
Title: What is the best way to collect and report statistics from within views 3's exposed filter?
I have a content type "song" and created a view on it. Using Views 3 exposed filter, people can search with different criteria.

With Google Analytics, I can collect some rough statistics. But I do not want anonymous statistics. I would like to collect and report the criteria by the login user/roles.

I can put a PHP code into my view so that every time someone interacts with this view, the PHP code will collect the criteria from the URL and save to a table.

Is there a better way?

**EDIT**

I've got an interim solution:

1. Write a custom module that uses `hook_form_alter` to update the exposed filter form. See link.
2. Install Views Watchdog
3. Create a view that reports on these watchdog entries. I can use PHP to parse the `watchdog's location` field to get my reports better.

If you have a better alternatives, please let me know.

# Answer
> 0 votes
You can use GA Push module:

> GA Push offers an API to enqueue informations that are sent GA servers, and three submodules to track browser events (using jQuery), form validation errors and log exceptions.

Instead of saving the data in your custom table you can just send it to Google Analytics.

Collect your data in your PHP code and send it like this:

```
      $push = array(
        'eventCategory' => $category,
        'eventAction'   => $action.
        'eventLabel'    => $label,
        'eventValue'    => $value,
      );
      ga_push_add_event($push);

```

You may hook on the form submit instead of adding PHP code to the view.

---
Tags: 7, views, nodes
---


# Question
Title: Drush update: How to keep file permissions?
Following scenario happens to be in place. There is a server administrator (root) who doesn't know a thing about Drupal. Then, there two (or more) web developers (userA, userB), who do not have root access but are all in the group "web".

The server has several Drupal instances which have to be updated on a regular basis. Each Drupal instance is set with permissions 2775 (dirs) or 2664 (files) and belongs to either userA or userB, group in all cases is web.

When using drush to update an instance, all files that are overwritten (due to updates) now belong to the user running drush and get the permissions 644 (instead of 664). Thus, when userA updates e.g. a module, this module can't be changed or updated by userB afterwards. userA always has to chmod the files after an update.

How can this be rendered unnecessary, or how can the file permissions be kept when using Drush?

# Answer
> 2 votes
Write a script that correct permissions, you can find an example in this article:

Securing file permissions and ownership

Execute this script manually every time a drush update is made.

Or you can write a simple drush command that executes this script when a drush commands that cnahges files executes. Check the drush\_hook\_post\_COMMAND: http://drupalcontrib.org/api/drupal/contributions%21drush%21docs%21drush.api.php/function/drush\_hook\_post\_COMMAND/7

# Answer
> 1 votes
https://www.drupal.org/project/file\_permissions

1. Download module to your ~/.drush folder:

`drush dl file_permissions-8.x --destination=~/.drush`

2. Run `drush cc drush` to clear Drush cache.
3. Run `drush fp` to fix file permission on current site.

---
Tags: 7, drush, files
---


title: Retrieving menu item using REST

text:
# Question
Title: Retrieving menu item using REST
I am looking for a way of getting menu items for a menu i.e(Main menu) via rest, enabling the Menu resource and trying `/entity/menu/{menu}` gives me only dataset of the menu i.e

```
{
  "uuid": "57e695a4-2af8-43ac-9300-b989ecbb2d87",
  "langcode": "en",
  "status": true,
  "dependencies": [],
  "id": "main",
  "label": "Main navigation",
  "description": "Site section links",
  "locked": true
}

```

but I need the menu links associated to that menu too. which is the most suitable approach ?

# Answer
There is still no native way within Drupal core to expose config entities via REST. There are 2 contrib modules which claim to allow retrieving menu items via REST, neither of which I have used.

**REST Menu Items**

Allows you to specify maximum and minimum depth in the request.

**REST Menu Tree**

Returns the menu tree. Not yet covered by Drupal's security advisory policy.

**Update 28 March 2017**

REST Menu Items works as advertised but check the issue queue for any outstanding bugs. For example, currently the alias for a menu item isn't returned.
> 1 votes

---
Tags: routes, 8
---


title: Add a breadcrumb to a view page?

text:
# Question
Title: Add a breadcrumb to a view page?
How can you just add a breadcrumb to views? Easy breadcrumb leaves out views. Views breadcrumb does not work correctly with Drupal 8. Is there a simple way with hooks?

EDIT 2: Maybe I mean something else?

In **Drupal 7** (with custom breadcrumb) it looks like this: The view "Informationen" is called:

One node out of the view is called:

In **Drupal 8** (with Easy breadcrumb) it looks like this: The view "Informationen" is called:

One node out of the view is called:

I hope I could explain the difference.

# Answer
> 3 votes
You should create a custom module (use core \>= 8.3). Use this code as a base to start:

**custom\_breadcrumb.info.yml**

```
name: 'Custom breadcrumbs'
description: 'Custom breadcrumbs implementation'
package: 'Custom'
# core: 8.x
type: module

version: '8.x-1.0'
core: '8.x'
project: 'custom_breadcrumb'
datestamp: 1443649740

```

**custom\_breadcrumb.services.yml**

```
services:
  custom_breadcrumb.breadcrumb_views:
    class: Drupal\custom_breadcrumb\Breadcrumb\ViewsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 1 }

```

**src/Breadcrumb/ViewsBreadcrumbBuilder.php**

```
<?php

namespace Drupal\custom_breadcrumb\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\LinkGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;

class ViewsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use LinkGeneratorTrait;
  use StringTranslationTrait;

  /**
   * @inheritdoc
   */
  public function applies(RouteMatchInterface $route_match) {
    // This breadcrumb apply only for some views.
    $parameters = $route_match->getParameters()->all();

    if (isset($parameters['view_id'])) {

       $views_id = array(
         'VIEW_MACHINE_NAME_1',
         'VIEW_MACHINE_NAME_2',
       );

       if (in_array($parameters['view_id'], $views_id)) {
         return TRUE;
       }
       return FALSE;
    }
  }

  /**
   * @inheritdoc
   */
  public function build(RouteMatchInterface $route_match) {
    // Breadcrumbs set up (cache settings are so important!).
    $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
    $breadcrumb->addCacheContexts(["url"]);
    $breadcrumb->addCacheTags(["view_id:{$parameters['view_id']}"]);

    $parameters = $route_match->getParameters()->all();
    if (isset($parameters['view_id'])) {
      if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_1') {
         $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 1'), '<none>'));
      }
      else if ($parameters['view_id'] == 'VIEW_MACHINE_NAME_2') {
        $breadcrumb->addLink(Link::createFromRoute(t('VIEWS NAME 2'), '<none>'));
      }
    }

    // Reverse order for this to work!!!.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    return $breadcrumb;
  }
}

```

Remember to replace **VIEW\_MACHINE\_NAME\_1** and **VIEW\_MACHINE\_NAME\_2** with the machine name of your views. Also replace **VIEWS NAME 1** and **VIEWS NAME 2** with the breadcrumb title you want for each view.

# Answer
> 2 votes
You can restrict the access to the view by configuring the pages section.

>

>

---
Tags: views, breadcrumbs
---


title: Warning: Missing argument 2 for l()

text:
# Question
Title: Warning: Missing argument 2 for l()
I try to show image that have link but i received error like this is anyone know and can help me .. thanks

Here's my code

```
<div id="profil">
'.tabel_budgetcenter().'
</div>
<div id="pengeluaran_pp">
'.tabel_pengeluaranpp().'
</div>
<div id="cuti">
'.l(theme('image', array(
    'path' => 'misc/images/print_24.png',
    'alt' => 'to pdf',
    'title' => 'to pdf'), "print/lpr_budget/coa_all_pdf/".$thn."/".$coacode, array("attributes"=>array('target'=>'_blank'),'html'=>TRUE))).'
'.l(theme('image', array(
    'path' => 'misc/images/excel.png',
    'alt' => 'to excel',
    'title' => 'to excel'), "print/lpr_budget/coa_all_xls/".$thn."/".$coacode, array("attributes"=>array('target'=>'_blank'),'html'=>TRUE))).'

'.tabel_budgetcenter2().'
</div>

</div>';
return $output;
}

```

# Answer
This:

```
theme('image', array(
  'path' => 'misc/images/print_24.png',
  'alt' => 'to pdf',
  'title' => 'to pdf')

```

Should be this:

```
theme('image', array(
  'path' => 'misc/images/print_24.png',
  'alt' => 'to pdf',
  'title' => 'to pdf'))

```

You missed the closing parenthesis in both this, and the next link as well.

So that means you need to change this:

```
l(theme('image', array(
  'path' => 'misc/images/print_24.png',
  'alt' => 'to pdf',
  'title' => 'to pdf'), "print/lpr_budget/coa_all_pdf/".$thn."/".$coacode, array("attributes"=>array('target'=>'_blank'),'html'=>TRUE)))

```

To this:

```
l(theme('image', array(
  'path' => 'misc/images/print_24.png',
  'alt' => 'to pdf',
  'title' => 'to pdf')), "print/lpr_budget/coa_all_pdf/".$thn."/".$coacode, array("attributes"=>array('target'=>'_blank'),'html'=>TRUE))

```

In order to correct the misplaced closing parenthesis that you put at the end of l(), instead of at the end of theme().
> 1 votes

---
Tags: 7
---


# Question
Title: How can I add markup above the table in a custom module?
I am working on a Drupal 8 custom module which renders pages as shown in the following image.

So far, I am able to build the table and my code is the following.

```
  public function dexp_layerslider_list() {
    $header = [
        'ID',
        'Name',
        'Action',
    ] ;
    $results = db_select('{dexp_layerslider}', 'd')->fields('d', [
        'id',
        'name',
    ])->execute();
    foreach ($results as $row) {
        $url = Url::fromUserInput("/admin/dexp_layerslider/". $row->id . "/edit");
        $row->name = (Link::fromTextAndUrl($row->name, $url));
        $editslides = Url::fromUserInput('/admin/dexp_layerslider/'.$row->id.'/editslides');
        $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides))->toString();
        $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
        $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides))->toString();
        $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
        $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides))->toString();
     $tmp =  [
            '#type' => 'inline_template',
             '#template' => '{{ link1 |raw }}, {{ link2 | raw }}, {{ link3 | raw}}',
                '#context' => [
                         'link1' => $editslides_link->getGeneratedLink(),
                         'link2' => $exportslides_link->getGeneratedLink(),
                            'link3' => $deleteslides_link->getGeneratedLink(),
                            ]
                    ];
        // Row with attributes on the row and some of its cells.
     $rows[] = array(
            'data' => array($row->id,$row->name,$tmp )
                );
        }
     $table = array(
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#sticky' => FALSE,
        '#empty' => t('No slider created yet.'),
         );
        for($i= 0; $i
            $table['#rows'][$i]['data'][2] = $tmp;
        }
    return $table;
 }

```

How do I add a "Add slide" and "Export slide" links?

# Answer
You have multiple solutions to achieve what you want

1. Using #prefix

```
 $table = array(
  '#prefix'=> '<div><a>my link</a></div>',
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

```
2. A better way to do this is

```
 $table = array(
  'links' => [
     '#type'=> 'container'
     'link_one'=> [
        '#type' => 'link',
        '#title' => $this->t('Add slide'),
        '#url' => Url::fromRoute('my_route'),
      ],
   ],
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

```
3. Add module definied actions: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-actions
> 1 votes

---
Tags: theming
---


# Question
Title: How can I disable all outgoing emails from a site all at once?
There are some automated outgoing emails from my Drupal site like by core system mail, ubercart, webform and Rules.

The reason is that I also have a test site which is exactly the copy of the production site. And I would like to disable all the outgoing emails so that no mails will be sent from the testing one by mistake.

I have installed "phpmailer" "mime mail" "mail editor" modules.

Is there an out-of-box way to do this?

# Answer
The Maillog module is for exactly this purpose, as

> Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core.
> 11 votes

# Answer
It would seem to me that you'd want to leave Drupal doing its business logic thing accurately as a production site. Sending Mail (or "logging email") is the mail server's job ... so we just tell the server to not really send the emails.

You can make this a development server configuration value using php.ini `sendmail_path` value. From this Stackoverflow post you can see how to set it for php.ini. While it cannot go directly into a vhost entry it may go into a directive in your local development enviroment apache configuration as per this ServerFault post.

This way no matter what you do to Drupal, the server never sends email.

```
<VirtualHost *:80>
    Standard stuff goes here

    <Directory /dir/to/your/web/root>
        php_admin_value sendmail_path "tee mail.out > /dev/null"
    </Directory>

</VirtualHost>

```
> 5 votes

# Answer
Another nice module for this exact purpose is Reroute Email. It allows you to define an email address to send all mail to while active.

> This module intercepts all outgoing emails from a Drupal site and reroutes them to a predefined configurable email address.
>
> This is useful in case where you do not want email sent from a Drupal site to reach the users. For example, if you copy a live site to a test site for the purpose of development, and you do not want any email sent to real users of the original site. Or you want to check the emails sent for uniform formatting, footers, ...etc.
>
> This is also a good demonstration of what hook\_mail\_alter(), available in Drupal 5.x and later, can do.
> 3 votes

# Answer
There is also this nice community page which lists several other possibilities to achieve the same result: Managing Mail Handling for Development or Testing
> 0 votes

# Answer
There is also MailSystem which can route outgoing emails to TestingSystem.
> 0 votes

# Answer
```
/**
 * Implements hook_mail_alter
 * it will alter all email sent by drupal
 */
function modulename_mail_alter(&$message) {
  // 'To' field as ''(blank) so it wont send any email
  $message['to'] = '';
}

```
> 0 votes

---
Tags: 6, emails, testing
---


# Question
Title: Filter |raw doesn't show entity media image
Using the following code for displaying content from a WYSIWYG field: `content.field_body|raw` I only got the text without images added in a editor as media. When I remove filter raw I see `<drupal-entity data-embed-button="media_browser" data-entity-embed....` is being displayed as a text but not as image.

# Answer
> 6 votes
This output from the body field

```
<drupal-entity data-embed-button="media_browser" data-entity-embed....

```

is the raw data stored in the database. The tag `<drupal-entity>` gets replaced by the text filter "Display embedded entities" when the field is rendered.

If you access the field data directly from the entity `#paragraph` you bypass this rendering process.

Instead of the raw filter, which doesn't help in any way, it only makes your site vulnerable to the content of the body field, you can apply the text format in a render element `processed_text`:

```
  {% set paragraph =  content.field_tabs.0['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_body.value,
    '#format':  paragraph.field_body.format,
  } %}

  {{ body }}

```

---
Tags: 8, media
---


# Question
Title: "Initial Menu Level" config in Block Layout not working
Using Drupal 8...

**Goal**

There are 2 regions in the header. The top region holds the **Level 1** menu links while the bottom region holds the **Level 2** menu links (or child links of the top regions).

What I want is for the **Who am I?** and **About** to only show on the top region. That's easy, **initial menu level is 1** and **max num of menu levels to display is 1**. That works great.

**Problem**

Problem comes along when I add the same menu to the bottom region and choose the following set up:

I thought that with these when a user clicks **About** on the top region, then the **child links** ("Just more links") of that menu link would be displayed on the bottom region. But nothing happens. It only works with the **Who am I?** link.

The only difference is that **Who am I?** points to **/node/2** while **About** points to the homepage with an added **?parameter=value**

# Answer
> 0 votes
Please check the following:

* The link for the menu item should be `<front>?parameter=value`
* The position and weight in the menu tree at `admin/structure/menu/manage/MENU_NAME`
* This patch may be related

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


title: Exposed filters doesn't work

text:
# Question
Title: Exposed filters doesn't work
I have recently come to begin to work on a site built by someone else, so I have no idea of what specifics may have been done when building this site I am referring to. At the moment, I'm trying to revamp the structure (as well as the look to play around with it in sections), and came across an interesting problem.

In the view, I have three exposed filters: 1) Object ID 2) Title 3) Keywords (from the Search:Search Terms filter).

Now when I type in the Title filter, everything works as expected. And when I type in Keywords filter for something that would be somewhere besides the Title, that works as well, with the exception of dates and numbers that aren't in the Title Field.

You can find this page here http://history.arvadahistory.org/photographs1

You will notice that each content type has a picture, then a blue title, then a black string of letters and numbers. An example being this: HF.00668

Now, when I type this (HF.00668) into the Object ID filter, I get absolutely nothing, but when I go to type this in the overall site search, the proper content pops up.

So why would my filters be acting like this? And is there any way to fix them?

# Answer
> 1 votes
Check query of view when you providing HF.00668 value in Object ID.

SQL query of views can be enable from views settings page with name of **Show the SQL query**.

You can also check operator value in exposed field settings.

---
Tags: 7, views
---


title: show entire Book Navigation tree

text:
# Question
Title: show entire Book Navigation tree
My question is about how to show the entire book navigation tree in a block (drupal 8)

Thanks to @oknate we can have a Book Navigation block with the top level book showing, But i need the whole tree. (think table of contents)

*All the folowing examples assume you are are the top page of a 3 level deep book.*

**Also, I have a working module at https://github.com/petergus/alt-book-nav.git**

Showing the title (top level) book in the book navigation block is done by replacing the following in book/src/Plugin/Block/BookNavigationBlock.php (with a custom module of course)

```
 // Only show the block if the user has view access for the top-level node.
  if ($nid) {
    $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
    // There should only be one element at the top level.
    $data = array_shift($tree);
    $below = $this->bookManager->bookTreeOutput($data['below']);
    if (!empty($below)) {
      return $below;
    }
  }

```

with

```
     if ($nid) {
        $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
        return $this->bookManager->bookTreeOutput($tree);
      }

```

That only shows the top level and child level though, I want to be able to view the full tree from any page.

I am completely new with drupal 8 and not very handy with PHP so all i could find out was that

```
     $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
     kint($tree);

```

returns only the book name and first level and

```
     $tree = $this->bookManager->bookTreeAllData($node->book['bid']);
     kint($tree);

```

(without the `$node->book`) returns multiples levels, that is, multiple 'below' arrays.

I have no idea how to go further with pulling that information into the block, does someone?

As mentioned above, I have the module that @oknate suggested at https://github.com/petergus/alt-book-nav.git

Greatly appreciating any help, and hoping this questions serves the community.

# Answer
> 1 votes
It turns that I already posted the answer in the question, but somehow missed it during testing!

Removing `, $node->book` from `$tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);` does print the entire expanded tree.

If someone has time to add a user form option to the module it could eventually benefit many and get on the drupal.org repo.

---
Tags: 8, nodes, blocks
---


# Question
Title: Form $_POST data missing value of submit button
I have a complex form API managed form that has several fieldsets with nested fieldsets and table elements (defined with webform component editor) with AJAX-controlled 'Add another' and 'Remove Last' buttons. There is also a form submit button at the end of the form, external to all fieldsets.

After a certain (of the order of 100) number of element groups (containing 4 or 5 fields each) are added and the form is submitted, the `$_POST` data generated after submitting the form does not include the value of the input element, so at a later stage the form API cannot determine the correct triggering element in function `_form_button_was_clicked` of form.inc.

The `$form_state['input'][$element['#name']]` element does not exist.

I've doubled the `post_max_data` and explicitly named the input element (by setting `$element['#name']`), all to no avail. I'd appreciate any thought on what else to try...

# Answer
> 1 votes
As sanzante suggested, the solution is to increase php's max\_input\_vars setting. I did it in the site's .htaccess file.

---
Tags: forms
---


# Question
Title: Remove the link "add comment" if the user has already commented on the node
I wish that my users can leave only one comment per node (including by using the url).

**Once their posted comment, I wish that the link "add comment" disappears.**

I tried numerous solutions, such as Onecomment or custom code, but all prevent the second comment at the level of the form (form validate), with an error.

I would like for better user experience than it is not upstream possible to click on "add comment".

Do you know a solution ?

# Answer
> 2 votes
If you are OK with custom modules, you can make the module below. If you have never made a custom module before, just make a folder called `single_comment` and create 2 files inside called `single_comment.info` and `single_comment.module` then add the code below into the respective files.

**single\_comment.info**

```
name = Single Comment
description = Allow users to only add one comment to a node.
core = 7.x

```

**single\_comment.module**

```
function single_comment_node_load($nodes, $types) {
  global $user;
  if (user_is_logged_in()) {
    foreach ($nodes as $node) {
      $comment_arr = comment_load_multiple(comment_get_thread($node, COMMENT_MODE_FLAT, 100));
      foreach ($comment_arr as $comment) {
        if ($comment->uid == $user->uid) {
          $node->comment = COMMENT_NODE_CLOSED;
          break;
        }
      }
    }
  }
}

```

You can call the module whatever you like but just remember to replace anywhere single\_comment occurs. That includes the folder, file names, name in .info and the function name.

# Answer
> 1 votes
I've never tried this solution. But it seems like you could

* Get the username of the current user... with a module such as something like this https://www.drupal.org/node/141110
* If that user has a comment, hide the add comment button. This presumes that you can figure out the author of the comment (you could potentially override the comment display .tpl to write that into JS, or at least make it easy to pick up with jQuery)

If your users aren't logged in, that would make things a little bit more tricky.

---
Tags: 7
---


title: Discount by time and not by date

text:
# Question
Title: Discount by time and not by date
How can I achieve the discount by time on not by date functionality. I have to provide discount on 8 March from 8AM to 8PM.

# Answer
> 2 votes
Currently, Commerce Discount doesn't support specific times in it's discount rules.

You could use PHP evaluation to make this work, though.

# Answer
> 0 votes
If you want to show date-time you can try this: https://www.drupal.org/project/stanford\_date\_timepicker

alter file commerce\_discount.admin.inc

```
$element['date']['#title'] = t('Start date');
// New class to show date time like 03/22/2017 12:32
$element['date']['#attributes']['class'][] = 'stanford-timepicker';
$element['date']['#description'] = t('Starts at 12:00:00 AM');

```

Note: need to change the tables accordingly.

---
Tags: commerce
---


# Question
Title: How to resolve error 'migration_group' entity with ID 'migrate_drupal_7' already exists?
I have been trying to migrate to Drupal 8 using the drush. I have followed all the instruction as mentioned in \[https://drupalize.me/blog/201604/custom-drupal-drupal-migrations-migrate-tools\]\[1\]

After installation, enabled all the required modules like **migrate upgrade, migrate tools and migrate plus**, and then added the code in settings.php file mentioned below.

```
 // Database entry for `drush migrate-upgrade --configure-only`
$databases['upgrade']['default'] = array (
  'database' => 'dbname',
  'username' => 'dbuser',
  'password' => 'dbpass',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
// Database entry for `drush migrate-import --all`
$databases['migrate']['default'] = array (
  'database' => 'dbname',
  'username' => 'dbuser',
  'password' => 'dbpass',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

Now used the command - `**drush migrate-upgrade --configure-only --legacy-db-url=mysql://dbuser:dbpass@localhost/dbname --legacy-root=/path/to/sites/default/files**` and than drush returns the following errors - `***'migration_group' entity with ID 'migrate_drupal_7' already exists***`

How can I resolve the error?

# Answer
> 2 votes
you can delete existing migration groups from: /admin/structure/migrate

---
Tags: migrations
---


title: Modal form instead of redirect

text:
# Question
Title: Modal form instead of redirect
I have a site-wide contact form setup that redirects the user to the homepage and posts the submission result to the help section. It works as intended, but I was wondering what I would need to do to change this behaviour.

Instead of redirecting, I would like to display the form submission result in a modal (maybe jQuery) popup.

**How could I achieve this?**

I wouldn't like to lose the core functionality, just maybe override it with a custom module or something. Any thoughts?

**EDIT:**

Starting with @rémy 's suggestion, I created a `.module` file where I'm trying to override the standard behavior for form submission.

Right now the only thing I have is as follows (although it doesn´t work):

```
<?php

/*
*  Override the the form submit behaviour.
*/

function modal_contact_form_result_form_node_form_alter(&$form,       FormStateInterface $form_state, $form_id){
    $form['actions']['submit']['ajax'] = array(
        'callback' => 'ajax_test_dialog_form_callback_modal'
    );
}

function ajax_test_dialog_form_callback_modal($form, FormStateInterface $form_state){
    $response = new AjaxResponse();
    $content = 'Form submitted successfully, thank you!';
    $title = 'YForm submited';
    $response->addCommand(new OpenModalDialogCommand($title, $content, array('width' => '700' )));

return $response;

}

```

But at this moment it neither prevents redirecting nor pops up the modal.

# Answer
> 3 votes
In a custom module, you need to alter the contact form and add an #ajax attribute to the submit button:

```
function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
    $form['#prefix'] = '<div id="my_form_wrapper">';
    $form['#suffix'] = '</div>';

    $form['actions']['submit']['#ajax'] => array(
          'callback' => 'ajax_test_dialog_form_callback_modal',
    );
}

```

And then provide this method, using OpenModalDialogCommand, in your module too:

```
    function ajax_test_dialog_form_callback_modal($form, &$form_state) {
      $response = new AjaxResponse();

      if ($form_state->getErrors()) {
        unset($form['#prefix']);
        unset($form['#suffix']);
        $form['status_messages'] = [
          '#type' => 'status_messages',
          '#weight' => -10,
        ];
        $response->addCommand(new HtmlCommand('#my_form_wrapper', $form));
      }
      else {
        $content = 'Something to show in the modal';
        $title = 'Hi, I'm a Modal';
        $response = new AjaxResponse();
        $response->addCommand(new OpenModalDialogCommand($title, $content, array('width' => '700')));
      }
      return $response;
    }

```

> Here I'm making use of the form element status\_messages to display validation errors, otherwise we pop up a modal with custom text.

With drupal\_get\_messages() you could get the system messages and clear the queue.

Don't forget to make the classes available

```
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

```

# Answer
> 1 votes
Have a look to your drupal watchdog.

You may add at the beginning of your module :

```
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

```

# Answer
> 1 votes
Check out https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8 \- it explains loading and rendering forms in modal dialogs in Drupal 8.

---
Tags: 8, ajax, emails
---


# Question
Title: How do I enable User 1 rights in minimal installation?
I have Drupal 8 minimal installation profile and it does not seem to have provided *super user* status to the first admin account created during the installation process.

How do I enable it?

# Answer
User 1 doesn't need any roles to have super user status. User 1 is exempted from the permissions system entirely. So, they automatically have all permissions, regardless of roles they may or may not have.
> 4 votes

---
Tags: 8, users, installation-profiles
---


# Question
Title: Multisites with shared files folder – good or bad idea?
I'm lacking experience on the following issue and unfortunately it isn't documented explicitly. I'ld like to have a shared files folder for a handful of multi-sites. As those sites all represent sub-organisations of one and the same parent organisation it should be possible that all of them have access to the same files in one certain files subdirectory using a shared file manager like IMCE.

The only concrete clue I found is on https://www.drupal.org/node/53705. But this is about Drupal 5.

> A /files directory could easily be shared across two domains without being shared across the remaining domains.

I wildly guess this didn't change much for following versions. But, have anybody ever tried it this way in production? Would you have any concerns doing it this way? What else could I consider to do instead?

As far as I've tested it right now this seems to work. Also images and files uploaded to image and file fields on site A stayed in the shared files folder even after multiple cron runs on site B and site C (as Clive noted to have a look at the file\_usage logic).

I also then deleted the files and images from site A's nodes and run site A's cron multiple times. Still the files stayed there. But this simply might be a permission issue, maybe.

# Answer
> 1 votes
This should not work. Managed files should be automatically removed once there are no more entries in the file\_usage table for them. I see you say that it's not happening on your setup, but maybe that's a permission or some other issue. That's not how it's supposed to work.

I'm curious how you plan on this working, in any case. If you're using file fields, then Sites B and C would have no way to know that you uploaded a file to Site A, so how it is useful? You say that you're using a file manager. Is it like IMCE or something where you are just browsing the files by directory? If you upload a file through something like that, it wouldn't get an entry in the files\_managed table, so it would not be automatically deleted. That would make sense.

---
Tags: files, multi-sites
---


# Question
Title: How to not display redundant information in table Views?
In a custom module of mine (Drupal 8.2.6), I have two custom entities A and B with a one to many relationship from A to B.
I use Views (table view) to display content of A and B and by default I get this:
Field1 (from A) Field2 (from B)
xxx aaa
yyy bbb
yyy ccc
zzz ddd
I'd like to NOT display yyy the second time.
How can I do that?

\[Edit\] just an example, instead of what is (by default) on the left, I'd like what is on the right of the picture:

# Answer
> 0 votes
Finally I found another solution using Rewrite Results.
Depending on another field (which can be hidden), I output 'nothing' or 'the content':

# Answer
> 1 votes
You can try Views Field View module.

1. Create a "secondary" view of Field2 contextualy filtered by relationship with EntityA.
2. In your main view, use Field1 and new Views Field of your "secondary" view (this field type is added by module).
3. Set up that new Views Field in your view to pass proper argument to "secondary" view contextual filter (and therefore show relevant Field2s related to EntityA)

---
Tags: views, 8
---


title: CSS and Js not loading with https

text:
# Question
Title: CSS and Js not loading with https
I'm trying to put my entire website under https connexion, but my css and js are not loaded. I don't know why.

I had this code to the htaccess at the root of the website :

```
  # Force HTTPS and WWW
  RewriteCond %{HTTP:HTTPS} !on
  RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]

```

And didn't touch anything else. If it's relevant, I'm using a hosting from online.net (french provider).

# Answer
So after researches, everything work now and here is my configuration :

I putted this code into my sites/default/setting.php file :

```
$conf['https'] = FALSE;
if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://www.efficient-network.eu';
}
else {
  $base_url = 'http://www.efficient-network.eu';
}
$_SERVER['HTTPS'] = 'On';

```

And needed to add a custom module to load every line in `<head> </head>` with https :

```
function https_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}

```

I don't know if it's the proper method, but it works.
> 1 votes

---
Tags: 7, security
---


title: How To Make Token Works On Field Label?

text:
# Question
Title: How To Make Token Works On Field Label?
I've created a custom content type and I have a field which referencing a views (Using Viewfield Module). Now I want to alter the field label using `[current-page:title]` token, But Token isn't working on field label.

I've tried `[current-page:title]` on field label, But the token is just print out not value.

How can I Use token on Field label?

# Answer
These two articles might help you out:

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

(From this article)

The Token module for Drupal 7 currently provides support for basic-level field tokens like \[node:field\_my\_image\_field\] and \[node:field\_node\_reference\_field\].

Customizing field token output

Sometimes the field tokens may not output as desired. To change how they are output, you must perform the following steps:

Enable the 'Token' custom display setting. Go to the "Manage display" of the entity type and bundle for which token you are trying to change. For example, to change how fields on Article nodes are displayed in tokens, go to admin/structure/types/manage/article/display. Expand the Custom display settings fieldset at the bottom of the page, click the "Tokens" checkbox, and then click the Save button.

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

(From this article)

The labels are not part of the field and are not intended to be. The style renders the field and label separately. In the vast majority of use cases, you do not want the label. If you do, you can rewrite the original field to include the label, or include the label as you like.
> 2 votes

---
Tags: entities, tokens
---


# Question
Title: The send function does not work in a custom form
I have a module that creates a form in a block with a template. But when I press the submit button, it does not execute the `submitForm` function. Instead if in the template only `{{form}}` if you do.

To clarify, in the template the fields are customized and I call them: `{{form.date}}`, `{{form.submit}}`

```
/**
 * {@inheritdoc}
 */
public function getFormId() {
    return 'custom_form';
}

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {

    $form['name'] = [
        '#type' => 'textfield',
        '#size' => 60,
        '#placeholder' => 'Votre nom',
        '#maxlength' => 128,
        '#required' => TRUE,
    ];

    $form['tel'] = [
        '#type' => 'number',
        '#default_value' => "",
        '#placeholder' => 'Votre numéro',
        '#size' => 20,
        '#maxlength' => 20,
    ];

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Réserver'),
        '#button_type' => 'primary',
    );

    return $form;
}

 /**
 * {@inheritdoc}
 */
 public function submitForm(array &$form, FormStateInterface $form_state) {

foreach ($form_state->getValues() as $key => $value) {
  drupal_set_message($key . ': ' . $value);
}
 }

```

# Answer
> 1 votes
You have to write the submit handler for the form to save data.

```
  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Insert queries.

    $query = \Drupal::database()->insert('mymodule_table');
    $query->fields([
      'name' => $form_state->getValue('name'),
      'tel' => $form_state->getValue('tel'),
    ]);
    $query->execute();

  }

```

# Answer
> 1 votes
I believe you do have to render with `{{ form }}` because it will render more than just your two form items. This is why the submit is not executing. If that is all you have in your twig, then it would sound like you are missing a form tag and hidden form elements.

# Answer
> 0 votes
If you don't render with {{ form }}, you have to make sure to add these elements to your twig:

```
{{ element.form_build_id }} {# required #}
{{ element.form_id }} {# required #}

```

as well as adding the html manually and adding the appropriate attributes. This gives you more flexility in your template. But there are many advantages to just using {{ form }}, such as managing the elements entirely in your form class, rather than having to update two places. But sometimes if your layout is really odd, it may make more sense to break the form elements up in the template.

---
Tags: 8, forms, blocks
---


# Question
Title: Cache images in custom module without caching entire render array
I created a module that generates a slide show. This isn't using views, I'm manually loading nodes that contain images and placing them inside a render array in a block plugin. When running an audit in chrome I noticed a message

> The following resources are explicitly non-cacheable.

Then it lists all the images present in that slideshow. After reading this I understand that you can cache render arrays, but I still need it to be dynamic, so that the slideshow updates everytime a node is added. Also different slideshows are shown to different users so I need that dynamic as well.

Is there a way to cache only the images in a render array?

# Answer
> 2 votes
Blocks are cached by default in Drupal 8. The image non-cachable warning isn't a drupal issue. It's a false flag from chrome. Because image derivatives in Drupal (those generated from an image style) have a query argument chrome thinks it's not cachable.

To test that your block plug-in is caching, you can put a die() statement inside the build method to test if the code runs on each page load. If it is running on each page load, you can comment out elements until it does use cache. Then it should run the code once and then on subsequent page loads it won't run the code.

To make sure your block is refreshed when certain nodes are cleared, you can add them to the cache tags in your build array. This may happen automatically if you are pulling the render array from each image from the node it came from. Otherwise you can add them in your code like this:

```
$build['image']['#cache']['tags'][] = 'node:123';

```

To test, clear the cache and reload the page. Verify on the cache\_render table that the block is cached and your tag is there.

To test that editing that node updates the block, first update that node. Then on the next page load of the page with your block, it should re-run the code for your block plugin.

To make sure the block is unique per user, you can add the user context to the cache contexts array

```
$build['image']['#cache']['contexts'][] = 'user';

```

To test, clear the cache, then reload the page with your block. Check on the cache\_render table that the cached item has user in the cid column.

Something like:

```
entity_view:block:my_block:[languages:language_interface]=en:[theme]=abilitylab_theme:[user]=123

```

Then test the block with a different user, and there you go: Unique block per user.

---
Tags: theming, 8, blocks
---


title: How can I change accordion style?

text:
# Question
Title: How can I change accordion style?
I added the Accordion module on Drupal 7 and it works without any problem, but I would like to change the style of the view. I have already read the documentation, but I don't know how I can put CSS styles to the view.

I can add styles to the views-accordion.css file but I don't know how to add the classes to the view or how to make it use my styles instead of its default styles.

**Update :**

I edited the file views-view-accordion.tpl.php, but still no result ! The styles will not change !

# Answer
> 1 votes
You have to check this:

This module comes with a default css stylesheet, which **you can disable in the options**.

Files included for your convinence:

* views-acordion.css - A default stylesheet with how the classes the author thought would be best used.
* views-view-accordion.tpl.php - **copy/paste into your theme directory** \- please the comments in this file for requirements/instructions. Both files are commented to explain how things work. Do read them to speed things up.

So you have to follow this instructions, add a custom styles on your theme, add custom classes in your template (If you need it), but dont forget default clasess make animation work.

---
Tags: theming, navigation
---