# Question
Title: Javascript will not load for anonymous users
I have a controller with a route that has some javascript attached to it as a library. When logged in as any user (admin or standard) the JS loads just fine. When anonymous, the library file is loaded, but Drupal JS is not.

How the library is defined:

```
my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery

```

In the console the error says:

> ReferenceError: Drupal is not defined
>
> \< anonymous \> http://example.com/themes/custom/my\_theme/js/my\_javascript.js:7:3
>
> \< anonymous \> http://example.com/themes/custom/my\_theme/js/my\_javascript.js:6:2

The lines in the JS the error is referring to are:

```
(function ($) {
  Drupal.behaviors.myScripts = {

```

This is the case for all browsers. JS works fine when logged in as any user, but when anonymous, Drupal's JS does not load.

# Answer
The code in the question appears to be similar to what was done in Drupal 7. In Drupal 8, the dependencies for your javascript need to be explicitly defined and it is a good idea to pass them through the closure as well. You can read more about the Javascript API in Drupal 8 on the new documentation pages.

```
my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal

(function ($, Drupal) {
  Drupal.behaviors.myScripts = {};
)(jQuery, Drupal);

```
> 10 votes

# Answer
Solved by adding more dependencies to the library definition and adding a hook to add the JS again, and render libraries.

New library definition:

```
my_javascript:
  version: 1.x
  js:
    js/my_javascript.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

Hook to render libraries:

```
function my_theme_preprocess_page(array &$variables) {
  $attachments['#attached']['library'][] = 'my_theme/my_javascript';
  \Drupal::service('renderer')->renderRoot($libraries);
}

```

Update: The hook was not needed, but adding the Drupal object in behaviors correctly for D8 was. Accepted another answer instead.
> 0 votes

---
Tags: 8, users, javascript
---


# Question
Title: "Source database does not contain a recognizable Drupal version."
I have installed two Drupal sites in my local Ubuntu desktop 15.10 Apache2 (2.4.12) environment: One is a fresh install of Drupal 8 and The second is a copy of an existing working site built with Drupal 7 (which is mostly core-modules based, very humble by means of pages). Both sites are working fine without any problem, anywhere.

My aim is first and foremost upgrading the Drupal 7 site to Drupal 8. I did all the preliminary stages like configuring the same languages, Keep minimal by means of modules (uninstalling any modules in the D7 site that I could easily bring back after the Upgrade), making sure the same modules are installed in both sites, etc, and now I just want to "Transcend" (hope its a good phrasing) my Drupal 7 site into the fresh Drupal 8 one.

To achieve my aim I've installed the Drupal Upgrade module in my Drupal 8 site, went to localhost/sitename/upgrade, and filled in all the details of the Drupal 7 site.

When I clicked the "Review upgrade" button I got the error:

> Source database does not contain a recognizable Drupal version.

I've googled this error as an exact phrase ("Error") and found very few results; Most of them seem to me to require a PHP programming knowledge that I've yet acquired, so I can't determine if the error is due to a bug (especially since this module is still under heavy development) or due to my mistake in understanding the concept\functionality of this module.

1. What reasons are there that the D8 Drupal upgrade module wont "like" the D7 database I provided? Especially while the Drupal 7 site is working fine both online and locally.
2. Would migrating be a decent alternative for upgrading, if upgrading isn't possible for whatever reason? If so, what is the best most simple solution You could think of for migration?

I went to /var/www/html/benia/modules/migrate\_upgrade/src/MigrationCreationTrait.php and did:

```
-- return $version_string ? substr($version_string, 0, 1) : FALSE;

++ return 7;
++ return $version_string ? substr($version_string, 0, 1) : FALSE;

```

Than got this error in top of the screen.

# Answer
> 0 votes
I left 2 modules installed, which I (then) thought to be "so basic" they had a migration path just as all core modules have. These were, if I remember correctly, Metatag and Redirect.

These, and other modules, do now have contributed migration paths you can use by patching them with this migration path. (You "inject" it into the module with the path.)

# Answer
> 4 votes
At this stage, I don't think there is a `simple` option to upgrade from 7 to 8. As you can see on the release note:

> Once you are ready, Drupal 8 core also includes the Migrate module to update existing Drupal 7 and 6 sites to Drupal 8 directly. Migrate is marked "experimental" in Drupal 8.0.0, but will be fully supported in an upcoming release. https://www.drupal.org/news/drupal-8.0.0-released

A little bit technical behind the scene: From 7 to 8 version, they keep the same concept when building site (like node, entity, permission, views...) but not the core. I would say: they changed everything to OOP, Symfony component, architecture... So there is no way to `upgrade` your drupal site directly from decent version to 8.0, you have to `migrate`. Here is how the `migrating` process should look:

1. Recreate the site with the same functionality to your d7 site.
2. Recreate the theme (using twig template)
3. Migrate content over

The cost to this process is (unfortunately) same to recreate a new site or more. With the no 3, take a look at this article by Phase 2: https://www.phase2technology.com/blog/upgrading-to-a-drupal-8-site/

# Answer
> 2 votes
Your error message is an exact match with the string contained in the line at http://cgit.drupalcode.org/migrate\_upgrade/tree/src/MigrationCreationTrait.php#n40 within the code of the "Drupal Upgrade" module (https://www.drupal.org/project/migrate\_upgrade).

It shows that it is not a bug, but instead an "exception being thrown". Looking at the 3 proceeding lines of that code, I think it is only a problem in setting up the connection.

See also comment #3 on Drupal Database not recognized.

> To check that the source database is a valid Drupal database, and to determine the version of the database, the upgrade process looks at the 'system' table - is that table present in the database you specified in the form? Is the Drupal installation in that database prefixed (and if so, did you enter the prefix in the "Advanced options" section of the form)?".

That is followed by comment #4 in that same issue.

> Providing tables' prefix solved the issue.

And of course, the comment from benjy would also help to get more details about the actual error you're running into.

> You could print out `$e->getException()` and then you'll see the PDO error.

You could (temporary) add such print between lines 122 and 123.

# Answer
> 0 votes
Once I got that error message. It turned out to be the database prefix set by me, *drupal\_*. You should put that in the advanced options.

---
Tags: 8, migrations
---


title: Clean URLs cannot be enabled

text:
# Question
Title: Clean URLs cannot be enabled
I'm stuck on this issue, I've followed a variety of idea and tutorials trying to fix the issue, most which follow a similar path to this (http://stevenmcmurry.com/howto/2014\_07/enabling-clean-urls-drupal-ubuntu-1404-lts). I'm running off of Apache2 on Ubuntu.

Currently my 000-default.conf looks like this:

```
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        <Directory /var/www/html/>
    AllowOverride All
    Order Allow,Deny
    Allow from all
</Directory>
# error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

</VirtualHost>

```

But I'm still running into the issue of clean URL's not allowed to be enabled. The odd thing I'm trying to work on is at the moment, I can't see the .htaccess in the drupal site root.

Has anyone run across a situation like this?

Thanks!

# Answer
Mostly .htaccess is hidden While viewing cpanel click to show hidden files also, Else download .htaccess file and put it on root directory
> 0 votes

# Answer
It appears Ubuntu decided the files with "." prefixes shouldn't be moved along with the rest of the download directory. Redownloaded .htaccess and moved .htaccess file with sudo command from download file to drupal root folder.
> 0 votes

---
Tags: 7, installation
---


# Question
Title: Changing the routing class is throwing an error
I am trying to change my UserLoginForm class to iLibUserLoginForm with the following code.

```
namespace Drupal\ilib_sso\Routing;

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

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\ilib_sso\Form\iLIBUserLoginForm');
    }
  }

}

```

This is the original yml.

```
user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

```

My iLIBUserLoginForm.php file with the extending class inside it exists at `ilib_sso/src/Form/` but I keep getting the following error:

> Fatal error: Cannot declare class Drupal\user\Form\iLIBUserLoginForm, because the name is already in use in /var/www/company/web/modules/custom/ilib\_sso/src/Form/iLIBUserLoginForm.php on line 258

Why is it re-declaring this class in `Drupal\user`? How do I prevent that, or modify it so that it works?

All I'm trying to do is extend the login form class with my own custom one.

```
class iLIBUserLoginForm extends UserLoginForm {
  // ...
}

```

# Answer
> 1 votes
There is no "it" involved here.

*You* defined it in the \Drupal\user namespace, as you probably copied the class from user and didn't fix the namespace definition.

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


# Question
Title: The path_processor_outbound service only work after clearing the cache
I tried overwrite all links from my site in Drupal 8 in accordance with a URL parameter.

I use the service path\_processor\_outbound and implemented the `processOutbound()` method, extending the `OutboundPathProcessorInterface` interface.

### services.yml

```
services:
   test_concept.test_concept_sayHelloService:
   class: Drupal\test_concept\Services\TestConceptRepeater
   tags:
      - { name: 'path_processor_inbound', priority: 100 }
      - { name: 'path_processor_outbound', priority: 300 }

```

### Method of my class

```
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
  $current_uri = \Drupal::request()->getRequestUri();
  $path_args = explode('/', $current_uri);
  $sede = $path_args[1];
  $path = "/" . $sede . $path;
  return $path;
}

```

This work very good when reloading the site alter flushing the cache, but when I change the URL parameter and reload the site again, the URLs don't change, even if `processOutbound()` runs again.

Is a problem with the cache?

# Answer
That's because those links get cached and Drupal doesn't know by what to vary those caches.

That's why you receive that additional argument, $bubbleable\_metadata. You need to use it to specify that our changes depend on a certain url parameter. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

You need something like this:

```
if ($bubbleable_metadata) {
  $bubbleable_metadata->addCacheContexts(['url.query_args:your_parameter']);
}

```
> 4 votes

---
Tags: 8, uri, symfony-services
---


# Question
Title: Why is the default display for a custom entity blank?
I have two custom entities, which use the same boilerplate framework. I can add content to both, but one displays fine (sample) and the other is just blank (chemical).

The twig templates for both are:

module/templates/chemical.html.twig

```
<div{{ attributes.addClass('chemical') }}>
{% if content %}
  {{- content -}}
{% endif %}
</div>

```

and in module/templates/sample.html.twig

```
<div{{ attributes.addClass('sample') }}>
{% if content %}
  {{- content -}}
{% endif %}
</div>

```

There are no error messages. Is there something in the entity definition file module/src/Entity/Chemical.php that might be throwing off the display, but still allowing the data to be entered and saved correctly?

Here is the Chemical Entity definition:

```
<?php

namespace Drupal\lab_system\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;

/**
 * Defines the Chemical entity.
 *
 * @ingroup lab_system
 *
 * @ContentEntityType(
 *   id = "chemical",
 *   label = @Translation("Chemical"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\lab_system\ChemicalListBuilder",
 *     "views_data" = "Drupal\lab_system\Entity\ChemicalViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\lab_system\Form\ChemicalForm",
 *       "add" = "Drupal\lab_system\Form\ChemicalForm",
 *       "edit" = "Drupal\lab_system\Form\ChemicalForm",
 *       "delete" = "Drupal\lab_system\Form\ChemicalDeleteForm",
 *     },
 *     "access" = "Drupal\lab_system\ChemicalAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\lab_system\ChemicalHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "chemical",
 *   admin_permission = "administer chemical entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "smiles" = "smiles",
 *     "boiling_point" = "boiling_point",
 *     "tid" = "tid",
 *     "alternate_tid" = "alternate_tid",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/lab_system/chemical/{chemical}",
 *     "add-form" = "/admin/structure/lab_system/chemical/add",
 *     "edit-form" = "/admin/structure/lab_system/chemical/{chemical}/edit",
 *     "delete-form" = "/admin/structure/lab_system/chemical/{chemical}/delete",
 *     "collection" = "/admin/structure/lab_system/chemical",
 *   },
 *   field_ui_base_route = "chemical.settings"
 * )
 */
class Chemical extends ContentEntityBase implements ChemicalInterface {

  /**
   * {@inheritdoc}
   */
  public function getAlternateNames() {
    return $this->get('alternate_names')->values;
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getSmiles() {
    return $this->get('smiles')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function getBoilingPoint() {
    return $this->get('boiling_point')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setBoilingPoint($bp) {
    $this->set('boiling_point', $bp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);

$fields['name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Name'))
  ->setDescription(t('The name of the Chemical entity.'))
  ->setSettings(array(
    'max_length' => 50,
    'text_processing' => 0,
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

$fields['alternate_names'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Alternate Name'))
  ->setDescription(t('Alternate Names.'))
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setSettings(array(
    'max_length' => 50,
    'text_processing' => 0,
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

$fields['smiles'] = BaseFieldDefinition::create('string')
  ->setLabel(t('SMILES'))
  ->setDescription(t('The SMILES structure.'))
  ->setSettings(array(
    'max_length' => 100,
    'text_processing' => 0,
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

$fields['boiling_point'] = BaseFieldDefinition::create('float')
  ->setLabel(t('Boiling Point'))
  ->setDescription(t('The boiling point of the compound.'))
  ->setDefaultValue(TRUE)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'float',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'string_textfield',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

$fields['tid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Chemical Family'))
  ->setDescription(t('The family to which this chemical belongs.'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'integer',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

$fields['alternate_tid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Chemical Family'))
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setDescription(t('The family to which this chemical belongs.'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'integer',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

return $fields;
  }

}

```

# Answer
Probably because you have no preprocess hooks for your template? And did you define the templates with hook\_theme()? You probably have render element =\> 'elements' there, but that means your output is actually in elements, not in content.

See https://www.drupal.org/node/2808481 for an issue to add generic entity templates to all entities with everything that's needed, that will also show you what you currently need to do yourself to get something in {{ content }}
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Different front page node depending on logged in?
How would I go about displaying a different front page node depending on if the user is logged in or not.

For example when a user is not logged in, you would be viewing the About Page. When a user is logged in, you would be viewing your user profile page.

# Answer
There is several solutions to go about this

but the easy way out is this module

Frontpage module

but you can also make a simple rule that says that `if the user is logged in`

Rules module

Node.js Alternativ solution

hope it helps you on the way
> 2 votes

# Answer
```
if (user_is_logged_in()){
   drupal_goto('your-logged-in-page');
}

```
> 0 votes

---
Tags: 7, theming, nodes
---


title: Node clone module - how to use it?

text:
# Question
Title: Node clone module - how to use it?
I am using Node clone.
The administration part of the module works 100%. I can edit the settings, but the clone tab that should appear beside the other node related tabs (edit, devel...) does not appear.

Has anyone out there used this module and could help me?

# Answer
I have enabled Node clone on a Drupal 7 site. The cloning capability appears as an action link at the beginning of the node content on the View tab, *not* as a separate tab. The link text is "Clone content". The actual HTML is:

```
<ul class="action-links"><li><a href="/node/34/clone">Clone content</a></li>

```

I'm using a clean Zen subtheme. Perhaps your theme is preventing the action links from appearing?
> 8 votes

# Answer
This is an older question, but for anyone out there looking for a solution to this for Drupal 7, the simplest way is to install the Node Clone Tab module, and it will appear as a tab next to View, Edit, Devel, etc.
> 4 votes

# Answer
Sounds like a permission issue, this module defines 2 new permissions, have you set them for the users you want?
> 2 votes

# Answer
I experienced the same problem, the "Clone Content" link wasn't displayed on my node preview page because I had a custom built theme that only output certain fields for each node. Try switching to another theme and see I that solves your problem.

The reason why the link didn't appear was because I had removed the following code from the page.tpl.php

```
 <?php
 if ($action_links): ?>
    <ul class="action-links"><?php print render($action_links); ?></ul>
 <?php endif; ?>

```

My suggestion is to check your page.tpl.php file so that the above statement really exists. If it doesn't simply copy the code into your template. *note* remember to empty your cache after doing so.
> 2 votes

# Answer
If you have Views installed, and /admin/content has been set up to have editable views, you can add the "Clone" link to the view. Just click the gear (that appears when you hover over the view) and choose "Edit view". Then (next to the word "FIELDS") click "add". Select "Content: Clone link" from the list of fields to add. Don't bother with a (column header) label, and you can leave all other settings at the defaults. Save the view and you should have a "Clone" link next to every node (that you haven't excluded in the configuration for Node Clone).
> 1 votes

# Answer
I meet the same problem on Drupal 8 with a Bootstrap theme. Inspired by Dan Halbert's answer above

> The cloning capability appears as an action link at the beginning of the node content on the View tab, not as a separate tab. The link text is "Clone content".

I turn on the action link (Primary admin action, under Structure \> Block layout) and it works exactly.
> 1 votes

---
Tags: 7
---


# Question
Title: Submit AJAX form and update database then show all database results
Is what i am trying to do is on this page it will display all items from the database that currently exist. Then at the top of this list will be a small form that will allow someone to add an item to the list. After someone submits the data and posts the form I want the list below to automatically populate with the updated data. I am having a really hard time trying to figure this out.

```
function clay_mod_blacklist_form($form, &$form_state) {
drupal_add_css(drupal_get_path('module', 'clay_mod') . '/css/clay_mod.min.css');
drupal_add_js(drupal_get_path('module', 'clay_mod') . '/js/jquery.maskedinput.js');
drupal_add_js(drupal_get_path('module', 'clay_mod') . '/js/clay_mod.js');

$form['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company Name'),
    '#required' => TRUE
);
$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Contact Name'),
    '#required' => TRUE
);
$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => t('Phone'),
    '#required' => TRUE
);
$form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#required' => TRUE
);
$form['submit_button'] = array(
    '#type' => 'button',
    '#submit' => array('clay_mod_blacklist_form_submit'),
    '#ajax' => array(
        'callback' => 'clay_mod_blacklist_form_ajax',
        'wrapper' => 'box',
        'method' => 'after'
    ),
    '#value' => t('Add To Blacklist'),
    '#id' => 'ajax-save-form-values'
);

$form['results'] = array(
    '#type' => 'container',
    '#prefix' => '<div class="customShit" id="box">',
    '#suffix' => '</div>'
);

if(isset($form_state['values'])) {
    $form['results'][] = $form_state['values']['results'];
}
// This is where I was display info from database before the form was submitted
//    if(!empty($form_state['values']['results'])) {
//        $form['results'] = $form_state['values']['results'];
//    } else {
//        $rows = db_select('blacklist', 't')
//            ->fields('t')
//            ->execute()
//            ->fetchAll();
//        foreach($rows as $k => $v) {
//            $form['results'][$k]['#markup'] = "<div    class=\"vvvvvvvvv\">x{$v->name}y</div>";
//        }
//    }

return $form;
}
function clay_mod_blacklist_form_ajax($form, $form_state) {
    return $form['results'];
}
function clay_mod_blacklist_form_submit($form, $form_state) {
   ddl('ajax submit');
   $form_state['rebuild'] = TRUE;
   clay_mod_blacklist_form_save($form, $form_state);

}
function  clay_mod_blacklist_form_save(&$form, &$form_state) {
$companyName = $form_state['values']['company'];
$name = $form_state['values']['name'];
$phone = $form_state['values']['phone'];
$email = $form_state['values']['email'];
$query = db_insert('blacklist')
    ->fields(array(
        'company_name' => $companyName,
        'name' => $name,
        'phone' => $phone,
        'email' => $email,
    ))->execute();
}

```

# Answer
> 0 votes
Add a wrapper around the entire form, and return the entire form from your ajax callback. Then just build the rows reguarly in your form definition - The newly added rows will be shown since all the data is pulled from the database when the from is generated.

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

  // Add the rest of your form definition here

  $form['submit_button'] = array(
    '#type' => 'button',
    '#submit' => array('clay_mod_blacklist_form_submit'),
    '#ajax' => array(
      'callback' => 'clay_mod_blacklist_form_ajax',
      'wrapper' => 'clay_mod_blacklist_form_wrapper',
      'method' => 'after'
    ),
    '#value' => t('Add To Blacklist'),
  );

  $rows = db_select('blacklist', 't')
    ->fields('t')
    ->execute()
    ->fetchAll();
  foreach($rows as $k => $v) {
    $form['results'][$k]['#markup'] = "<div    class=\"vvvvvvvvv\">x{$v->name}y</div>";
}

function clay_mod_blacklist_form_ajax(&$form, &$form_state)
{
  return $form;
}

```

---
Tags: forms, database, ajax
---


title: BCC For drupal mail function

text:
# Question
Title: BCC For drupal mail function
I am using Drupal 7 and focused to work with email option. I am using the Forward module. How can I add the BCC field in the drupal\_mail() function.

my default function having,

```
drupal_mail('forward', 'forward_page', trim($to), language_default(), $params, $params['from']);

```

# Answer
> 28 votes
Everything you need is in the email message headers array.

```
$params['headers'] = array(
    'Bcc' => 'bcc_email@example.com',
    'Cc' => 'cc_email@example.com',
);

```

Here is an example implementation of drupal\_mail() with bcc headers included.

```
$params = array(
    'body' => $body,
    'subject' => $subject,
    'headers' => array(
        'Bcc' => $header_bcc,
        'Cc' => $header_cc
    )
);

$email = drupal_mail('ModuleName', 'message_key', $to, LANGUAGE_NONE, $params, $from, true);

```

Using hook\_mail() you need to add (thank you @clive):

```
/**
 * Implements hook_mail().
 */
function ModuleName_mail($key, &$message, $params) {
    switch ($key) {
        case 'message_key':
            $message['headers'] += $params['headers'];
    }
}

```

# Answer
> 3 votes
You can use the hook mail alter for changing or adding altered to, cc and bcc mail ids, see the example:

```

/**
 * Implements hook_mail_alter().
 */
function hook_mail_alter(&$message) {
  $message['to'] = 'mail@gmail.com';
  $message['headers']['Bcc'] = 'Your mail ids goes here with comma seperation';
  $message['headers']['Cc'] = 'Your mail ids goes here with comma seperation';
}

```

Also you can use bcc and cc mail ids in the $params array of drupal\_mail():

```

$params = array(
  'body' => $body,
  'subject' => 'Your Subject',
  'headers' => array(
    'Cc' => 'Your mail ids goes here with comma seperation',
    'Bcc' => 'Your mail ids goes here with comma seperation',
  ),
);

```

# Answer
> 2 votes
There's a module for that: If you want to get a bcc of all mails that drupal sends check out the BCC Module.

# Answer
> 2 votes
You can do this:

```
$message['headers']['Bcc'] = 'email@address.com';

```

# Answer
> 1 votes
In `hook_mail_alter()` use `$message['params']['headers']['Bcc'] = 'yourmail@gmail.com';`.

---
Tags: emails
---


# Question
Title: Best practice for caching CSS libraries?
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme it says:

> Some libraries you load may not be needed on all pages. For faster performance don't load libraries where they are not being used.

At the same time, if you have many different files to load for each page, this will slow down the speed for each page load.

How big should the library be before you should consider to load it in a separate library?

How does the database caching system work? Will each library be cached in a separate CSS file? If I have page X and Y where i only need some CSS library on page Y, will both of them share CSS file A and then the other also have CSS file B? Or will these pages have only 2 different CSS files?

# Answer
> 0 votes
> At the same time if you have many different files to load for each page this will slow down the speed for each page load.

You don't need to worry about this in Drupal, as Drupal will aggregate the CSS files when you have CSS aggregation turned on, and you should always have this enabled on a production site.

As such, you should ensure that only the relevant CSS is attached to an element/page to which it belongs.

For example, I'm creating a site right now that has a booking page. This page has a chart-like schedule on it, showing what time slots are available. It's not unthinkable that this could be swapped out at some time in the future. So I have all the CSS for that chart in a single file, and the chart is attached to that element of the render array. Therefore if anyone ever removes that element, or sets the access on it to FALSE, the CSS will not load.

Drupal will handle the aggregation in the background and serve an aggregated file that contains my file when the user is served the schedule, and serve an aggregated file that does not contain my file, when the user is not served the schedule.

So to sum it up, don't worry about having too many CSS files in Drupal. On the contrary, it's better to have your CSS modular, so that each file contains CSS to a specific element/page, and attach that file to that element/page. Drupal will handle the rest.

> And how does the D8 caching system work; will each library be cached in a separate css file? If I have page X and Y where i only need some css library on page Y, will both of them share CSS file A and then the other also have CSS file B? Or will these pages have only 2 different CSS files?

Aggregates are created as needed. If a page needs file X, Y and Z, it will create an aggregate that contains those files. If another page only needs X and Y, it will create an aggregate with those files. If that same page is visited by a loggeed in user that needs file A, then an aggregate will be created with those files.

# Answer
> 0 votes
Size is not the correct factor. purpose is the correct factor.

Is there code in your library that could be reused by another library? If the advert is yes then you should separate it to another library.

For example, for some custom form in writing, I require that the values of some field will be copied to a second (disabled) field. If I put the JavaScript as part of the base library of my form, then I'll have to write the same code again for another form. However if I'll create a separate library for this behavior then I could reuse across my project.

Personal tip: when writing a name for a library ask what is the purpose of the library, add don't show generic names like *base* or *form\_behaviors*.

---
Tags: theming, 8, caching
---


# Question
Title: How to create sub menu in Drupal 8 using views result for specific item of the menu?
I have one menu link available in the **Main Menu**. It is called as **"Video"**.

In my system, there is vocabulary called as **"Video Taxonomies"**. It have following taxonomies entries.

1. Entertainment
2. Comedy
3. Friction

I have created one block for listing all this category.

Now, I want this block result would appear under "Video" link of the **Main Menu**.

So, I want following output when we will hover on the Video Link of the Main menu.

* Video Link

+ Entertainment
    + Comedy
    + Friction

I have used https://www.drupal.org/project/menu\_views for Drupal 7.

Please suggest.

# Answer
We have implemented using the

```
MODULE_NAME_menu_links_discovered_alter(&$links).

```

In which, We have accessed the result of the block by using the following code.

```
 $result = views_get_view_result("view_name", "display_id");
    foreach($result as $result) {
      $title = "Entertainment"; // we have took as static
      $tid = 10;
      $slug = str_replace(' ', '_', strtolower($title));
      $links[$slug] = array(
        'title' => $title,
        'route_name' => 'view.VIEW_NAME.DISPLAY_ID'
        'route_parameters' => array('arg_0' => $tid),
        'description' => 'Dynamic',
        'provider' => 'MODULE_NAME',
        'parent' => 'menu_link_content:DATABASE_UUID_OF_SELECTED_CATEGORY',
        'id' => $slug
      );
    }

```

We have used **route\_name** for assigning the url, this url should be the existing url of the drupal site.

We need **route\_parameters** for passing the arguments.

For accessing the **Video Link : reference** in **parent** of **$links**. I have got it from the

```
SELECT uuid as DATABASE_UUID_OF_SELECTED_CATEGORY FROM `menu_link_content` where id = "TID_Video_Link_of_Main_menu"

```

After that, We have used that id in **parent** as **'menu\_link\_content:04c479c9-7234-4de2-a4f0-e03b0a3003b6'** so all links will be added below the Video Link of the main menu.

After doing all the code and we need to clear the cache. And we are able to see the sub menu from the views of texonomy to Video Link of the main menu.

Please suggest me if there is any better way than this.

**For Reference:** https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Menu!menu.api.php/function/hook\_menu\_links\_discovered\_alter/8.2.x
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to exclude a cache table from memcache?
I have created a one custom table for storing the data, based on cache rules i have created a table.

Installed and enabled Memcache module in site.

Configured memcache in settings.php

```
  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;
  $conf['cache_thrive_tips'] = 'DrupalDatabaseCache';
  $conf['memcache_servers'] = array('localhost:11212' => 'default');

```

When i configure memcache in my site, at that time onwards my custom table(**cache\_abc**) not storing any values.

How can i exclude only this table from memcache?

# Answer
> 6 votes
You do it in the same way the code you are showing does for cache\_form.

```
$conf['cache_class_cache_abc'] = 'DrupalDatabaseCache';

```

Adding that line in the settings.php file, you are telling Drupal to save the cache for cache\_abc in the database.

Keep in mind that, in Drupal cache terminology, cache\_abc (which would be the name of the database table containing the cache data, when the cache is saved in the database) is called *bin*.

---
Tags: 7, caching
---


# Question
Title: Use migrate to populate entity_reference with nid
I am migrating a D6 site to D8. The D6 site used the "Node Relativity" module, which has been broken for a while. It was used to establish a link between two content types, which I will call `meeting` and `recording`.

Now I am trying to use the `migrate` module (and friends like `migrate_plus`) to establish an entity reference to `recording` in the `meeting` content type. Here is what I have done:

* In the D8 site, specified the field structure for the two content types. In the `meeting` content type there is an entity reference for the `recording` called `field_recording_link`.
* Exported the configuration into custom modules. I can now create a database from scratch and it creates the content types.
* Connected my D6 database to import content. Textfields from the `meeting` content type do get imported.
* Written a custom source module with a `prepareRow()` method that exposes the NID of the `recording` nodes (called `recording_nid`). I can see this NID in the migration.

In the `migrate_plus.migration.upgrade_d6_node_meeting.yml` file, added the following stanza in the `process` section:

```
field_recording_link: recording_nid

```

but this does not populate the field. I have also tried:

```
'field_recording_link/target_id': recording_nid

```

but that does not work either. I feel as if this ought to be straightforward, but I am pretty stuck.

* Do I need to make a process plugin? If so what should it do? Use PHP to create an entity reference and populate it?
* Do I need to call an existing process plugin? If so which one?
* Do I have to write a separate `.yml` file just for this field? If so what would it look like? I have been looking around for examples but have not had much luck.

I would appreciate any advice you have, as well as links to examples of this.

# Answer
It was straightforward. I had a typo in my YML file. The correct answer was:

```
field_recording_link/target_id: recording_nid

```

The important thing is to set the `target_id` field, since that is what the entity reference really is.
> 4 votes

---
Tags: 8, entities, migrations
---


# Question
Title: How to debug users geting automatically logged out for unknown reasons?
For our Drupal 6 site, we've experienced such issue that logged-in users are getting logged out for around one week or several days.

Firstly I thought this might happen with Boost module, but it seems this issue happens as our test site that runs without boost enabled. We have already set cookie time long as following in settings.php

```
ini_set('session.cookie_lifetime',  2147483647);
ini_set('session.gc_maxlifetime',   200000);

```

This site is pretty big and includes a lot of custom modules/code, which make it difficult to debug what's going on. I greb the code, and no luck to find session\_destroy code, or user logout code. Maybe I need to set session.gc\_maxlifetime as large as session.cookie\_lifetime?

Is there some way to debug this issue when users are logged out?

# Answer
This issue is solved by updating this setting

ini\_set('session.cookie\_lifetime', 21474836); The original value '2147483647' is too big for some reason.
> 0 votes

---
Tags: 6, caching, users
---


# Question
Title: What's the difference between private message & message?
In my user backend I have a tab named 'messages' (mysite.com/user/uid/messages) and a second named 'Private messages & invitation' (mysite.com/user/uid/contacts).

For what I see private messages is where users can message each others when there are trusted contact.

Now I want to know the use of 'Messages'. Also I've seen that there is two modules message & Privatemsg.

# Answer
I installed Drupal Commons once out of curiosity, but it was a long time ago and my memory is fuzzy. I know both of those modules, so this is just an educated guess on how Commons is using them:

Private message is for messaging other users on the site. While Messages is used for notifications/alerts that tells you someone posted here or there, or someone liked your comment etc...
> 0 votes

# Answer
By using the Message module, you can create your own custom "*Events logging*" (to register things that happened in a site).

A great sample of this you can find in Commerce Kickstart, which uses the Commerce Message module, to create such "*Events logging*". In this case in the format of an Order History, as shown in this screenprint (from this module's project page).

The Message module is an amazing module, though there is not a lot of documentation about it. It is fully entity based, which implies that it perfectly (out of the box) integrates with modules such as Views and Rules. And to give you an idea of the kind of things you can use it for, have a look at the answers to:
> 1 votes

---
Tags: 7
---


# Question
Title: How can I embed the content of a field into the content of another field?
If I have a news site where I can select a source e.g. a press agency (given by a Taxonomy field) when creating a new article, how can I put this source at the beginning of the article text when viewing it? Like this:

(SOURCE) Beginning of article blabla............................

I already found a solution by using three different custom templates for getting rid of all the html wrappers and then floating the article text around (SOURCE), but there must a better solution like manipulating the node array or sth?

# Answer
You can combine two fields in `hook_ENTITY_TYPE_view()`

```
function mymodule_node_view(&$build, $entity, $display, $view_mode) {

  if (isset($build['field_source'][0]['#markup']) && isset($build['body']['0']['#text'])) {

    $build['body']['0']['#text'] =
      '<strong>(' . $build['field_source'][0]['#markup'] . ')</strong> ' .
      $build['body']['0']['#text'];

    unset($build['field_source']);

  }
}

```

and unset the added field to avoid double content.

You can also add html tags if they are allowed in the text format.

This is an example. You have to look into the build array after you've configured the display mode in ui and adjust the array keys.
> 2 votes

# Answer
I think you have done it the correct way...

You could also use a preprocess function to add the 'float:right' style when your field is displayed:

```
function your_module_preprocess_field(&$vars) {
   $element = $vars['element'];
   $fn = $element['#field_name'];
   switch ($fn) {
      case 'field_your_source_field':
         $vars['attributes']['style'][]='float:left';
      break;
   }
}

```

This is maybe more clean to add a class the same way:

```
 $vars['attributes']['class'][] = 'your--float-left-class';

```
> 1 votes

---
Tags: theming, 8, entities
---


# Question
Title: Per entity settings storage (configuration / state / field)
Background : #2833770 : Save user configs to states

Auto-logout saves the *per-user* settings using configuration API, which would obviously break with environment change and config deployment.

The suggested patch moves the storage from the config API to state API. My take on this and from the documentation of State API:

1. State API is a better alternative which will avoid the deployment issues, but isn't perfect as the state can anytime be reset.
2. The *per-content* configuration would get lost once that happens.

How often can a state API be reset? I would prefer some examples other than docs.

As an alternative, I think it would be safe to save the settings in a field on the user entity, but I would like to go this route only if state API is not a good option. I would really appreciate any input on the same.

# Answer
Core provides a storage/API to store per-user information: the user.data service. It also provides a very simple example implementation in the Contact module: See `contact_form_user_form_alter()` and `contact_user_profile_form_submit()`.

```
\Drupal::service('user.data')->set('contact', $account->id(), 'enabled', (int) $form_state->getValue('contact'));
$account_data = \Drupal::service('user.data')->get('contact', $account->id(), 'enabled');

```
> 3 votes

---
Tags: 8, configuration
---


# Question
Title: How to use service renderer with context theme?
I have snippet code:

```
//Load block view (have override template)
$block = Block::load('views_block_1480647185');

// get render array
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

// get markup string
$markup = \Drupal::service('renderer')
  ->render($render);

kint($markup);

```

when i visit different **url admin** (example.com/admin/content), **non-admin** (example.com). Value markup is different.

**In example.com/admin/content**

**In example.com (use override template view)**

I think because url use different theme (bartik and seven).

So how can set **markup value** same value in url **non-admin**? How can do that with drupal service renderer?

# Answer
> 2 votes
Use the `theme.manager` service to set the active theme to what you desire, render the block and set the original active theme back.

```
/** @var \Drupal\Core\Theme\ThemeInitialization $theme_initialization */
$theme_initialization = \Drupal::service('theme.initialization');
$active_theme = \Drupal::theme()->getActiveTheme();
\Drupal::theme()->setActiveTheme($theme_initialization->getActiveThemeByName($theme));
// Render your block...
\Drupal::theme()->setActiveTheme($active_theme);

```

---
Tags: theming, 8
---


# Question
Title: How do I create a site inside another one?
I have a Drupal site (example.com). There is some content, and there is a page at `example.com/projects/abc`.

What I want to do is create another site on `example.com/projects/abc/NEWSITE`.

**How can I do that?**

Normally, I can create folders via FTP such as projects-\>abc-\>NEWSITE, but there is content on example.com/projects example.com/projects/abc.

# Answer
It's possible, but usually not really recommended solution - as we have subdomains/multisites in Drupal.

But basicly only thing that will probably need small adjustments is .htaccess, make sure to edit RewriteBase variable. Check out these links:

Same/Similar topics here:

How to get Drupal 7 installed in a sub-folder / sub-directory properly?

https://stackoverflow.com/questions/4122488/a-drupal-site-inside-another-drupal-subdirectory

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

Configuring .htaccess to ignore specific subfolders: https://www.drupal.org/node/30334

https://stackoverflow.com/questions/2718406/how-to-exclude-a-folder-on-drupal-site-so-that-drupal-does-not-recognise-it-its

Also if You decide to go for multisite -\> read this one: https://www.drupal.org/docs/7/multisite-drupal/multi-site-in-subdirectories

Hope this will help You :) Good luck!
> 2 votes

---
Tags: 7, multi-sites
---


# Question
Title: How to use access callback and access arguments to restrict access by role?
I'm creating website for a hostel, in this there are two roles (guest and property owner).

if i give `'access callback' => TRUE` the page can be accessed by both of the property owner and guest, but i don't need it, the page should be accessed by only property owners.

# Answer
> 5 votes
The callback is, well the callback; the function that will be run to determine access for the path.

The arguments are the arguments provided to that function for context. They can be static, or come from parts of the URL (not query params).

What you need to do is instead of `TRUE`, provide the name of a function which determines whether the current user is a "property owner", and return TRUE or FALSE from that function to allow/deny access respectively.

The common way to achieve that for role-based access is to use `hook_permission` to provide your own permission to the system, call it "access top secret area" or whatever, grant the new permission to the property owner role through the UI, and change the access arguments to an array containing that new role.

The default access callback is `user_access`, so it will have the effect of running

```
$access = user_access('access top secret data');

```

Obviously if you need more advanced logic, e.g. to determine that a property owner is accessing only data on a property they actually own, a custom callback will make more sense.

---
Tags: 7
---


title: Change view title programmatically

text:
# Question
Title: Change view title programmatically
I couldnt find an answer to this question in Drupal 8.

I've created a simple custom module:

**mymodule.info.yml**

```
name: 'mymodule_name'
description: 'basic module for custom implementations'
package: 'custom'
type: module
version: '8.x-1.0'
core: '8.x'

```

**mymodule.module**

```
function mymodule_views_post_execute(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');

}
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');
}

```

I tried this hook implementations separately, not at smae time. Both changes the view title, but my custom theme doesnt work.

I also tried in my custom theme the following code:

```
function mytheme_preprocess_views_view(&$variables) {
    $view = $variables['view'];
    $view->build_info["title"] = "Foo";
}

```

It prints "Foo" inside view content, it doesnt override view title.

Any idea?

# Answer
> 2 votes
You probably want to change the global title used for the title block. This is retrieved from the route. The route for a view is built from the view configuration when you save a view (or clear the cache). The title in the route is static. If you want to change it, modify it in the view configuration. You can do this in ui or in code.

If you want to make this dynamically, you can replace the static `_title` in the view route with a title controller `_title_callback` to provide a different title on every request.

---
Tags: views, 8
---


# Question
Title: Twig/variable support in Custom block HTML
I'm trying to understand if/how you insert Twig variables in blocks in the custom block library.

To clarify, the block's HTML has been configured via the UI at `/admin/structure/block/block-content`

Standard Twig syntax, e.g. a 'say-something' tag like `{{ base_path ~ directory }}` \- which I want so I can set an `<img src` attibute correctly - doesn't seem to be parsed at all and I don't see a way to use Tokens.

Examining the HTML source with Twig debugging on, it's theme hook is listed as "field", so if I add a preprocess function:

```
function themename_preprocess_field(array &$variables, $hook) {
  xdebug_break():
}

```
* that's being called rather too often
* when it does reach the custom block, there doesn't seem to be anything in $variables that labels it as such, other than a render array with the processed text:

`$variables['items'][0]['content]['#text']`

What's the simplest approach for this? Is the only way to do it to write a module?

Thanks, William

# Answer
You can't use twig variables in the body field of a block (or a node). But you can use tokens. Install the modules Token and Token Filter. You need to add the token filter to the text format you are using in the body field.
> 1 votes

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


# Question
Title: One filter criteria for two different displays of the same view?
Hi there drupal wizards.

I want to be able to filter two different view displays and display the search results of a filter query simultaneously on the same page with only one shared filter criteria search that works on both views.

I have no problem to do the filter criteria for each one, but I want one common filter search criteria that filters both views and displays them one after the other on the same page.

How do I do this?

If possible I don't want to hack code, just configure things.

To be more precise: I have one map search working based on location data. The filter is exposed as a block. However I've created a block display showing the same view as a table list that the filter block query does not seem to affect at all. I'm using context to display the second view display block In the same path.

# Answer
> 3 votes
Seems like you want to display two different views with a common shared exposed filter in the same page (or as you said "same path"), instead of making two displays of the same view:

1. After created your view and your primary "view block", add the needed filter to that block, make sure that the filter is valid for all pages.
2. Then create an Attachment (you can find it in view configuration page Add\>Attachment), and attach its to the block in Attachment settings by chosing "Attach to:Block" and set a preferred display position of that attachment (Attachment position)
3. Configure your Attachment with your needed format and fields, making sure that these configurations are for "this Attachment only"(\*override)
4. Finally Set to Yes the "Inherit exposed filters:" in Attachment settings
5. Et voilà enjoy your block+attachment with the same shared filter!

If you want to share the same filter in more than one views globally in the entire site, you can take a look to modules like Views Global Filter

# Answer
> 2 votes
This might work :) If you have two views, which both have the same field exposed as a filter, you could set the Filter identifier to the same value. Go to the filter on both views and under More you will find "Filter identifier", set it to the same value.

---
Tags: views
---


# Question
Title: How to link fields from a Content Type to an Entityform field
Using Drupal 7. Our Recruiting department will be creating events & at these events want to be able to hand a tablet off to an individual so that they can enter info about themselves:

* Name
* Address
* Email, etc...

After content is submitted the Recruiter then can go in & enter "Notes" about the individual.

I'm using Entityforms for that part.

I've also created a content type for Events.

Data would be Event Type (Career Night, College Fair, etc) Location (Rutgers University, etc) Date of Event, Recruiter (Last name) & after the event enter Number of Attendees.

I'm trying to figure out how to relate an applicant to the event that they attended. I'm not having any luck with Entity References.

I'm thinking the related items would be Event Date, Location, Recruiter. I can't figure this out. Any help would be appreciated.

# Answer
> 0 votes
Thinking of this leads me to the following conclusion. You want to hand over the tablet, meaning it should not be logged in as an administrator or by any other means allow people to see and edit more then then allowed.

So you could do this with simple comments.

Create a content type of event in which you have fields for the date, the name of the event, the location and the recruiter (author?).

Then edit the content type and navigate to this tab:

Here you can add comment fields, including the name and any other information you want from the person. Give anonymous users permission to create comments, but not view them and you are done. Later if you log in, an admin can edit the comment and add notes.

Another solution would be the webform module. More or less allowing you to create any type of form on any type of node. It comes with a wide variety of fields and a clear admin interface, also allowing exports etc. Adding notes can be achieved by editing the submission as well.

UPDATE:

I always thought entity forms were for backend forms. You can attach one to a node folloing this tutorial: http://www.sixmiletech.com/content/embedding-entiyform-node

That should solve your entity reference stuggles.

Summary of the video would be to create an entity reference field on the event-node. Configure it to reference to `Entity form type(s)`. On the manage display tab of the content type configure the entity reference to 'Render the entity\`.

Now create a node, select the right entity form type and save. You now have a node with an attached form.

# Answer
> 0 votes
I was not able to resolve this with Entity Forms. I did find exactly what I was looking for: Drupal 7 Node Reference Tutorial

I had to create a content type for a "Registrant" & using Node Reference URL was able to tie a registrant to an event. This video explains it perfectly.

---
Tags: entities
---


# Question
Title: How to know how many elements are processed in the finish callback?
I followed Smack My Batch Up : Batch Processing In Drupal 8 article to create a batch job and all works fine. But in the finish callback I can't get the total number of processed elements.

This is my code:

```
$operations = [];
foreach ($lines as $line) {
/*
Here I have an array of operations and each element have the name of
the operation callback function and the line that should be processed.
Maybe this is the problem.
*/
  $operations[] = ['process_line_saint_du_jour', [$line]];
}

$batch = array(
  'title' => t('Migrating Saint of the Day'),
  'operations' => $operations,
  'finished' => 'process_line_saint_du_jour_batch_finished',
  'init_message' => t('Saint of the Day migration is starting.'),
  'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
  'error_message' => t('The migration process has encountered an error.'),
  'file' => drupal_get_path('module', 'diocese_migrate') . '/diocese_migrate.batch.inc',
);

batch_set($batch);

```

This is my finish callback function:

```
function process_line_saint_du_jour_batch_finished($success, $results, $operations) {
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      count($results),
      'One Saint of the Day processed.', '@count Saint of the Day processed.'
    );
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

```

The problem here is that I have only one element in the `$results` array and I have processed 366 elements, all works fine but at the end of the batch I have the following message:

> One Saint of the Day processed.

# Answer
Reading the Batch Process in Drupal 8 and Drupal 8 Batch Example articles I found the answer.

The key is in the

```
//Message to show during each execution of the callback function
$context['message']
//Array with the total of processed items.
$context['results']

```

So, the solution is in the operations callback function, now the functions is like this and it works:

```
function process_line_saint_du_jour($line, &$context) {
  //Custom Code
  $info = str_getcsv($line, ";", '"');
  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}

```
> 3 votes

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


# Question
Title: Validate a custom type node before submitting
I'm to validate the creation of a new content node, of a custom content type. It seems I cannot find the right hook.

I tried using hook\_node\_presave, however, the only way to stop node from creating is to throw an exception. This is rather user unfriendly.

```
 function custom_module_node_presave($node) {

    if($node->getType()=='custom_content_type'){
            if(some_business_rules_apply()){
                    drupal_set_message('You cannot add a new node.','error');
                    # cancel saving
                    throw new \Exception(t('You cannot add a new node.'));
            }else{
                    # do something more
            }
    }
}

```

I tried to use hook\_node\_validate but it seems like it is not called. Do I miss something? Maybe, I use the wrong name for the hook function? Is there some kind of example for hook\_node\_validate?

```
function custom_type_node_validate(\Drupal\Core\Entity\EntityInterface $node, $form, &$form_state){
    \Drupal::logger('My logger')->info('Node validate');
}

```

# Answer
> 13 votes
In Drupal 8 the hook `hook_node_validate()` has been removed. Here are some suggestions.

**Reference:** hook\_node\_validate() and hook\_node\_submit() have been removed.

## Field constraints

If you're trying to validate an individual field, use a constraint.

```
/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function custom_general_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter node.page.field_service.
  if ($entity_type->id() === 'node' && $bundle === 'page') {
      $fields['field_service']->addConstraint('CustomAssignableService', []);
  }

```

## Entity constraints

For general constraints on the entire entity or constraints which are not specific to a single field.

```
/**
 * Implements hook_entity_type_alter().
 */
function custom_general_entity_type_alter(array &$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('CustomAuthorizedTerritory');
  }
}

```

## Form validation

The "constraints" will always validate the field / entity no matter the form / method with which you use save the entity.

Additionally, you can provide form validation using a `hook_node_form_alter()` to improve the UX with nice error messages.

**Note:** These are "form-level" validations and are only applied when the node is created / updated from a said form. Users might be able to bypass these restrictions while saving the node using web services or other forms (if any).

```
// In the mymodule.module file.

/**
 * Implements hook_form_FORM_ID_form_alter().
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'mymodule_node_form_validate';
}

function mymodule_node_form_validate($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->getType() == 'custom_content_type') {
    if ($form_state->getValue('some_property') !== '123') {
      $form_state->setErrorByName('some_property', t('Property must be 123.'));
    }
  }
}

```

---
Tags: 8, hooks
---


title: exposed sort not defaulting to "any"

text:
# Question
Title: exposed sort not defaulting to "any"
I have an exposed sort on my view by "has taxonomy term with depth". I want it to default to "Any " but it keeps on defaulting to one of the choices. Is there a way to make it default to Any? I dont see the option for the default choice. thanks.

# Answer
1. Did You checked if the exposed sort is not "required"? (there should be a checkbox that it's not mandatory field)
2. Did you checked if the "remember last chosen option" is unchecked?

3. Did You highlighted any possible option in configuration of this sorting?

**EDIT:**

I'm talking about this options list in 3. It should not be highlighted to default to ANY

**EDIT 2**
> 1 votes

---
Tags: 7
---


# Question
Title: How to supply hidden field value to node based on webform?
Using D8 to create a node based on a Webform named "White Paper". I have a hidden field on the webform named white\_paper\_title.

When creating a node based on this form, I've added the following in the *Default webform submission data* field, like so:

```
white_paper_title: 'something'

```

This works fine if I base the new node on Webform, and select "White Paper" from the list.

The problem is that it never works when I create a new content type based on the White Paper webform. When viewing the node in the browser, the hidden field is there, but the value is never plugged in. How do I get this working?

# Answer
> 5 votes
You can pass a field's value as a token to the webform.

You would need to add 'field\_white\_paper\_title' to your webform node and then change the "Default webform submission data (YAML)" to

```
white_paper_title: [webform_submission:node:field_white_paper_title]

```

---
Tags: 8, webforms
---


title: Can I add php code on title of a link?

text:
# Question
Title: Can I add php code on title of a link?
I have this problem: I created three content types. Actor, author and musician. An user can modify own actor, author and musician profile, if his role is one of these.

A user can have more than one role, so, he can be actor, author and musician. An actor can be a man or a woman, so his role canbe actor or actres. In user menu I must have links on pages for these roles, so, an actor can have `actor/[user:name]` and an author can be `author/[user:name]`. Title of these links should be `[user-name]` actor or actres depending on the role.

Ok, I can use user-name token, but how can I retrieve the role? Can I use php code on title of link?

# Answer
Since you did not specify a version I am assuming Drupal 8, but the hooks are nearly the same for Drupal 7. (You can navigate to them from the linked documentation pages).

The problem is that a user can have multiple roles and they can be assigned in a random order. This way you can never be sure that the correct role is shown.

You could try to provide Drupal with some custom tokens for these roles. This means you'll have to create a small custom module, but that is really not that hard.

Then you'll have to implement 2 hooks in your .module file:

`hook_token_info_alter()`. This allows for the tokens to show up in the token browser.

`hook_tokens_alter()`. The code could look something like this:

```
function <modulename>_token_info_alter(&$data) {
  // Add description of user tokens.
  $data['tokens']['user']['actor-role'] = array(
    'name' => t("Actor role"),
    'description' => t("Role if the user is an actor."),
  );
  $data['tokens']['user']['author-role'] = array(
    'name' => t("Author role"),
    'description' => t("Role if the user is an actor"),
  );

  // Add as much as you like (need).

}

function <modulename>_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $options = $context['options'];

  if ($context['type'] == 'user' && !empty($context['data']['user'])) {
    $user = $context['data']['user'];

    if (isset($context['tokens']['actor-role'])) {
      // PHP logic to determine the role. Below is an assumption and might not work.
      // Set the value to the actor-role token to 'Actor' or nothing.
      $actor-role = $user->hasRole('actor_role_id') ? t('Actor') : '';
      $actress-role = $user->hasRole('actress_role_id') ? t('Actress') : '';

      // Combine them (one should be empty leaving the other)
      $actor-role-to-show = $actor-role . $actress-role

      $title = $node->field_title->view('default');
      $replacements[$context['tokens']['actor-role']] = $actor-role-to-show;
    }

    // Again add as many as you like.
  }
}

```

Now you should be able to use `[user:author-role]` and any other tokens you have defined.
> 0 votes

---
Tags: 7, users, navigation, tokens
---


# Question
Title: how to filter by YEAR of a date (not the published date) in a view
I can add a contextual filter for the YEAR of the published or created date, but not for another date . How can I create an exposed filter by this other date?

# Answer
If I am not mistaken this has to do with the granularity setting of the filter. At the moment you add the filter in Views you can set the granularity (if it already exists you can change it by clicking the filter or clicking the settings link behind it).

## Contextual

Make sure to select `Date: Date (node)` as the contextual filter type. Also make sure this is set to `year` to make the filter work per year only and select the field you want to filter on.

this allowed me to use /2015 in my url to filter nodes with a date field with a 2015 value.

## Exposed

If the problem is with exposed filters, just select the date field, and set the granularity to year:
> 3 votes

---
Tags: 7, views
---


# Question
Title: How to use full_html format for custom field?
How can I use a the full\_html format for my custom field in my custom node type? I'd prefer a solution that didn't use any third-party modules.

I've essentially followed this guide, but my custom fields have their HTML tags escaped when rendered.

I've been searching for hours, and can't seem to quite come up with a solution.

I've added 'format' =\> 'full\_html' like in this answer: Specifying text format when creating field on custom node type, but it didn't do anything.

After my changes I used the Devel module to uninstall and reinstall my module.

Edit: added code.

**biolawnorganics\_content\_types.install:**

```
<?php

require_once 'include/nodetypes.inc';

function _biolawnorganics_add_missing_fields() {
  node_types_rebuild();

  $nodeTypes = node_type_get_types();
  $fieldInfoMap = field_info_field_map();

  $fieldsArr = _biolawnorganics_build_all_fields();
  $fieldsInstancesArr = $fieldsArr['instance'];
  $fieldsTypesArr = $fieldsArr['type'];

  foreach ($fieldsTypesArr as $ft) {
    $fieldName = $ft['field_name'];

    if (!isset($fieldInfoMap[$fieldName]))
      field_create_field($ft);
  }

  $contentTypesArr = _biolawnorganics_build_all_content_types($fieldsInstancesArr);
  $contentInfosArr = $contentTypesArr['info'];
  $contentFieldsArr = $contentTypesArr['fields'];

  foreach ($contentFieldsArr as $ck => $cfs) {
    if (!isset($nodeTypes[$ck])) {
      error_log("WARNING: Content type mismatch on $ck.");
      continue;
    }

    $bodyFieldInstance = field_info_instance('node', 'field_body', $ck);

    if (is_null($bodyFieldInstance))
      node_add_body_field($nodeTypes[$ck]);

    foreach ($cfs as $cf) {
      $fieldInstance = field_info_instance('node', $cf['field_name'], $ck);

      if (is_null($fieldInstance))
        field_create_instance($cf);
    }
  }
}

function biolawnorganics_content_types_install() {
  _biolawnorganics_add_missing_fields();

  drupal_set_installed_schema_version('biolawnorganics_content_types', 7001);
}

function biolawnorganics_content_types_update_7001(&$sandbox) {
  biolawnorganics_content_types_install();
}

function biolawnorganics_content_types_uninstall() {
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';

  foreach (array_keys(_BIOLAWNORGANICS_CONTENT_TYPES) as $t) {
    $result = db_query($sql, array(':type' => $t));

    $nodeIds = array();

    foreach ($result as $r)
      array_push($nodeIds, $r->nid);

    node_delete_multiple($nodeIds);
    node_type_delete($t);
  }

  foreach (array_keys(_BIOLAWNORGANICS_FIELDS) as $f) {
    $fieldInstances = field_info_instances('node', $f);

    foreach ($fieldInstances as $fi)
      field_delete_instance($fi);

    field_delete_field($f);
  }
}

// vim: set ts=2 sw=2 et syn=php:

```

**include/nodetypes.inc:**

```
<?php

define(
  '_BIOLAWNORGANICS_FIELDS', array(
    'biolawnorganics_promos'  => array(
      'type' => array(
        'label'  => 'Promotions Sidebar',
        'type'   => 'text_long',
        'format' => 'full_html'
      ),
      'instance'  => array(
        'widget'  => array(
          'type'   => 'text_textarea',
          'format' => 'full_html'
        )
      )
    )
  )
);
define(
  '_BIOLAWNORGANICS_CONTENT_TYPES', array(
    'biolawnorganics_home'  => array(
      'info'    => array(
        'name'        => 'bioLawn Organics Home',
        'description' => 'bioLawn Organics Home Page',
        'has_title'   => FALSE
      ),
      'fields'  => array(
        'biolawnorganics_promos'  => NULL
      )
    ),
    'biolawnorganics_page'  => array(
      'info'    => array(
        'name'        => 'bioLawn Organics Page',
        'description' => 'bioLawn Organics Generic Page',
        'has_title'   => TRUE,
        'title_label' => 'Title'
      ),
      'fields'  => array(
        'biolawnorganics_promos'  => NULL
      )
    )
  )
);

function _biolawnorganics_build_field_type($fieldName, $fieldTypePartial) {
  $fieldType = $fieldTypePartial;

  $t = get_t();

  $fieldType['field_name']  = $fieldName;
  $fieldType['label']       = $t($fieldType['label']);

  return $fieldType;
}

function _biolawnorganics_build_field_instance($fieldType, $fieldInstancePartial) {
  $fieldInstance = $fieldInstancePartial;

  $fieldName = $fieldType['field_name'];

  #$t = get_t();

  $fieldInstance['field_name']  = $fieldName;
  $fieldInstance['label']       = $fieldType['label'];
  $fieldInstance['type']        = $fieldType['type'];
  $fieldInstance['entity_type'] = 'node';

  $fieldInstance['display'] = array(
    'example_node_list' => array(
      'label' => $fieldType['label'],
      'type'  => $fieldType['type']
    )
  );

  return $fieldInstance;
}

function _biolawnorganics_build_content_info($contentName, $contentInfoPartial) {
  $contentInfo    = $contentInfoPartial;

  $t = get_t();

  $contentInfo['base']          = $contentName;
  $contentInfo['name']          = $t($contentInfo['name']);
  $contentInfo['description']   = $t($contentInfo['description']);
  if ($contentInfo['has_title'])
    $contentInfo['title_label'] = $t($contentInfo['title_label']);

  return $contentInfo;
}

function _biolawnorganics_build_content_fields(
    $contentName,
    $contentFieldsPartial,
    $fieldInstancesArr) {
  $contentFields = $contentFieldsPartial;

  foreach (array_keys($contentFields) as $fn) {
    $fieldInstance = $fieldInstancesArr[$fn];

    if (is_null($fieldInstance)) {
      error_log("WARNING: Missing field instance for $fn.");
      continue;
    }

    $fieldInstance = (array)clone (object)$fieldInstance;

    $fieldInstance['bundle'] = $contentName;

    $contentFields[$fn] = $fieldInstance;
  }

  return $contentFields;
}

function _biolawnorganics_build_all_fields() {
  $fieldTypesArr = array();
  $fieldInstancesArr = array();

  foreach (_BIOLAWNORGANICS_FIELDS as $fk => $fv) {
    $ft = _biolawnorganics_build_field_type($fk, $fv['type']);
    $fi = _biolawnorganics_build_field_instance($ft, $fv['instance']);

    $fieldTypesArr[$fk] = $ft;
    $fieldInstancesArr[$fk] = $fi;
  }

  $fieldsArr = array(
    'type' => $fieldTypesArr,
    'instance' => $fieldInstancesArr
  );

  return $fieldsArr;
}

function _biolawnorganics_build_all_content_types($fieldInstancesArr) {
  $contentInfosArr = array();
  $contentFieldsArr = array();

  foreach (_BIOLAWNORGANICS_CONTENT_TYPES as $ck => $cv) {
    $ci = _biolawnorganics_build_content_info($ck, $cv['info']);
    $cf = _biolawnorganics_build_content_fields($ck, $cv['fields'], $fieldInstancesArr);

    $contentInfosArr[$ck] = $ci;
    $contentFieldsArr[$ck] = $cf;
  }

  $contentTypesArr = array(
    'info' => $contentInfosArr,
    'fields' => $contentFieldsArr
  );

  return $contentTypesArr;
}

// vim: set ts=2 sw=2 et syn=php:

```

# Answer
> 1 votes
Thank you for your help @AdrianCidAlmaguer, I was just missing `'settings' => array('text_processing' => 1)`, all `'format' => 'my_format'` does is set the default text\_processing mode, and has no apparent effect without `'settings' => array('text_processing' => 1)`. I used this diff and it just worked (I knew it had to be something simple.):

```
diff --git a/include/nodetypes.inc b/include/nodetypes.inc
index 02d18e5..ad6b2a3 100644
--- a/include/nodetypes.inc
+++ b/include/nodetypes.inc
@@ -4,8 +4,12 @@ define(
   '_BIOLAWNORGANICS_FIELDS', array(
     'biolawnorganics_promos'  => array(
       'type' => array(
-        'label' => 'Promotions Sidebar',
-        'type'  => 'text_long'
+        'label'     => 'Promotions Sidebar',
+        'type'      => 'text_long',
+        'format'    => 'full_html',
+        'settings'  => Array(
+          'text_processing' => 1  // Allow text processing
+        )
       ),
       'instance'  => array(
         'widget'  => array(
@@ -170,9 +174,16 @@ function _biolawnorganics_build_field_instance($fieldType, $fieldInstancePartial
   $fieldInstance['field_name']  = $fieldName;
   $fieldInstance['label']       = $fieldType['label'];
   $fieldInstance['type']        = $fieldType['type'];
+
+  if (isset($fieldType['format']))
+    $fieldInstance['format`']   = $fieldType['format'];
+
+  if (isset($fieldType['settings']))
+    $fieldInstance['settings']  = $fieldType['settings'];
+
   $fieldInstance['entity_type'] = 'node';

-  $fieldInstance['display'] = array(
+  $fieldInstance['display']     = array(
     'example_node_list' => array(
       'label' => $fieldType['label'],
       'type'  => $fieldType['type']

```

# Answer
> 1 votes
If you want to have a text with full\_html format you can use the text\_format like this:

```
  $form['comment'] = array(
    '#type' => 'text_format',
    '#base_type' => 'textarea', // #base_type is optional.
    '#title' => t('Comment'),
    '#default_value' => $default,
    '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  );

```

---
Tags: 7, entities
---


title: Views slideshow with pagination

text:
# Question
Title: Views slideshow with pagination
Basically i need to create slide show same like this one example.

In this slide show there should be pagination like (1,2,3,4) and i need text and picture should refer to another content type and this text must be taken from the content type(for example the first 100 characters. How to achive this? what modules is best for this. any example will be nice. I found some examples with views and slideshow module, but most problem is pagination and how to get the text from content type to show it on a slideshow.

# Answer
Use Views Slideshow module and create a view with format Slideshow.

Check Readme file or Documentation of the module to create a view.

Views Slideshow module uses Jquery Cycle plugin which enables you to create exact slideshow effect that you are trying to achieve.
> 2 votes

# Answer
add field row number and uses this field in style: and set field to control
> 2 votes

# Answer
Here is the step by step tutorial to create slideshow the way you want

http://www.brightwebsitedesign.com/how-to-install-views-slideshow-module-on-drupal7
> 0 votes

# Answer
I would recommend field\_slideshow module instead of "Views Slideshow"

> Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.
> 0 votes

---
Tags: views, javascript
---


# Question
Title: Can I automatically regenerate all images after using Drush image-flush?
I used `drush image-flush` to delete all generated image style images on my site.

I know that image style images are automatically regenerated when you try to view them in a browser, but is there a way to "prime the cache" and automatically regenerate all image styles for all images after they have been deleted?

# Answer
There is a module that could help with this task, it offers a couple of extra features also that can be useful.

**Image Cache Info**

> Imageinfo Cache will generate image styles right after an image is uploaded and also on entity save. This will help with front end performance as the needed image style will already have been generated; thus the end user doesn't have to wait for the image to be generated. This can also mitigate some issues with image style generation if your CDN is configured incorrectly as the images will be generated without the request going through the CDN.
>
> Comes with a drush command called image-generate. It will generate images for a given field and style.

There is also a beta version of a rules module (kind of older):
> 4 votes

# Answer
I usually see people using wget or httrack for this - request every page in your site, and all of the images will be regenerated. Not very sophisticated, I know. As far as I know, though, there is no Drush command to do this.
> 5 votes

# Answer
If you want to generate image style programmatically for specific image using your custom code, here is the way:

```
image_style_create_derivative(image_style_load('medium'), $fileData->uri, image_style_path('medium', $fileData->uri));

```

*In case that you are building your custom API and want to generate the image to prepare it for the next request.*
> 2 votes

---
Tags: drush, media
---


title: Redirect user after registration

text:
# Question
Title: Redirect user after registration
I am trying to redirect new users after registration depending on values saved in $\_SESSION. I use ajax for registration form submission and `hook_user_insert` fro redirect

```
function MYMODULE_user_insert(&$edit, $account, $category){
global $user;
if(isset($_SESSION['VAR']) && !$user->uid){
    drupal_goto('path/to/somewhere');

}

```

Once form is submitted I receive alert `AJAX HTTP request terminated abnormally` and page html code. What should I change to make redirect working?

# Answer
You should alter the register form and set new redirect value.

```
function MYMODULE_user_register_form($form, &$form_state) {
  $form_state['redirect'] = 'path/to/somewhere';
}

```
> 1 votes

# Answer
Return

```
<script type="text/javascript">
  window.location.href="your_location";
</script>

```

from your ajax callback. Hope you get the idea
> 0 votes

# Answer
In case of ajax `drupal_goto` doesn't work. I found solution here. But it requires custom form submit function.

```
function MYMODULE_form_user_register_form_alter(&$form, &$form_state) {
$form['#submit'][0] = 'MYMODULE_user_register_form_submit';

}

```

And to make things work copied code of legacy function from `user` module
> 0 votes

---
Tags: redirection, forms
---


# Question
Title: 'File' class not found in submitForm(...) - uploading managed_file
I have an image field in my custom module's form:

```
namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Html;

class MyModuleForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['image_file'] = array(
      '#type' => 'managed_file',
      '#name' => 'image_file',
      '#title' => t('Block image'),
      '#size' => 40,
      '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
      '#upload_location' => 'public://myimages/'
    );
...

```

And for `submitForm(...)` I use:

```
  public function submitForm(array &$form, FormStateInterface $form_state){
    $image = $form_state->getValue('image_file');
    $file = File::load( $image[0] );
    $file->setPermanent();
    $file->save();
    ...

```

But when I use the form to submit image I get error (in log):

> Error: Class 'Drupal\my\_module\Form\File' not found in ...

# Answer
You need to add it in a use statement in your class (at the top of the file with the rest of the use statements)

```
use Drupal\file\Entity\File;

```
> 3 votes

---
Tags: forms, 8, files
---


title: Custom field type not found

text:
# Question
Title: Custom field type not found
I'm writing my first custom field type. The field will contain a rating field for authors. Now when I create the class for the field and activate my module nothing has been found. No errors can be found in the log and the field is not be inserted into the field list of the content type.

I used the "Drupal 8 Development Cookbook" for more information about Drupal 8, but when I check my source with the example from the book I can't find any changes (except from my custom rating).

My class that contains the custom field was placed in the src/Plugin/Field/FieldType/Rating.php file and looks like:

```
<?php

/**
 * @file
 * Contains \Drupal\RateField\Plugin\Field\FieldType\Rating.
 */

namespace Drupal\RateField\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'Rating' field type.
 *
 * @FieldType(
 *   id = "rating",
 *   label = @Translation("Rating field"),
 *   description = @Translation("This field stores a rating of the object."),
 *   category = @Translation("General"),
 *   default_widget = "string_textfield",
 *   default_formatter = "string"
 * )
 */
class Rating extends FieldItemBase {
  /**
   * {@inheritdoc}
   */
  public static function schema(\Drupal\Core\Field\FieldStorageDefinitionInterface $field_definition) {
    return array(
      'columns' => array(
        'rating' => array(
          'description' => 'Rating',
          'type' => 'int',
          'length' => '255',
          'not null' => TRUE,
          'default' => '0',
        ),
      ),
      'indexes' => array(
        'rating' => array('rating'),
      ),
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['rating'] = \Drupal\Core\TypedData\DataDefinition::create('range')
      ->setLabel(t('rating'));

    return $properties;
  }

}

```

Can someone help me with this?

# Answer
> 2 votes
This is most probably a namespace issue, I think you have to replace

```
namespace Drupal\RateField\Plugin\Field\FieldType;

```

with

```
namespace Drupal\rate_field\Plugin\Field\FieldType;

```

or whatever your name's folder is called.

Good luck!

---
Tags: 8, entities
---


# Question
Title: Sort related nodes in block views based on a score calculated with common vocabulary
Is it possible in drupal8 with Views to show related nodes in a block based on a score calculated with common vocabulary (each common tag adds some affinity points depending on vocabulary type).

The sorting in views is ordered by: 1- Editor manual selection. 2- Best related nodes ordered by max affinity with the current node 3- Nodes sorted by date

Regards, Thanks for your help

# Answer
> 1 votes
To place the php code to calculate the score there are several approaches:

1. Add an extra field for the score to your content type and calculate it in submit or presave.
2. Add a custom views field plugin: http://enzolutions.com/articles/2015/10/11/how-to-include-php-code-in-drupal-8-views/ or a custom sort plugin: https://chromatichq.com/blog/create-custom-views-sort-plugin-drupal-8
3. Use the module Computed Field.

With (1) you save the value in the database. This is best for calculations that don't change after saving the content.

A custom views plugin (2) is more dynamic and needs no space in the database, but it has to be recalculated each time.

The extra module (3) can do both, but it is not ready for production, still in alpha. If you read the linked how-to for views field plugins in (2) there are some good points that in D8 plugins are often more powerful than contrib modules to extend Drupal with custom php code.

---
Tags: views, 8, nodes
---


# Question
Title: Rest Export View multilingual content taxonomy filter fails
I am going to create a REST API using Drupal 8 Rest Export with Views. It is working fine so far. I am showing some fields from content type article and added contextual filters for language and tags.

I get results like this

```
[
   {
      "title": "Autem Camur Inhibeo Typicus",
      "field_tags": "restapi, test",
      "field_image": "http://localhost/drupal_8_api/sites/default/files/2016-12/gen5431.tmp.gif"
   }
]

```

I made every field of my article translatable except the tags (they should be the same in every language). This works fine, too, the correct translation is shown and the tags change for all translations if I change them in one translation (I have english and german right now)

My problem: When I filter by language it works fine and I get only german/english nodes. But if I filter for the tags and for german language I get no results. I could locate the problem a bit. If I set the tags-field to translateable, it works. So I think the problem might be that the german translation has no "own" tags and the filtering fails with this. The strange thing is that the JSON result is correct. (If I just filter for language I can see the correct tags in the german JSON)

Any help is appreciated (the tags should really not be translatable)

# Answer
> 0 votes
Pretty sure that's "just" yet another variant of the bug that this issue is trying to fix: Views should not condition joins on the langcode of fields that are not translatable

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


title: Add css style to theme in module

text:
# Question
Title: Add css style to theme in module
I'm writing a module that contains a star field. Now I'm placing the stars using the viewElements function of my field formatter. Everything is working. But I need to place some syling to the field output. Can I send some css styling to the active theme using my module?

My field formatter looks like:

```
public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
    $total = $item->rating/2;

    $stars = '';

    //Place colored stars
    for($i =0; $i < floor($total); $i++)
    {
        $stars .= '<span class="star on"></span>';
    }

    //Place half star
    if(floor($total) != $total)
    {
       $stars .= '<span class="star half"></span>';
    }

    //Place open stars
    for($i = ceil($total); $i < 5; $i++)
    {
        $stars .= '<span class="star"></span>';
    }

      $element[$delta] = array(
        '#markup' => $stars,
      );
    }
    return $element;
  }

```

The only thing that I'm missing is the css style that looks like:

```
.star {
    font-size: x-large;
    width: 50px;
    display: inline-block;
    color: gray;
}
.star:last-child {
    margin-right: 0;
}
.star:before {
    content:'\2605';
}
.star.on {
    color: gold;
}
.star.half:after {
    content:'\2605';
    color: gold;
    position: absolute;
    margin-left: -20px;
    width: 10px;
    overflow: hidden;
}

```

# Answer
> 5 votes
To do this, you need to create a \*.libraries.yml file, with the path to your css file in it:

MODULE.libaries.yml:

```
star-field:
  version: Version
  css:
    theme:
      path/to/stylesheet.css: {}

```

Then you can attach that library to your element:

```
$element['#attached']['library'][] = MODULE/star-field;

```

This can be overridden in a theme if/when necessary, so this styling should be considered the default styling that the module creates.

More reading: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

---
Tags: theming, 8
---


# Question
Title: Create custom action for Views Bulk Operations
I'm trying to add some custom actions to my Views Bulk Operations, but for some reason, they don't appear in the list. i want to add custom button to user can apply it and node DATE update to today...

This is my code (so I guess this is a working code...)

```
    /**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => FALSE, // Doesn't need config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}
/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {

  // I DONT KNOW .....................

}

```

# Answer
> 1 votes
I believe your type should not be `entity` but the actual entity type you want to use, like `node`. Then it should show up on nodes.

Also VBO requires no triggers to be defined, unless you want the action to be triggered via the action module as well. For just VBO this can be an empty array. I have no idea what behavior is, never used it.

See an example of VBO with a form here: Add multiple friends at once with user relationships

---
Tags: nodes
---


title: How to export comments?

text:
# Question
Title: How to export comments?
I have two Drupal website setups. One is development and another one is live. In my live setup lot of comments are there. I want to export all comments and import to development setup. How can I do that?

# Answer
> 1 votes
The best way to migrate content is the Migrate module, in the module page you can find many Case studies with code inside and in the documentation page you will find all the information that you need.

Inside the Migrate module folder you can find the Beer.inc file, which is an example of how you can do simple mappings. For more complicated migrations you can look into Wine.inc.

---
Tags: 7, nodes, migrations, comments, importing-exporting
---


# Question
Title: Comment replies to be another comment type
I need the comment replies to be another comment type. So, the normal comments should be of type "Standard". The answers to these standard comments should be of the type "Special", with more fields.

How do I achieve this?

# Answer
You don't need to use two different comments you can use only one and hide the "special" fields if the comment is not a reply comment.
> 1 votes

---
Tags: 8, comments
---


# Question
Title: Classes with the same name and description, but different location
When I am looking for an information about any class in api documentation, I often encounter the situation when there are several classes with the same name and the same description, but different location.

For example, there are two classes with name YamlDiscovery and the same description.

How should one select a needed class for oneself? Can use any class? If so, what for they were added both into Drupal 8?

# Answer
> 4 votes
That's a bad example, it is then used as another name to avoid a name conflict `use Drupal\Component\Discovery\YamlDiscovery as ComponentYamlDiscovery;`.

Usually you can see the purpose of the class when you look at the namespace or the corresponding file location. It's OK to use the same class name in different namespaces. As you can see in this issue there can be different opinions how descriptive class names should be and how much you should rely on the namespace of the class to make the purpose clear:

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

# Answer
> 1 votes
So we have 2 classes, one belongs in the `Drupal\Component\Discovery` namespace and the other in `Drupal\Core\Discovery`.

The `Component` namespace has code that is independent and the idea is that you should be able to use these classes outside of Drupal, so classes in components MUST NOT depend on any Drupal specific code, but MAY have dependencies on other Drupal components or external libraries.

Classes in `Core` namespace however are allowed to have Drupal specific code and if we look at the `YamlDiscovery` class in the `Core`-namespace we can see it extends the one from the Component.

```
namespace Drupal\Core\Discovery;

use Drupal\Component\Discovery\YamlDiscovery as ComponentYamlDiscovery;
use Drupal\Core\Serialization\Yaml;

/**
 * Provides discovery for YAML files within a given set of directories.
 *
 * This overrides the Component file decoding with the Core YAML implementation.
 */
class YamlDiscovery extends ComponentYamlDiscovery {

```

So, regarding which one you should use, I did some digging and the YamlDiscovery class in Core does use the PECL Yaml extension if it is available which is a performance boost. The issue is here: https://www.drupal.org/node/1920902

Generally I would prefer to use Drupal components as they are not tightly coupled to Drupal and loose coupling is considered good practises. However, in many cases Drupal Core adds things that you may need or enhances things like performance in this case. So if you have the PECL Yaml extension, go ahead and use the one from Core. Here is the link for the change record:

To give you another example, here is a good explanation on when the Drupal component and Drupal core differs much more. https://www.drupal.org/node/1834108 In this case I would use the latter (the class from Core) since it adds translation and formatted date values features.

---
Tags: 8
---


# Question
Title: How do I hide the authoring information?
I installed Drupal 8.2.4 and the IceMagic-8.x-1.0 theme. How do I hide the authoring information on articles?

# Answer
Edit the node type, in the "Display settings", there is a checkbox "Display author and date information", turn that off.
> 4 votes

---
Tags: nodes, 8
---