title: Change form title for a custom entity

text:
# Question
Title: Change form title for a custom entity
I'm just trying to clone a d7 site in 8. My first step was to use drupal console to generate a custom entity. Everything is working fine but I want to change the title of the form to "Create project" instead of the default "Add project".

I don't see "Add " anywhere *except* for `module.links.action.yml`, but that is just the local action - it doesn't change the name of the form.

The root of the directory looks like:

```
config
  schema
    project_entity_type.schema.yml
src
  Entity
    ...several classes
  Form
    ...several classes
  templates
    ...couple template files
  Tests
    LoadTest.php
module.page.inc
module.links.action.yml
module.links.menu.yml
module.links.tasks.yml
module.module
module.permissions.yml

```

# Answer
The answer comes from here: https://www.drupal.org/node/2187643.

Note: change "module" in the below code to the name of your module.

The first step is to register an event subscriber service. In `module.services.yml`:

```
services:
  module.route_subscriber:
    class: Drupal\module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

Next, create your class `RouteSubscriber` and extend `RouteSubscriberBase`:

```
  namespace Drupal\module\Routing;

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

  /**
   * Subscribe to the Route to change page titles.
   */
  class RouteSubscriber extends RouteSubscriberBase {

    private function alterRoutes(RouteCollection $collection) {
      if ($route = $collection->get('entity.project_entity.add_form')) {
        // set the title (or override '_title_callback' below)
        $route->setDefault('_title', 'Create Project Request');
        // unset the _title_callback; alternatively you could override it here
        $route->setDefault('_title_callback', '');
      }
    }
  }

```

Note that you receive a `RouteCollection` in `alterRoutes` and then using the `$collection-get()` will return an instance of `Route`. The documentation for Route can be found here: http://api.symfony.com/2.7/Symfony/Component/Routing/Route.html

If you're having trouble figuring out what your routes are, the excellent drupal console `drupal route:debug` tool will help you.
> 2 votes

---
Tags: 8
---


# Question
Title: Getting rid of module-specific control logic
I'm writing a module that can have some additional functionality if other modules such as Block or Menu are enabled, but I don't want to declare them as a dependency.

Currently I'm using `if(module_exists($module)) { ... }` to provide module-specific functionality within my custom module (in this case, defining a particular view if the module in question is present).

However I've heard that this is not the right way to provide module-specific features, and that instead I should use hooks and plugins. The only problem is that I don't really know what that means or how to get started converting my module to using those instead of `if()`s.

How do I define a custom view that depends on another module without using an `if()`?

One of the things I am trying to do is to expose that module's SQL tables to Views if the module exists, and then define a custom view with those tables.

# Answer
If you want to provide Views with your module, dependent on enabled modules, you can implement

`hook_views_default_views`

> This hook allows modules to provide their own views which can either be used as-is or as a "starter" for users to build from.
>
> This hook should be placed in MODULENAME.views\_default.inc and it will be auto-loaded. MODULENAME.views\_default.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
>
> The $view-\>disabled boolean flag indicates whether the View should be enabled (FALSE) or disabled (TRUE) by default.

In that hook implementation, you can check if the relevant module is enabled with `module_exists` or `function_exists` when defining that View or component of the View and return the View definition(s) accordingly.
> 1 votes

# Answer
I think what you are looking for (or what other people meant when they said that you shouldn't use module\_exists() so much) would be to implement hooks "on behalf of" another module.

E.g. Crumbs introduces a hook\_crumbs\_plugins(), and then it implements this hook on behalf of other modules: menu\_crumbs\_plugins(), taxonomy\_crumbs\_plugins(), etc. These hooks will only ever be triggered if the respective other modules are enabled.

Whether this is a good idea, depends. It is ok if you are really confident that the respective module will never ever implement this hook by itself. But you need to be aware that you are intruding in the other module's "namespace".

Module names as function prefixes in D7 are quite fragile anyway compared to real namespaces, so maybe we all don't care so much in D7 and just pray that nothing blows up.

Otherwise I don't think it is all too wrong to use module\_exists() where it makes sense.

Next time someone says this is best practice, ask them to explain why! There are a lot of mythical and unquestioned DOs and DONTs floating around in the community..
> 0 votes

# Answer
If you're using `hook_views_default_views`, then using `if` `module_exists` is perfectly fine.

See the example how Entityform module implements that in `entityform.views_default.inc` file:

```
/**
 * Implements hook_views_default_views().
 */
function entityform_views_default_views() {
  $view = new view;
  $view->name = 'entityforms';
  // ...
  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['title'] = 'List';
  // ...
  $handler->display->display_options['relationships']['uid']['required'] = 0;

  if (module_exists('views_bulk_operations')) {
    /* Field: Bulk operations: Entityform */
    $handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
    $handler->display->display_options['fields']['views_bulk_operations']['table'] = 'entityform';
    // ...
    $handler->display->display_options['fields']['views_bulk_operations']['vbo']['force_single'] = 0;
  }

  /* Field: User: Name */
  $handler->display->display_options['fields']['name']['id'] = 'name';
  $handler->display->display_options['fields']['name']['table'] = 'users';
  // ...
  $handler->display->display_options['tab_options']['name'] = 'management';
  $views[$view->name] = $view;

  return $views;
}

```

Then if another module wants to alter the existing view definition, it can use `hook_views_default_views_alter` in similar way (see example here).
> 0 votes

---
Tags: 7, hooks
---


title: Add a node field to a comments view

text:
# Question
Title: Add a node field to a comments view
I'm using Drupal 7, Views 3, and Token.

I created a view of comments.

I would like added to this view a field of the parent node.

I thus added a header, of type "global text area", I tried of added a token corresponding to the desired field, clicked on "Use replacement tokens from the first row ", but it does not work (the token appears but not the field).

Have you a solution?

# Answer
> 1 votes
You should be able to see the parent node field suggestion in your views. One thing I doubt is parent node of comment on the top(first row) should have that field you are trying to add, as 'Use replacement tokens from the first row' will simply replace the title as per the parent node on the first row.

Adding a sample view on the same lines

View Configuration

View Preview

# Answer
> 1 votes
You need to add a relationship to your view on the nid. Once you do that you will have the fields from the parent node available to be added to your view.

---
Tags: 7, views, theming, tokens
---


# Question
Title: How to add subquery in views to remove particular type of rows?
I have applied join to **users** table with **node\_revision** table like below:

```
function custom_overrides_views_data_alter(&$data) {

  $data['users']['node_revision'] = array(
    'title' => t('Users revisions authored'),
    'help' => t('Relate a user to their revisions'),
    'relationship' => array(
      'base' => 'node_revision',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('revisions bubbla'),
    ),
  );
}

```

And by creating view now I got number of revisions per user like below:

> Westerberg (15752)
>
> Eriksson (4305)
>
> Jakob (4182)
>
> Andersson (4153)

But now I want to remove those revisions which are created when user created node first time ie: will only show edits but not the revisions which are created first time when new node was created. To solve this logic is to remove nodes having below true:

**excluding the “first time created” nodes (original node revision)**

```
node.created = node_revision.timestamp

```

I tried using query alter but it uses quotes around field please suggest how to remove that ?

```
if ($view->name == "my_view") {

    $sub_query = db_select('node', 'n')
      ->fields('n', array('created'))
      ->condition('n.created', 'node_revision_users.timestamp');

    $view->query->where[1]['conditions'][] = array(
      'field' => 'node_revision_users.timestamp',
      'value' => $sub_query,
      'operator' => 'NOT IN'
    );

  }

```

**Output problem is like screenshot:**

Please suggest! thanks

# Answer
You should use `where()` to match table columns instead of condition

```
if ($view->name == "my_view") {
    $sub_query = db_select('node', 'n')
      ->fields('n', array('created'))
      ->where("n.created = node_revision_users.timestamp");

      $view->query->where[1]['conditions'][] = array(
        'field' => 'node_revision_users.timestamp',
        'value' => $sub_query,
        'operator' => 'NOT IN'
      );
}

```

**Update**

Why where() not condition()

**Syntax for condition:**

```
$query->condition($field, $value = NULL, $operator = '=')

```

shows condition() is for building standard condition fragement

**Syntax for where:**

```
$query->where($snippet, $args = array())

```

shows where() is for building any arbitrary SQL as conditional fragment.

`$snippet` may contain any legal SQL fragment.
> 2 votes

---
Tags: 7, views
---


# Question
Title: How can I flush a json response in a controller?
Didn't find this when I googled before, posting to maybe save the next person some time.

# Answer
> 0 votes
Maybe obvious for people familiar with Symfony, but was new for me; spent way too long trying to find something so simple:

```
$json_response = new JsonResponse($my_key_value_array);
$json_response->send();
$this->function_that_takes_a_long_time();

```

---
Tags: 8, ajax
---


title: Bug API migration with postgreSQL

text:
# Question
Title: Bug API migration with postgreSQL
i have an issue concerning the API migration. I have an existing drupal 7 website with a MySQL database. Now i want to migrate this website in a new drupal 8 instalation with a postgreSQL database. With a drupal 8 postgreSql, i can't execute the drush commande "migrate-status" or other :

while with exactly the same module and config, simply changing the BDD by a mySql one, i have access to these commands :

Does the migration modules are compatible with a postgresSql drupal ? Regards

# Answer
It looks like you simply don't have the migrate\_tools module enabled in the Postgres environment.
> 0 votes

---
Tags: drush, migrations
---


title: Migrate Entity Validation

text:
# Question
Title: Migrate Entity Validation
I am trying to migrate some data with the migrate api in a custom entity called Seller.

Each seller has an email address with a constraint "UniqueField" which checks, that the email address is just entered once. If i try to import a seller with an existing email address, the seller will be created although the email already exists.

So my question is: Doesn't the migration api consider the entity validation or how can I do this?

One solution for the problem would be to write a custom process plugin for the email address, but it would be nice, if the entity validation would check this automatically.

# Answer
> 0 votes
There is an open core issue to add validation to content entities: https://www.drupal.org/node/2745797

With that patch, you can enable validation thusly:

```
destination:
  plugin: entity:node
  validate: true

```

---
Tags: 8, migrations
---


# Question
Title: Error after installing module twice: Configuration object already exist
I've followed How to create views programmatically in Drupal 8, but as I asked in this topic, my view doesn't appear in my list.

When I install my module twice (*Enable -\> Uninstall -\> Enable*), I have an error:

> Configuration object `views.views.viewsname` already exist

I also tried to import it directly in Drupal, copied the exact same code and this worked.

# Answer
As the error says, the problem isn't with your module, but simply that the configuration your module is trying to create already exists in your installation.

You have two options to get it installed:

1. delete the configuration first, in the UI or programatically (How do I remove a configuration object from the active configuration?) and then add an enforced dependendency on your module, to make sure it is removed when your module is uninstalled. Note that you must first remove the config, the enforced dependency that removes your config only works once installed using the new definition.
2. Provide as optional config in config/optional instead of config/install. Optional config is different from other config in two ways:
    * First, it is only installed when all the required dependencies exist. That is useful if you have optional integration with another module and if it is installed, provide some configuration for it. This even works if that other module is installed later on. Configuration with missing dependencies in config/install fails with an error as Drupal assumes your module will not work correctly if the config can not be installed.
    * Second, it will also be silently skipped if the config exists already, which is the relevant thing for your case. It will however also be silently skipped if the existing config just happens to be a view with the same name that is actually something else.
> 1 votes

---
Tags: views, 8
---


title: Redirect a form to an external URL

text:
# Question
Title: Redirect a form to an external URL
Want to redirect $form\_state to external URL after successful registration of the user. Like, need to redirect to facebook after user registration.

```
  $query = "http://facebook.com";
  $url = Url::fromRoute('user.register', [], ['query' => ['service' => $query]]);
  $form_state->setRedirectUrl($url);
  //$url = Url::fromUri($query);
  return RedirectResponse::create($url->toString(), 302);

  $form_state>setResponse(newTrustedRedirectResponse('https://google.com', 302));
  return new RedirectResponse($query);
  $form_state->setRedirect($query);
  $form_state->setRedirectUrl(Url::fromUri($query));
  $response = new RedirectResponse($query);
  $response->send();

```

tried above all methods, but nothing works.

# Answer
> 8 votes
The method that you missed is `$form_state->setResponse()`. In combination with a `TrustedRedirectResponse` object, which exists for security reasons (to prevent users from accidentally being redirected to another site), you can use code similar to the following.

```
$response = new TrustedRedirectResponse('https://facebook.com');
$form_state->setResponse($response);

```

---
Tags: forms, 8, redirection
---


# Question
Title: Why my custom submit handler isn't working in menu item edit form?
Code:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_menu_link_content_menu_link_content_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  array_unshift($form['#submit'], 'mymod_menu_link_content_form_submit');
}

function mymod_menu_link_content_form_submit($form, \Drupal\Core\Form\FormStateInterface $formState) {
  //some code
}

```

Debug shows me that my custom submit handler is added to `$form['#submit']` array as a first item. However this submit handler is never called.

# Answer
> 3 votes
Forms can have submit callbacks in two places. Either on the form level or on the button that is pressed. The form level callbacks are only invoked if no button-specific callbacks are specified.

Entity forms generally have the submit callbacks on the submit button, which is usually `$form['actions']['submit']['#submit']`.

This was the same in Drupal 7, although the node form and possibly others had a backwards compatibility layer that also invoked form-level submit callbacks, but this was removed.

---
Tags: forms, 8
---


# Question
Title: How to tell Stringsoverrides module to replace text only in specific module?
How to tell Stringsoverrides module to replace text only in specific module? Are there any alternatives to this module?

# Answer
String Override works for the strings defined inside `t()`, t() takes context as one of the parameters, for example

```
1. t('May', array(), array('context' => 'Long month name')
2. t('May', array(), array('context' => 'Abbreviated month name')

```

Both the strings are 'May', if you replace it would be changed across, but t() function also takes context, so if you provide the right context, only that instance of sting will be replaced. String overrides also takes the context while replacing the string, you have to make sure the string you want to replace in a moudle passes through t() and with what context.

Other way could be if its a variable then do a variable\_set()

What I prefer is to patch the module, keep the patch in patches folder. To me string replacement is not mission critical peace, after next update release we re-do our patch.
> 0 votes

---
Tags: i18n-l10n
---


title: How to translate database field values?

text:
# Question
Title: How to translate database field values?
I cannot find information on how translate database field values. On my site I use Support Ticketing System module. If I'm trying translate interface to German (for example) everithing is ok except Status field (Status field is reffering to support ticket status - new, in progress, closed). I can see in the database all these values (new, in progress, closed) in certain table. But how to translate them? The built-in Drupal interface translation does not recognize these values.

Can you advise the correct way for translation of these field values?

# Answer
Have a look at the Field Translation module, a submodule (i18n\_field) of the i18n module. Some more details about it (from the Community documentation):

> ... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (`Administration > Configuration > Regional and language > Translate interface`).

Especially the "***list options***" mentioned above seem to be what you're looking for.
> 0 votes

---
Tags: database
---


# Question
Title: Drupal 8 Bootstrap Theme Background "transparent" (e.g. offcanvas-lining visible)
I have installed the Drupal 8 Bootstrap Theme (version 8.x-3.0-rc2) on a newly setup site. When I logout and view the page everything looks as I would expect it. But while I am logged in when I click on "Back to Site" in the top left corner then I only see a background of`background-color: #333` which is being set by a class named `.offcanvas-lining`. This makes working with the theme almost impossible because the text and headers have the same color and so the text is invisible.

I could probably override that somehow but I would like to understand if this is an issue with the Drupal 8 theme or if I have made a mistake when I setup the theme.

What is this `offcanvas-lining` element doing and why am I seeing its background rather then the usual white bootstrap background which is the default.

# Answer
> 2 votes
Looks like this was being caused by the "Settings Tray" module which was added in Drupal 8 and which I had activated. Deactivating the module has fixed the issue for me.

It seems other people also have this issue with other themes: https://www.drupal.org/node/2819091

---
Tags: theming, 8
---


# Question
Title: What to attach event listener to in Drupal behavior
I have a use case where I need to listen to the insertIntoActiveEditor event in the insertIntoActiveEditor event in the Insert module, but with this code:

```
(function ($) {

/**
 * Custom behavior to generate image style derivatives on S3 when an image is
 * inserted into the WYSWIYG editor.
 */
Drupal.behaviors.generateDerivative = {
  attach: function(context, settings) {
    $(document).on('insertIntoActiveEditor', function(event, data) {
      var test = 'a';

    })
  }
}
})(jQuery);

```

I'm getting an error that says

```
Uncaught TypeError: $(...).on is not a function

```

on this line

```
$(document).on('insertIntoActiveEditor', function(event, data) {

```

I thought I had that syntax correct, but apparently I don't. Do I need to change my selector to be the Insert button (the same as is used in the module JS)? I"ve tried changing it to

```
$('input[value="Insert"]').on('insertIntoActiveEditor', function(event, data) {

```

but I still get the same error.

Thanks.

# Answer
The cause was pretty basic - this is in the admin theme, which in Drupal 7 is set to use jQuery 1.4.4, and .on() wasn't added until 1.7. I switched to using .bind(), and it works fine now.
> 1 votes

---
Tags: 7, event-subscribers, javascript
---


title: How do I add conditional validation?

text:
# Question
Title: How do I add conditional validation?
I have field collection. The problem is that one field is depended on select list.

When I choose type "job" from select list then company field should be required for that collection. Otherwise company field should be completely omitted in validation.

Update:

I tried to add my own constraint validator but with no effect and I don't have errors on that.

```
function job_market_user_entity_bundle_field_info_alter(
  &$fields,
  \Drupal\Core\Entity\EntityTypeInterface $entity_type,
  $bundle
) {
  if ($entity_type->id() == 'field_collection_item') {
    /* @var Drupal\field\Entity\FieldConfig $company_field */
    if ($bundle === 'field_jmu_working_experience') {
      $company_field = $fields['field_jmu_company'];
      if ($company_field) {
        $company_field->addConstraint('JobTypeConstraint');
      }
    }
  }
}

```

Constraint

```
namespace Drupal\job_market_user\Plugin\Validation\Constraint;

use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\Plugin\Validation\Constraint\CompositeConstraintBase;
use Drupal\Core\Validation\Annotation\Constraint;
/**
 * @Constraint(
 *   id = "JobTypeConstraint",
 *   label = @Translation("Job Type", context = "Validation"),
 * )
 */
class JobTypeConstraint extends CompositeConstraintBase {

  /**
   * @var string
   */
  public $message = 'Company field is required for Job working experience';

  /**
   * {@inheritdoc}
   */
  public function coversFields() {
    return ['field_jmu_type', 'field_jmu_company'];
  }
}

```

Validator (I added violation just to check if it's invoked - no effect yet)

```
namespace Drupal\job_market_user\Plugin\Validation\Constraint;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 *
 * Supports validating company depended on job type
 */
class JobTypeConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;

  /**
   * {@inheritdoc}
   */
  public function validate($entity, Constraint $constraint) {
    $this->context->buildViolation($constraint->message)
      ->atPath('field_jmu_company')
      ->addViolation();
    return;
  }

  /**
   * Instantiates a new instance of this class.
   *
   * This is a factory method that returns a new instance of this class. The
   * factory should pass any needed dependencies into the constructor of this
   * class, but not the container itself. Every call to this method must return
   * a new instance of this class; that is, it may not implement a singleton.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The service container this instance should use.
   *
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity_type.manager')->getStorage('user'));
  }
}

```

# Answer
> 1 votes
Afterwords for some reason adding constraint in field collection haven't work for me. Maybe this is an issue of field collection module. I found ugly solution that cover my needs.

The first part is adding states for each collection item. They are responsible for showing and hiding company field depends of the job type value. States use jQuery so content is dynamically changed without page reload (nice!).

The second part is adding form validation hook `$form['#validate'][]`.

```
function job_market_user_form_alter(
  &$form,
  \Drupal\Core\Form\FormStateInterface &$form_state,
  $form_id
) {
  if ($form_id === 'user_working_experience_form') {
    foreach ($form['field_jmu_working_experience']['widget'] as $key => $value) {
      if (isset($form['field_jmu_working_experience']['widget'][$key])) {
        $widget = &$form['field_jmu_working_experience']['widget'][$key];
        if (isset($widget['field_jmu_type'])) {
          $states_when_job_is_selected = array(
            'visible' => array(
              ':input[name="field_jmu_working_experience[' . $key . '][field_jmu_type]"]' => array('value' => 'job'),
            )
          );

          if (isset($widget['field_jmu_company'])) {
            $widget['field_jmu_company']['#states'] = $states_when_job_is_selected;
          }

          $form['#validate'][] = '_form_user_working_experience_validate';
        }
      }
    }
  }

  return $form;
}

```

In validation:

Company field validation only checks if this field is required. So for `($type !== 'job')` I have to usnet require error.

Few weird things going on there which I'll try to explain:

1st I have to cast `$collection_item` to an array `$collection_item_array = (array) $collection_item;`. When I use var\_dump on this it returns that this variable is an array but when I try to get array element it throws an error

> Cannot use object of type Drupal\Core\StringTranslation\TranslatableMarkup as array

Hmm Smells like really bad coding practice because this variable is reference and it type change in other function.

2nd `$form_state` don't have an method like `$form_state->removeError($error)` so I have to copy all errors, clear them using `$form_state->clearErrors();` unset what I have to unset and set errors. The one more thing about this is you can't get errors and set errors like this:

```
// Types are not compatible
$errors = $form_state->getErrors();
$form_state->setErrors($errors);

```

3rd `$company_field_name` is not name I expected. if you copy name from html it'll look like this:

`field_jmu_working_experience[' . $key . '][field_jmu_company][0][target_id]`

this is not correct for `$form_state->setErrorByName($name, $message = '')`

Name should have that structure:

`field_jmu_working_experience][' . $key . '][field_jmu_company][0][target_id`. This is explained here

Finally Validation function looks like this.

```
function _form_user_working_experience_validate(
  &$form,
  \Drupal\Core\Form\FormStateInterface &$form_state
) {
  $collection_items = $form_state->getValue('field_jmu_working_experience');
  foreach ($collection_items as $key => $collection_item) {
    $collection_item_array = (array) $collection_item;
    $type_field = isset($collection_item_array['field_jmu_type']) ? $collection_item_array['field_jmu_type'] : [];
    $company_field_name = 'field_jmu_working_experience][' . $key . '][field_jmu_company][0][target_id';

    if (!empty($type_field)) {
      $type = $type_field[0]['value'];

      if ($type !== 'job') {
        $errors = $form_state->getErrors();
        $form_state->clearErrors();

        if (isset($errors[$company_field_name])) {
          //unset required
          unset($errors[$company_field_name]);
        }
        /* @var Drupal\Core\StringTranslation\TranslatableMarkup $error*/
        foreach ($errors as $err_key => $error) {
          $form_state->setErrorByName($err_key, $error->render());
        }
      }
    }
  }
}

```

I hope in the future all issues were be resolved and we'll be able to use Constraints.

# Answer
> 4 votes
You can use the States API to make a field visually required, visible/hidden and so on.

One simple example from https://randyfay.com/states

```
  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name=student_type]' => array('value' => t('High School')),
      ),
    ),
  );

```

There are UI modules to configure this, like https://www.drupal.org/project/conditional\_fields, but I think none is ported to D8 yet. So you have to form alter it in.

Also, keep in mind that this is UI only. You still need to implement corresponding server-side validation.

# Answer
> 0 votes
You can actually use the states API to do what you want without all of that workaround.

put this in your array:

```
  '#states' => array(
    'enabled' => array(
      array(':input[name="Country"]' => array('value' => 'US')),
    ),
    'visible' => array(
      array(':input[name="Country"]' => array('value' => 'US')),
    ),

    'required' => array(
      array(':input[name="Country"]' => array('value' => 'US')),
    ),
  ),

```

This makes the current selection required only if USA was chosen.

---
Tags: 8, entities
---


# Question
Title: Uppercase module names - what could go wrong, technically?
This is a technical curiosity question.

Afaik, it is convention that module names in Drupal should be lowercase, with underscores.

Obviously it is generally good to follow conventions.

But does someone know what could go wrong, technically, if module names are upper case or mixed case? E.g. camel case.

I think to remember to have seen at least one case in contrib where a module was CamelCase, but I don't remember which one.

# Answer
> 3 votes
Update functions, for example, go wrong: The regular expression that looks for them only works if the module name is lowercase only.

I don't remember exactly how it fails, but I used to have a case once where someone wrote a module that had uppercase characters and it wasn't possible to have update functions.

That's the only thing that I'm aware of.

---
Tags: 8
---


title: Can't add js to content creation pages

text:
# Question
Title: Can't add js to content creation pages
I'm trying to add JS to content create pages using the second function from @kiamlaluno's answer

However, this is not working for me.

I created a module with his folder structure:

`add_js
 add_js.info
 add_js.module
 custom.js`

add\_js.info:

```
name = Add JS to admin pages
description = Add js to admin pages
core = 7.x

```

add\_js.module:

```
<?php

    function add_js_init() {
      if (arg(0) == 'admin') {
        $path = drupal_get_path('module', 'add_js');
        drupal_add_js($path . '/custom.js');
      }
    }

```

custom.js:

```
jQuery(document).ready(function ($) {
    $("html").addClass("hello");
});

```

Also tried this .module file:

```
<?php

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_form':
      $form['#after_build'][] = 'mymodule_after_build';
      break;
  }
}

function mymodule_after_build($form, &$form_state) {
  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js ("$path/mymodule.js");
  return $form;
}

```

Although I am pretty inexperienced still, I did remember to enable the module and flush the caches... :D

# Answer
```
/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

```

In your case would be:

```
/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function add_js_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';
}

```

**Note:** This will add the JS to all of your content types node edit pages.

---

If you need to target a specific content type, all you gotta do is add an if statement, see:

How can I find the form ID of a form?

```
/**
*  Implements hook_form_BASE_FORM_ID_alter.
*/
  function add_js_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
      $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';
    }
  }

```

and I believe you could alternatively do this, put the `my_form_id` directly in the hook:

```
/**
*  Implements hook_form_BASE_FORM_ID_alter.
*/
  function add_js_form_my_form_id_alter(&$form, &$form_state, $form_id) {

      $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';

  }

```
> 4 votes

---
Tags: 7, javascript
---


# Question
Title: Search API Solr: How to index fulltext fields with and without stemming?
**In short:** Is there any way to index the stemmed and non-stemmed version of Fulltext fields in Drupal Search API Solr without resorting to hardcoding field data into `copyfield` in the schema file?

(and if not, what's the safest, most Drupal / Search API friendly approach to doing this? e.g. using Drupal field machine names in the Solr schema file, maybe?)

---

**Background:** A common practice when working with Apache Solr is to use a stemmer like `SnowballPorterFilterFactory` *(stemmers make searches match by the grammatical 'stem' of a word, so for example, searches on "walking" match content with "walked")*, then, **to copy fulltext fields** (e.g. using copyfield), stemming one of the two duplicates and not stemming the other.

This popular approach has two advantages (at the cost of more processing):

* Exact matches are indexed more highly than close matches - a search on "walking" matches content with "walking" twice (stemmed and unstemmed) and content with "walked" once (stemmed only)
* You're guaranteed to not have any awkward cases where a search on a stemmable term fails to match content that contains that original exact term\*.

As I understand it, when Solr is used outside of Drupal, this is usually done by hardcoding `<copyfield>` declarations into the Solr schema file for each field that is to be stemmed.

---

*(for the sake of this question, imagine a Search API Solr search indexing nodes, processing as fulltext the fields Title, Body, Teaser, and one custom field named Notes)*

---

**The problem:** With **Drupal** and the **Search API module**'s Search API Solr, the fields are configured by Drupal dynamically - rather than being hardcoded in the Solr `schema.txt` file. It's not clear how to make the two approaches play nicely together.

Is there a better, more Drupal-friendly way to index stemmed and unstemmed content than hard-coding the field names into something based on `copyfield` in the `schema.txt` file?

If hard-coding is the answer, what names should be used, what care needs to be taken to avoid namespace problems?

---

**Another popular approach** with Solr outside of Drupal is to create a composite field of all your fulltext fields, combined, and treat it as a *string* rather than fulltext - so it bypasses filters and simply mops up and boosts any words that are searched for exactly as they appear in the text. Search API has two features under Workflow that look promising for this, `Aggregated fields` and `Complete entity view` \- **but** (as far as I can tell) both can only index as Fulltext and would therefore be stemmed just like the regular field.

---

I can't see anything on this specific to Search API Solr. The closest I can see is this issue for D8 core search, but that's rather different. I can't find any information about anything like this for Search API.

---

\**(for example, I find that with stemming, searches on 'unravelling' don't match content containing 'unravelling', but searches on 'unravel' do. It's being stemmed down to 'unravel', but for some reason it's not recognising 'unravelling' as a valid extension of the stem 'unravel'. 'Unpublished' is another example (unpublish matches, unpublished doesn't). I've seen various reports of similar language-specific stemming issues. Keeping an unstemmed copy seems to be the standard approach, but I can't see any clean way to do this in Drupal)\*

---

Also posted as a support issue on the Search API Solr queue (yes, cross posting like this is okay, actually encouraged to make life easier for maintainers)

# Answer
> 9 votes
Good question, and also a topic that should probably be brought up as a feature request for both Apache Solr Integration and Search API Solr at some point. Searching both stemmed and unstemmed content can often lead to significantly better results.

For Search API Solr, there's no way to do this without modifying the schema.xml bundled with the module. But you're probably already aware of that since you're using stemming and the bundled schema does not have stemming enabled by default.

The key to doing this without lots copyField definitions is to **use a combination of dynamicField and copyField**. You'll also need **two different fieldType definitions**, one for unstemmed and one for stemmed text.

Try these steps:

1. Duplicate the entire definition for `<fieldType name="text">` as `<fieldType name="stemmed_text">` and uncomment the SnowballPorterFilterFactory filter.
2. Add a dynamicField definition using this new fieldType. The data does not need to be stored, only indexed. Example: `<dynamicField name="stemmed_*" type="stemmed_text" termVectors="true" stored="false" />`
3. Add a wildcard copyField definition that copies all text fields into corresponding stemmed text fields. Example: `<copyField source="t_*" dest="stemmed_*" />`
4. Reindex.
5. Add "qf" params to the Solr query for all stemmed fields you want to search. You can do this via `hook_search_api_solr_query_alter()`. If you want all text fields, you can look for field names prefixed with "t\_".

**Bonus**: Sometimes it helps to boost matches against the unstemmed field in order to make more exact results appear first. You can add boost factors to the field names in the qf param.

**Bonus #2**: The pf param ("phrase field") is another good way to boost exact matches. This lets you give priority to results where terms are in the same order as what the user entered.

**Apache Solr Integration module:**

For those using apachesolr.module, matching against both stemmed/unstemmed can be done without changing schema.xml. The bundled schema includes lots of dynamicFields and is quite flexible. By default, searchable fields are stemmed. You can simply copy content fields to unstemmed dynamicFields in `hook_apachesolr_index_documents_alter()` and then add "qf" params for those fields via `hook_apachesolr_query_alter()`.

# Answer
> 0 votes
I don't know if the following is a complete and sufficient solution to the original problem, but I post it anyway. Maybe it it will be helpful.

You can use hook\_entity\_property\_info() to define a property for your field, and then index this property as a duplicate of the original field, with different settings.

E.g. I just did this for a 'list\_text' field, where I indexed the property as "Fulltext", and the original field as "String" which is more useful for a facet.

---
Tags: search
---


# Question
Title: Update node alias while retaining the old alias
I want to update many of my node's aliases. I have seen many questions here at Drupal Answers, but nothing I can use, as far as I can see.

What I want to do: I want to update a big portion of URLs (mostly forum nodes) to a new alias and still keeping the old aliases. I can do this by using VBO. However, when I update the URL alias using VBO, all forum nodes as well as other nodes will get the "Has new content" marker saying "updated". I want to avoid the nodes getting this "updated" marker since I have around +10,000 nodes.

I have looked in Rules trying to figure if there is I way I can set the nodes to being marked as "read" when I update the URL alias, but I can't see a way to do this.

The reason I'm not just deleting all aliases and then bulk generate them again, is that it won't keep my current aliases thus giving me many 404 errors in the future.

Is there a way to update the node's alias and still keeping the old alias and not having all the nodes marked as "updated"?

# Answer
Ultimately, a VBO action affecting a node is going to call `node_save()` which will change the `changed` node property that determines when the **updated** marker appears.

To get around this, you'll need to preserve the node `changed` timestamps following your bulk alias updating. You can do this by directly updating the `node.changed` column in the database.

Depending on your preferences, there's many ways to backup/restore database data. For example, executing a Drush snippet before node alias bulk updating could dump a JSON file with your nid/updated timestamps:

```
drush ev '$nodes = db_select("node", "n")
  ->fields("n", array("nid", "changed"))->execute();
$timestamps = array();
foreach ($nodes as $node) {
  $timestamps[$node->nid] = $node->changed;
}
echo json_encode($timestamps);' > my_node_timestamps.json

```

Following bulk alias updating, another snippet could restore it from the JSON:

```
cat my_node_timestamps.json | drush ev '
$timestamps = json_decode(file_get_contents("php://stdin"));
foreach ($timestamps as $nid => $timestamp) {
  db_update("node")
    ->fields(array("changed" => $timestamp))->condition("nid", $nid)->execute();
}
'

```

As the case with any operations directly touching your database directly, make sure to perform backups before performing any such bulk operation.
> 1 votes

---
Tags: path-aliases
---


# Question
Title: How to make the cart menu display the number of items added?
How to make the cart menu display the number of items added?

Example If I added one item, the cart menu will display "one".

Module: Drupal Commerce

# Answer
> 1 votes
**Commerce Ajax Add to Cart**

> Using this module you can ajaxify the add to cart operation. The updated cart will be displayed without page refresh and a popup message will be shown after you add an item to cart. You can customize the look of the blocks using its template files.

---
Tags: 7, commerce
---


title: Accesing blocks from the server via FTP

text:
# Question
Title: Accesing blocks from the server via FTP
So I created a custom block and put the block on every page but unfortunately the block causes a white screen... I can't login to change the block because the block is on every page, as I mentioned. Is it possible using an FTP program to access blocks via the server and delete/change them?

# Answer
> 3 votes
First of all, blocks are stored in the Database, not in your web directory. Therefore, FTP is useless here.

If the custom block was created using a custom module, simply disable the module.

If the custom block was created using the Drupal User Interface, you can disable your custom block by changing the status from 1 to 0 or edit the block body by login in into your Database using PHPMyAdmin and finding the correct block table.

---
Tags: blocks, wsod
---


# Question
Title: Drush is always scanning the whole drupal directory?
Every time i run a drush command the command returns after 40s. (or more if time consuming operation like cache clean or so)

After strace the command i realized that drush is scanning my whole drupal directory. I have mounted via nfs an storage with thousands of Files which are accessed by an own module and i think there is no need for drush to scan these files on every run. Is there an option to exclude a path ?

my files are in drupal\_root/sites/default/files/my\_module/nodes/nid/

Greetings Robert

# Answer
There might be something wrong with your module... You say there are more than a thousand files scanned but are they placed in your module's directory ?

Drush is not supposed to scan your `sites/default/files` folder for instance or any other data folder you might have set. As a best practice you should not place data in your module's path (obvious... isn't it ?). If you have done so, you should think about moving them somewhere else.

When executed, Drush scans all activated modules path (along with a few others such as `sites/all/drush`) for `.drush.inc` files. This is the expected behavior and that might cause your slow script execution.
> 1 votes

# Answer
After investigating the problem with a new attempt. i debugged drush and noticed that my drush version was scanning the whole data directory of my module for alias files. An corresponding bug report you can find here:

https://github.com/drush-ops/drush/pull/1537

so here is what you have to do: update drush
> 0 votes

---
Tags: drush, files
---


title: YAML Form in Block

text:
# Question
Title: YAML Form in Block
I want to show order form on all my services pages.

I have created a form using YAML form.

Want to know how can I display that form in a block.

# Answer
> 0 votes
YAML Forms are available as block by default. In block layout you can place a "Form" block and then select in the autocomplete field "Form" which YAML form you like to display.

---
Tags: forms, 8
---


# Question
Title: How to set value of file field with entity_metadata_wrapper
How do you set the value of a file field when using the entity\_metadata\_wrapper?

I've tried doing this in code:

```
$file = new stdClass();
$file->uid = 1;
$file->uri = $file_path;
$file->filename = basename($file_path);
$file->filemime = file_get_mimetype($file_path);
$file->filesize = filesize($file_path);
$file->status = FILE_STATUS_PERMANENT;
$file->display = '1';
file_save($file); // I also tried: $file = file_save($file);

$node = array(
  'type' => 'news_item',
  'uid' => 1,
  'status' => 1,
  'comment' => 0,
  'promote' => 0,
  'language' => 'en',
);

$entity = entity_create('node', $node);

$ewrapper = entity_metadata_wrapper('node', $entity);

$ewrapper->field_document->set((array) $file); // I also tried: $ewrapper->field_document->set($file);

$ewrapper->save(true);
entity_save('node', $entity);

```

But I get this exception:

```
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of C:\wamp\www\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).

```

Any help is very mych appreciated.

# Answer
Wrapping the file array in another array seems to do the trick for me:

```
$file = (array) $file;
$items = array($file);
$ewrapper->field_document->set($items);

```

But I haven't found out *why* yet...
> 14 votes

# Answer
Well I just found out a **simpler and less ugly looking way to set image**.

```
$image_file = A FILE OBJECT; //Lot of choices here : new stdClass(), file_load, etc
$wrapper->FIELD_NAME->file->set($image_file);

```

Just as taxonomy or node/entity reference, the file field name point on a loaded object, thats how I find out.

---

:: EDIT a posteriori ::

Here how I would have do it with OP question.

```
// Get the file
$file = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg');

// Wrap' it like one of your French girls
$wrapper = entity_metadata_wrapper('node', $node);

// And set the photo
$wrapper->field_photo->file->set($file);

// And save the node
$wrapper->save();

```
> 20 votes

# Answer
My node already existed and I had to set the following parameters:

```
$wrapper->field_pdf->set(array('fid'=>$fid, 'display'=>1, 'description'=>'This is a PDF'));

```

Different set-ups may require different parameters I suppose. If you look in your error logs (admin/reports/dblog) you can see what parameters are needed.
> 5 votes

# Answer
Just in case anybody would find this helpful:

If you don't have an actual file handle and only know the `fid` you can use:

```
$wrapper->field_file->set( array( 'fid'=>1234 ) );

```

And (assuming a file with that fid exists) Drupal will attach the correct file upon `$wrapper->save()`.
> 1 votes

# Answer
You have two ways to do it:

```
// By loading the file object in any way
$file_obj = file_load($fid);
$w_containing_node->field_attachment_content->file->set( $file_obj );

// By passing an array with the fid
$w_containing_node->field_attachment_content->set( array('fid' => $fid) );

```

Here is the source of the information: https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers#example-value-set-save
> 0 votes

---
Tags: 7, files, entities
---


# Question
Title: How to post correctly fields in views-view-fields.tpl.php?
I'm using Drupal 7, and Views 3.

I would like to reproduce my comment template in `views-view-fields.tpl.php`.

Thus I need to print my fields to be able to arrange them as I wish it.

For each field, I proceed like that : `<?php print $view->render_field('field_name', $id);?>`, is it the correct/secure way ?

I don't think so, because all the row does not display.

# Answer
The correct way is:

```
<?php print $fields["field_name"]->content; ?>

```

---

**Note:** Using `views-view-fields.tpl.php` will affect all of your views, which you may not want.

To target a specific view you need to use:

**views-view-fields--\[view-name\]--\[machine-name\].tpl.php**
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: How to sort by title using Search API / fuzzy search?
In d7 i'm using fuzzysearch together with a table view for a quite long list of contacts. So far this works quite well – searching for "Mill" will list all "Miller" entries. Problem is: there is no option for sorting the results other than by *relevance*, *ID*, *content type*, *random* or *PHP*.

It would be great if the table was sortable by any of the fields – like it is possible in a regular table view – or at least by the *title* field. I'm not sure if I'm missing something – or if this is anyways not possible?

These are all the option I currently have in the sorting section of the table view:

*(sorry, screenshot is partly in german)*

All pointers / hints gladly appreciated. Thank you!

# Answer
Finally I got it working – here is how:

Search and metadata » Search API » fuzzysearch index » filter

First I checked the option "Aggregated fields" in the top section "Data alterations". Then I added an *aggregated field* that I called "Sort Name" pulling data from the field "Name".

Then I added that field to the list of indexed fields in the tab "fields". It is important to change the field type to "string" – otherwise the field won't be available for sorting.

Then finally the field should be available for sorting from the "Sort by" dialogue inside the views form.

The third paragraph of the accepted answer to the question "I have no fields available for sorting with Search API sorts module" pointed me in the right direction: "*If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type.*"

…I hope this may help somebody sometime…
> 0 votes

---
Tags: views, search
---


# Question
Title: How to hide a view if it has more than 1 row and also show some block if this is true?
I have found a solution in "Hide a view if less than N results" for hiding the view by using the template.php file.

However I need to show a certain block also, the block is already in the correct region it would just need 'switching on' for this page.

Would it be possible to provide a callback inside the following code from the link posted above

```
function MY_THEME_NAME_preprocess_views_view(&$vars) {
  if ($vars['display_id'] == 'MY_DISPLAY_ID' && count($vars['view']->result) < 1) {
    $vars['view']->result = NULL;
  }
}

```

To a function which turned the block on

Note: I am just starting module development.

edit: I'm now thinking that this would need to be done inside a custom module as it might be too late to turn the block on from the template.php file. If someone could clarify this.

# Answer
# Part 1

Enable the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".

# Part 2

As per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the number of rows returned by your view***" (so that the block is only shown if the view has more then 1 row).

For that, perform these steps:

1. Use the Views Bulk Operations module to create a variation of your view in which you add a VBO field to it.
2. Create a Rules Component with a Rules condition "***Check number of results returned by a VBO view***". And select the VBO view created in the previous step.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: create category and subcategory menu on the left sidebar
> I need a category, subcategory and subbactegory based solution for example

```
Project
    Web project
        Project 1
        Project 2
    Desktop project
        Project 1
        Project 2

```

Project 1 (when i click this then content appear on right side) Project 2 (when i click this then content appear on right side)

> Basically, when i click on the li page wouldn't be refresh. 1) i click on web project then menu expanded Project 1, project 2 appear and if i click on project 1 then content related to project 1 appear on the right side. Similarly for Project 2 and the subcategory for desktop project will be same means i can create subcategory related to desktop project.. Like in any category and product relation we need to select the category and add the product detail similarly in this

# Answer
> 1 votes
* Views Tree would be worth trying.
* Toggling of leaf terms can be handled by javascript.
* To show content, you can declare ajaxified menu callbacks, which simply takes tid as argument and replace a certain section of DOM with the server reponse.

---
Tags: navigation
---


# Question
Title: Unpublished content is displaying in entity referenced fields
I am using entity reference to refer another content type. But in the list I am getting unpublished content also. Because I have given permission to view Unpublished content, but I don't want to show them here. So how can I restrict those content from displaying in Entity referred field value.

# Answer
While adding entity reference field to the content type,

In Field Setting--\> Entity selection--\>Mode --\>Select Views and create a view by filtering only Published content, and assign the same to "View used to select the entities \*"

Hope this will help you in building views link
> 2 votes

---
Tags: 7, nodes, entities
---


title: "Radios" not creating multi options?

text:
# Question
Title: "Radios" not creating multi options?
I am creating a radio button like this:

```
$form['paymentMethodSelect'] = array(
    '#type' => 'radio',
    '#title' => $this->t('How would you like to make payment?'),
);

```

This works and creates a single radio button. Now according to documentation, to create multiple radio buttons, you change "radio" to "radios". But if I do that:

```
$form['paymentMethodSelect'] = array(
    '#type' => 'radios',
    '#title' => $this->t('How would you like to make payment?'),
    '#default_value' => 'eft',
    '#options' => [
        'eft' => 'EFT (Electronic Funds Transfer)',
        'cc' => 'Credit Card',
    ],
);

```

But if I do that then I end up with this:

Any idea why I am not seeing two radio buttons as expected?

# Answer
Your code still shows radio instead of radios for `'#type'` attribute.

```
$form['paymentMethodSelect'] = array(
    '#type' => 'radios',
    '#title' => $this->t('How would you like to make payment?'),
    '#default_value' => 'eft',
    '#options' => [
        'eft' => 'EFT (Electronic Funds Transfer)',
        'cc' => 'Credit Card',
    ],
);

```

Otherwise there is no other problem I see in your code.
Sample code from D.O

```
$form['settings']['active'] = array(
  '#type' => 'radios',
  '#title' => $this->t('Poll status'),
  '#default_value' => 1,
  '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
);

```
> 1 votes

---
Tags: forms, 8
---


title: Pending approval mail not sent

text:
# Question
Title: Pending approval mail not sent
Am using the register module to create an alternate registration page which requires admin approval. The pending approval mail is not sent to the user registering through the page.

Wish someone could help me here. I've also created an issue in the module page. Thanks

The problem is not with the module. The pending approval mails are not sent even registering with default drupal path while rest of the mails are delivered.

# Answer
> 0 votes
Check these variables:

```
user_mail_register_admin_created_notify
user_mail_register_no_approval_required_notify
user_mail_register_pending_approval_notify
user_mail_status_blocked_notify
user_mail_cancel_confirm_notify
user_mail_status_canceled_notify

```

Use drush (`drush vget user_mail_register_no_approval_required_notify`) or install Mail Control; This module provide only interface modifications. The underlying functionality is already there by default in Drupal 7.

You can also drop in `settings.php`:

`$conf['user_mail_register_admin_created_notify'] = FALSE;
$conf['user_mail_register_no_approval_required_notify'] = FALSE;
$conf['user_mail_register_pending_approval_notify'] = FALSE;
$conf['user_mail_status_activated_notify'] = FALSE;
$conf['user_mail_status_blocked_notify'] = FALSE;
$conf['user_mail_cancel_confirm_notify'] = FALSE;
$conf['user_mail_status_canceled_notify'] = FALSE;`

---
Tags: 7, users
---


# Question
Title: Checkboxes, Radios, 'select or other' wont render inside table select element
I want to render elements of type checkboxes or radios inside tableselect, but what I get are empty html tags. Textfield and select type elements render fine.

Basically this renders fine.

```
$tableSelectTesting = array(
  '#type' => 'select',
  '#options' => array(
    "1000" => "$1000",
    "other" => t("Other"),
  ),
);

```

This does not.

```
$tableSelectTesting = array(
  '#type' => 'radios',
  '#options' => array(
      "1000" => "$1000",
      "other" => t("Other"),
    ),
);

```

I add the form element to table select using the 'data' array key.

```
$options[$index] = array(
    'column1' => $column1Data,
    'column2' => array(
      'data' => $tableSelectTesting,
    )
  );

```

This is the output I get for the radios element.

```
<td><div id="some-id" class="form-radios"></div></td>

```

What should I be doing differently?

# Answer
> 0 votes
I believe you are missing some details in the way you structure your data. Check this example, specifically the data array tree.

Also, check the structure of the array that defines the tableselect. For radios it should look like this:

```
$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

```

(the #multiple property is the one that defines whether these are checkboxes or radios)

Your data in the array `$options` should look something like this:

```
$options = array(
  '1000' => array(
      'field_price' => '$1000',
  ),
  'other' => array(
      'field_price' => 'Other',
  ),
);

```

Notice the nested structure, and the field name (this could be anything, but it needs to exist, one for every column of the table, starting with the second column.

---
Tags: 7, forms
---


# Question
Title: How do I avoid duplicates when using a reference field?
I have a content type with an entity reference field. If I have more then one entity in this field, and display the field in a view, it displays duplicates.

Anyone figured out how to remove these duplicates in Drupal 8?

# Answer
I removed the duplicates using hook\_views\_pre\_render().

```
function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $filtered_nids = array();

    foreach ($view->result as $key => $row) {
      if (in_array($row->nid, $filtered_nids)) {
        unset($view->result[$key]); // remove the duplicate
      } else {
        $filtered_nids[] = $row->nid;
      }
    }
  }
}

```

Probably not the best solution, but it works for my case.
> 3 votes

---
Tags: views, 8
---


# Question
Title: Node's teaser view mode has extra "panels-default" markup/wrapper/classes
I'm using bootstrap 3 as basetheme and Physics as main. On content types view mode (teaser) I've created a Horizontal tabs group and added 3 Horizontal tab containers under it.

The problem is that content inside Horizontal tab is wrapped with Bootstrap panel markup which creates unnecessary borders and shadows. I can't find that where this is defined.

And since Horizontal tabs and Horizontal tab aren't part of either themes or supporting modules it seems weird that content is wrapped in any bootstrap markup.

Result

View mode/containers setup

**UPDATE**

The question is that why are these fields wrapped with a bootstrap panel markup?

# Answer
Copy bootstrap-panel.tpl.php from base to main and configure it per requirements.
> 0 votes

---
Tags: theming, display-suite
---


title: Feed mapping problem

text:
# Question
Title: Feed mapping problem
I want to create the following mapping for a product node: This is extracted and amended from an existing feed.

```
    'mappings' => array(
    0 => array(
      'source' => 'SKU',
      'target' => 'guid',
      'unique' => 1,
      'language' => 'und',
    ),
    1 => array(
      'source' => 'SKU',
      'target' => 'field_product:sku',
      'unique' => FALSE,
      'language' => 'und',
    ),
    2 => array(
      'source' => 'title',
      'target' => 'title',
      'unique' => FALSE,
      'language' => 'und',
    ),
    3 => array(
      'source' => 'body',
      'target' => 'body',
      'unique' => FALSE,
      'language' => 'und',
    ),
    4 => array(
      'source' => 'Group',
      'target' => 'field_product_category',
      'unique' => FALSE,
      'language' => 'und',
    ),
    5 => array(
      'source' => 'length',
      'target' => 'field_dimensions_length',
      'unique' => FALSE,
      'language' => 'und',
    ),
    6 => array(
      'source' => 'width',
      'target' => 'field_dimensions_width',
      'unique' => FALSE,
      'language' => 'und',
    ),
    7 => array(
      'source' => 'height',
      'target' => 'field_dimensions_height',
      'unique' => FALSE,
      'language' => 'und',
    ),
    8 => array(
      'source' => 'unit1',
      'target' => 'field_dimensions_unit',
      'unique' => FALSE,
      'language' => 'und',
    ),
    9 => array(
      'source' => 'weight',
      'target' => 'field_weight_weight',
      'unique' => FALSE,
      'language' => 'und',
    ),
    10 => array(
      'source' => 'unit2',
      'target' => 'field_weight_unit',
      'unique' => FALSE,
      'language' => 'und',
    ),

```

The first five items are OK and will map via nodes, the others, from 5 to 10 will not. When I go to /Admin/Content/Settings/Content types/Product display/Manage Fields The field\_weight element and field\_dimensions elements are clearly shown. How can I amend the node mapping to take these fields into consideration.?

# Answer
Based on your code, I believe you are working on eCommerce website.

I think you need to change your **target value** to:

> 'field\_dimensions:length', 'field\_dimensions:width', 'field\_dimensions:height', 'field\_dimensions:unit','field\_weight:weight','field\_weight:unit'
> 0 votes

---
Tags: nodes, commerce, feeds, importing-exporting
---


# Question
Title: How to avoid missing status for Workflow access module permission just after node creation?
I am using Workflow 7.x-2.8 to manage peer-reviewing publication.

When an authenticated user (an author) creates a post, he can choose a first workflow state transition from creation (by default) to draft. This draft is visible only for author and admin. This draft can be edited only by the author.

The sub-module Workflow Access allows me to manage permissions for each workflow state, which is really great. But, apparently, I have a problem with the first status assignment with Workflow Access (priority = 1).

Indeed, according to Devel Node Access module (DNA) debug mode, the status is not in node\_access table and I need to rebuild permissions to clear the issue (which is OK for dev website but of course, it is not OK for production website).

When the permissions are rebuilt, everything is fine and the node\_access table seems to be OK. Further, when the author decides to change the post to another workflow state (draft TO submitted), the permissions are correctly modified and the author can not edit the post anymore (pending approval).

Last detail : the content type related to this workflow is not published, by default.

I add a DNA screenshot and I hope everything is clear.

# Answer
> 0 votes
Just had the same problem for me, but for a custom hook\_node\_access\_records().

For me the solution to implement the hook\_node\_grants(). and clear the cache.

Once you use the hook\_node\_access\_records, you have to implement the hook\_node\_grants.

---
Tags: users, debugging, workflows
---


# Question
Title: Grouping data to be displayed in the a template.
I have the following related Content types:

I am creating a view to get the following output

* Resource Title
* Resource Type. (If type is Quiz, then also show the following data)
    + Quiz Title
        - Option Title 1
        - Option Title 2

Currently, i am getting the following output

* Resource Title
* Resource Type
* Quiz Title
* Option Title 1
* Resource Title
* Resource Type
* Quiz Title
* Option Title 2

How can I group the data in the templates to get the desired result?

Thanks

# Answer
An approach I have used at the moment is to use a preprocess hook in my template. Added the following preprocess template to a custom module

THEMENAME\_preprocess\_views\_view\_unformatted\__PAGENAME(&$variables)

where variable is an array containing \- view : the view object \- rows : an array of row items and each row is an array of content.

I looped over the data and constructed my required object, which then I set as a new property resource (i.e. $variables\['resource'\]) of variables.

Within the template (views-view-unformatted--PAGENAME.html.twig), I then have access to the resource variable to use in the twig template. e.g {{ resource.type }} , where type is a property added to the resource variable in the preprocess hook.

Not sure if this is the best way to approach the problem, but at least it is one way of approaching the problem.
> 0 votes

---
Tags: views, theming
---


# Question
Title: Base table not found ... my_site.key_value_expire doesn't exist
I was having some issues with syncing a site to Acquia via their devdesktop application, and so I started doing some troubleshooting -- including trying to copy the database over to a new site. At some point during the process, I must have installed/uninstalled something that the site didn't like. The frontend of the site is still functional, but the admin side is toast, giving me the `"The website encountered an unexpected error. Please try again later."` error on every page. I tried repairing the `key_value` table, but phpmyadmin fails, stating that `"The storage engine for the table doesn't support repair"`.

I've seen suggestions in other similar issues on how to properly drop and recreate this table. I'm hoping that somebody can provide similar help here, assuming that that is the issue.

If it's helpful, here's the full log that is returned via drush when I try to do something like `drush pm-disable modulename`. I have the feeling that it's mostly not applicable to this issue, but I figured it wouldn't hurt to include it.

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jakesfireworksdev_dev.key_value_expire' doesn't exist in                                                                                [error]
/Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Statement.php:59
Stack trace:
#0 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Statement.php(59): PDOStatement->execute(Array)
#1 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php(610): Drupal\Core\Database\Statement->execute(Array, Array)
#2 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('DELETE FROM {ke...', Array, Array)
#3 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Query/Delete.php(55): Drupal\Core\Database\Driver\mysql\Connection->query('DELETE FROM {ke...', Array, Array)
#4 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/KeyValueStore/DatabaseStorage.php(165): Drupal\Core\Database\Query\Delete->execute()
#5 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(642): Drupal\Core\KeyValueStore\DatabaseStorage->deleteAll()
#6 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(258): update_storage_clear()
#7 [internal function]: update_themes_uninstalled(Array)
#8 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('update_themes_u...', Array)
#9 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeInstaller.php(269): Drupal\Core\Extension\ModuleHandler->invokeAll('themes_uninstal...', Array)
#10 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeHandler.php(173): Drupal\Core\Extension\ThemeInstaller->uninstall(Array)
#11 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(320): Drupal\Core\Extension\ThemeHandler->uninstall(Array)
#12 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(83): drush_theme_uninstall(Array)
#13 /Users/mrweiner/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1237): _drush_pm_uninstall(Array)
#14 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_uninstall('rdfui')
#15 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#16 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('rdfui')
#17 /Users/mrweiner/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#18 /Users/mrweiner/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#19 /Users/mrweiner/.composer/vendor/drush/drush/drush.php(12): drush_main()
#20 {main}

Next Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'jakesfireworksdev_dev.key_value_expire' doesn't exist: DELETE FROM {key_value_expire}
WHERE  (collection = :db_condition_placeholder_0); Array
(
    [:db_condition_placeholder_0] => update
)
 in /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php:671
Stack trace:
#0 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Connection.php(635): Drupal\Core\Database\Connection->handleQueryException(Object(PDOException), 'DELETE FROM {ke...', Array,
Array)
#1 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php(81): Drupal\Core\Database\Connection->query('DELETE FROM {ke...', Array, Array)
#2 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Database/Query/Delete.php(55): Drupal\Core\Database\Driver\mysql\Connection->query('DELETE FROM {ke...', Array, Array)
#3 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/KeyValueStore/DatabaseStorage.php(165): Drupal\Core\Database\Query\Delete->execute()
#4 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(642): Drupal\Core\KeyValueStore\DatabaseStorage->deleteAll()
#5 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/modules/update/update.module(258): update_storage_clear()
#6 [internal function]: update_themes_uninstalled(Array)
#7 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ModuleHandler.php(402): call_user_func_array('update_themes_u...', Array)
#8 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeInstaller.php(269): Drupal\Core\Extension\ModuleHandler->invokeAll('themes_uninstal...', Array)
#9 /Users/mrweiner/Sites/devdesktop/jakesfireworksdev-dev/docroot/core/lib/Drupal/Core/Extension/ThemeHandler.php(173): Drupal\Core\Extension\ThemeInstaller->uninstall(Array)
#10 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/environment.inc(320): Drupal\Core\Extension\ThemeHandler->uninstall(Array)
#11 /Users/mrweiner/.composer/vendor/drush/drush/commands/core/drupal/pm_8.inc(83): drush_theme_uninstall(Array)
#12 /Users/mrweiner/.composer/vendor/drush/drush/commands/pm/pm.drush.inc(1237): _drush_pm_uninstall(Array)
#13 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(422): drush_pm_uninstall('rdfui')
#14 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#15 /Users/mrweiner/.composer/vendor/drush/drush/includes/command.inc(199): drush_command('rdfui')
#16 /Users/mrweiner/.composer/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#17 /Users/mrweiner/.composer/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#18 /Users/mrweiner/.composer/vendor/drush/drush/drush.php(12): drush_main()
#19 {main}

```

# Answer
> 0 votes
It turns out that the table I was attempting to repair was `key_value`, and not `key_value_expire` which is what was throwing the error. I'm not sure what happened to the table, but it seems like something caused it to be deleted. I was able to import the `key_value_expire` table from another database and the error halted.

---
Tags: 8, database, drush
---


# Question
Title: Drupal 8, don't automatically execute the view after the first load of the view page
I created a view page from the admin interface. Then when I go to the view page url with my browser, the view is displayed and show automatically some results.

Now, I want force the user to click on the execute view button for display results. I mean, the user go to the view page url, only exposed filters are displayed, he must click on the view submit button for display results of the view.

It's possible to configure that from the view interface configuration (I didn't find..) or I must use a custom module ? (and how?)

Thanks you :)

# Answer
> 0 votes
I find from the view ui how configure for "force" the user to submit the view for show results ! In the view ui, to the right (in the advanced settings), click on "exposed form style" and choose "Input required" :)

---
Tags: views, 8
---


# Question
Title: How to send node as body content in email using Rules?
I wonder if there is a way of inserting the contents of a node into the body of the email when using the Rules module?

# Answer
It depends on the Rules Event that your rules is using ... e.g.:

* If Rules Event is something like "*After updating existing content*", then you'll be able to use token `[node:body]` within (eg) the message body of Rules action "send eMail".
* If Rules Event is (eg) "*After updating an existing user account*" then token `[node:body]` is not available for using it within (eg) the message body of Rules action "send eMail".
> 0 votes

---
Tags: 7, rules, emails
---


# Question
Title: Fivestar: How to display description text inline
By default, the Fivestar module offers (at Structure » Content types » Article » Manage Display » Fivestar settings) to show "Text to display **under** the stars". It looks then like this:

How to show the description text **inline beside** the stars?

I wasn't able to do that in CSS (or to find the caused code in the module).

# Answer
> 0 votes
It's doable with CSS. You need to declare the parent of the description and the stars as flex or inline-flex or -webkit-inline-box: .field-type-fivestar .form-item { display: -webkit-inline-box; }

---
Tags: rating
---


# Question
Title: Drupal\Component\Plugin\Exception\PluginNotFoundException after upgrading drupal
I tried to upgrade from version 8.0.x to 8.1.x. I used drush with the command `drush up drupal`.

The output shows some errors:

```
Do you wish to run all pending updates? (y/n): y
The "block_visibility_group" entity type does not exist.                                                                                [error]
Performing system_update_8200                                                                                [ok]
Performing block_content_update_8003                                                                                [ok]
Performing path_update_8200                                                                                [ok]
Performing views_update_8200                                                                                [ok]
PHP Fatal error:  Uncaught Error: Class name must be a valid object or a string in /Applications/MAMP/htdocs/drupal8.com/core/modules/field/src/FieldStorageConfigStorage.php:155
Stack trace:
#0 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(189): Drupal\field\FieldStorageConfigStorage->mapFromStorageRecords(Array, Array)
#1 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Entity/EntityStorageBase.php(242): Drupal\Core\Config\Entity\ConfigEntityStorage->doLoadMultiple(Array)
#2 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Entity/Entity.php(507): Drupal\Core\Entity\EntityStorageBase->loadMultiple(Array)
#3 /Applications/MAMP/htdocs/drupal8.com/core/modules/field/field.module(181): Drupal\Core\Entity\Entity::loadMultiple(Array)
#4 [internal function]: field_entity_field_storage_info(Object(Drupal\Core\Entity\ContentEntityType))
#5 /Applications/MAMP/htdocs/drupal8 in /Applications/MAMP/htdocs/drupal8.com/core/modules/field/src/FieldStorageConfigStorage.php on line 155

```

After the update I just keep getting the following error on all pages:

> The website encountered an unexpected error. Please try again later.
>
> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "page\_variant" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager-\>getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I know this has something to do with the `page_manager` module. But actually I'm a bit helpless what I can try to resolve this problem. I even have no clue why this problem does occur. The page\_manager module is still in the `/modules` folder.

# Answer
That means you have a field with an unknown field type. Are you sure that you're not missing any modules that you used to have installed? And the the missing entity type sounds like you used to use https://www.drupal.org/project/block\_visibility\_groups but now it's gone?

My guess is that you accidently removed all/some contrib modules before updating, which you shouldn't do. Minor updates are like any other normal core update, except they come with some more changes.
> 2 votes

---
Tags: 8, updating, upgrading
---


# Question
Title: Remove HTML element when pasting from Word
I am pasting a GDoc content using "paste from word" button on the ckeditor (4.5.4) and I want to remove the extra `span` **with** `style` associated with links in the text (so that it uses my theme css).
Here is how a link is styled after pasting to ckeditor:

```
<a href="http://en.wikipedia.org/wiki/Neil_Armstrong" style="text-decoration:none;">
   <span style="text-decoration:underline;vertical-align:baseline;white-space:pre-wrap;">
     <span style="color:#1155cc;">
       <span style="font-family:arial;">
         <span style="font-size:14.6667px;">Neil Armstrong</span>
       </span>
     </span>
   </span>
</a>

```

I want it to be just

```
<a href="http://en.wikipedia.org/wiki/Neil_Armstrong" style="text-decoration:none;">Neil Armstrong</a>

```

I tried in ckeditor profile under **Advanced options**:

```
config.allowedContent = true;
config.disallowedContent = 'span {color, font*, text-decoration}';

```

This is not working!

# Answer
I end up removing the code from the custom javascript configuration in ckeditor profile (picture above) (http://localhost/admin/config/content/ckeditor/edit/Full).

```
config.allowedContent = true;
config.disallowedContent = 'span {color, font*, text-decoration}';

```

I updated my ckeditor config file:
/docroot/sites/all/modules/contrib/ckeditor/ckeditor.config.js with this:

```
 config.allowedContent = {
$1: {
    // Use the ability to specify elements as an object.
    elements: CKEDITOR.dtd,
    attributes: true,
    styles: true,
    classes: true
   }
};
config.disallowedContent = 'span; u; p h1 h2{line*,margin*}; *[dir]';

```

I added `u; p h1 h2{line*,margin*}; *[dir]` to get rid of other attributes:

```
<h1 dir="ltr" style="line-height:1.38;margin-top:24pt;margin-bottom:6pt;">Apollo 11</h1>
<p dir="ltr" style="line-height:1.38;margin-top:0pt;margin-bottom:0pt;">was the spaceflight that landed the first humans, Americans</p>

```

gives

```
<h1>Apollo 11</h1>
<p>was the spaceflight that landed the first humans, Americans</p>

```

Hope this helps someone!
> 0 votes

# Answer
Hi You can use https://www.drupal.org/project/wysiwyg\_filter and configure him in /admin/config/content/ckeditor , content types
> 0 votes

---
Tags: 7, wysiwyg
---


title: Set translated field

text:
# Question
Title: Set translated field
I'm having some trouble finding how to handle field translations in the documentation.

I have a requirement to keep certain fields in English and Japanese. I periodically have to update nodes and taxonomy terms programmatically. I'm doing this with a combination of EntityQuery and the Entity class.

Is there a set function that takes a language code? For example;

```
$term->set('field_my_field', 'my value', 'ja');

```

# Answer
You update another translation by getting an object for that language, and then you set the values of those fields.

```
$translation->set('field_my_field', 'my en value');
$translation = $term->getTranslation('ja');
$translation->set('field_my_field', 'my ja value');
$translation->save();

```

Those translation objects are actually shallow clones that have a different internal active language code, so you can update multiple translations and then save, for example.
> 8 votes

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


# Question
Title: Show/Hide fields not working for Condition Fields on node display
I have Conditional fields installed, with a checkbox as the dependency which shows two textareas when checked. The issue is when viewing the content type, the checkbox is NOT checked and the text areas still show up. I have checked in `Manage Dependencies` and the dependants are required and visible when checkbox field is checked.

Is there another place to adjust these settings, if so where would I look?

# Answer
This is a quirk of the module, per the documentation on the view context:

> The "Value", "Filled" and "Empty" conditions are special: they are the only conditions that have ANY effect on form validation and content view.

If you want to show/hide fields with the module during content display, you'll need to set the **Condition** to *Value* and the according value for your checkbox.
> 2 votes

---
Tags: entities
---


title: How to uninstall MailChimp

text:
# Question
Title: How to uninstall MailChimp
Please help me uninstall MailChimp.

I disabled all MailChimp component modules, then I clicked uninstall. I got no error messages.

I then deleted the MailChimp folder from Sites/All.

Finally I ran phpMyAdmin and searched for MailChimp. I then deleted everything having MailChimp in it, BUT MailChimp still appears (though disabled) when I click modules.

I'm trying to get rid of MailChimp because it does not work and because SimpleNews does not work. I'm think that they are fighting each other.

I'm using Adquia Dev Desktop on my Win 7 computer with Open Outreach distribution.

Thanks!

# Answer
> 0 votes
Are you sure you got all the module files? Normally they are placed in 'sites/all/modules' not 'sites/all' perhaps this was only the mailchimp library? But that should have been in 'sites/all/libraries'.

Did you flush the caches? This can be done via 'admin/config/development/performance'. Because it sounds like you deleted everything.

Disabled modules don't really cause any problems, is there a reason why you want to delete it fully?

# Answer
> 1 votes
The module will continue to be listed on the /admin/modules page as long as Drupal detects it on your filesystem within /sites/all/modules, /sites/default/modules, or another folder under /sites if you're running a multi-site setup. Just because the module is listed there doesn't mean it is enabled and running on the site.

Uninstalling modules is usually done the way you described it in the first line of your post. You go to /admin/modules to disable modules, then onto /admin/modules/uninstall to uninstall them. If the developer of the module did it correctly, you shouldn't have to do anything more than that. You will still see it listed in the modules page because it is still on your filesystem

I wouldn't recommend manually deleting anything out of the database unless you know exactly what it is that you're doing. You could mess things up When you disable and uninstall modules through the Drupal interface (or Drush), there are certain hook functions that get called which should remove data from the database.

What I would do is first is locate the module folder containing MailChimp. Ensure that you only have it in one place. If you had the module in different folders and only delete one, it will still be listed on the admin/modules page.

If you don't see it in those folders, re-install it. Then properly disable and uninstall it again the way you described WITHOUT touching the database yourself. This will probably undo any damage you could have caused in the database and ensure that the data in the database is properly cleared out. Afterwards, delete the module folder from the filesystem and it should be gone.

# Answer
> 0 votes
Check your field list (/admin/reports/fields) and remove any Mailchimp Subscription fields you find.

---
Tags: installation
---


# Question
Title: How to prevent a rule to be triggered inside a rule?
I'm using the Rules module and I have two rules:

* A: When flagged, 'Post a journal entry to the ledger'
* B: When unflagged, 'Remove journal entry from the ledger'

Rule A includes also two Rules components with conditions that check if the journal entry is balanced:

If the condition 'balanced' is true: \- Post journal entry to the ledger.

If the condition 'unbalanced' is true: \- Show a warning on the page and UNFLAG the journal entry.

The problem is that I don't want the Rule B to be triggered inside rule A, which currently happens.

Theoretically I could add a condition to Rule B like 'is balanced' but I don't want to modify other rules in order to prevent the execution of a rule inside a rule.

Is it possible to prevent nested Rules from firing?

# Answer
> 1 votes
This is a workaround solution.

You could add a boolean field to your journal entry content type. Side note, you could use the Field Permission module to hide the boolean field from the add/edit form.

Alternatively, if you're not using the sticky system, you could use that instead.

So now all you gotta do is add a **condition** to your **Unflag Rule**.

* **Boolean is false**/unchecked OR content **is unsticky**.

---

Now in your Component Action add:

* Set a data value and make your boolean True/checked OR Make content sticky
* Unflag node
* Set a data value and make your boolean false/unchecked OR Make content unsticky

### Voilà!!! your component will not trigger your unflag rule.

# Answer
> 0 votes
You may get closer (= simplify your Rules logic) by ALSO using the Conditional Rules module. Some more details about this module (from its project page):

> ... provides Rules plugins for conditionally altering execution flow directly inside a group of **actions**.

Here is a screenprint of a rule with an action that uses Conditional Rules (though only with an "if"-part here, no "else"):

For a sample using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

# Answer
> 0 votes
Sometime you need to prevent the next rules from executing.

* In your rule, you can add an action "Execute custom PHP code"

You can put this code to redirect to a different page rightaway without execute the next rule.

```
-------------------------
header("location:/");
exit;
--------------------------

```

The above code will do a page redirect to the home page and that's it.

The rest of the rules will never get execute.

---
Tags: rules
---


# Question
Title: How to remove the "Save" button from checkout cart summary form?
On the first checkout page (`checkout/xx/checkout`), there is a view which displays line items for the order. The view appears to be named *"Shopping cart summary (Commerce Order)"*

When I add the standard `Delete` button to the view (for deleting line items), it causes a `Save` button to appear below the line items.

How do I remove that `Save` button?

**Update:**

I tried a form-specific `hook_form_alter()`, but didn't find the `Save` button in the `$form` array. It appears to be a form embedded in another form. Reading answer from @Yogesh made me realize that maybe I had the wrong `$form_id` and can debug with a general `hook_form_alter()` and look for a nested call for the embedded form.

# Answer
One way of doing this is implementing hook\_form\_alter and hiding save button. Check example below:

```
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID') {
    // Set access to FALSE will prevent rendering form element on form.
    // Check the hierarchy of 'Save' button, before using #access.
    $form['actions']['save']['#access'] = FALSE;
  }
}

```
> 4 votes

---
Tags: commerce
---


# Question
Title: Accessing a block types content programatically
I have created a block type in the drupal 8 UI (structure/block/block-content/types ) that has two fields that are just strings. I then created 4 pieces of content using that block\_type. How do I access the content created by the block type in hook\_preprocessor\_html programmatically?

# Answer
This is a cutdown version of the function to access the block entities.

```
function _access_content_block_fields_build_arr($bidArr, $fieldRequestArr)
{

    $return = array();
    $blockElements = array();
    $blocks = \Drupal\block_content\Entity\BlockContent::loadMultiple($bidArr);
    foreach ($blocks as $block) {
        foreach ($fieldRequestArr as $fieldRequest) {
            $blockResult = $block->get($fieldRequest)->getValue();
            $blockElements[$fieldRequest] = $blockResult[0];
        }
        $return[] = $blockElements;
    }

    return $return;
}

```

purencool.com/accessing-a-block-types-content-programatically is the entire function for image fields url as well
> 0 votes

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


# Question
Title: fields.title.content in views-view-fields--n--block.html.twig won't display
This is what I wrote into **views-view-fields--n--block.html.twig**. The second and third fields are displayed properly *(here I used the machine name)*. But how do I get the title which is automatically there with every content type?

```
<div class="field-1">
<h1> {{ fields.title.content}}</h1>
{{ fields.field_news_bild.content }}<br>
{{ fields.body.content}}</div>

```

please help!

# Answer
Just found out that my title fields' name is title\_1.

this is what brought the solution:

```
 <ol>
    {% for key, field in fields %}
        <li>key: {{ key }}</li>
    {% endfor %}
</ol>

```

This shows all fields from the view in the template file.
> 0 votes

---
Tags: theming, entities
---


# Question
Title: Views exposed filter and non latin characters
I have a combined text box exposed filter of a view. Is there any way that I can alter the keywords used by the user to convert non-latin characters to latin using hook\_views\_query\_alter?

# Answer
> 0 votes
Transliteration module has some useful functions to convert unicode strings into latin strings. You may give it a try and use some of those functions in your alter hooks. I cannot give you a specific function name but I'm sure that I've used this module for a similar purpose.

Anyway, if you work with non-latin languages, you'll probably need to install this module for other purposes, like fixing the filenames and url parts generated by user input etc.

A quick look-up into the source code of Transliteration module, I can say that you can use `transliteration_get()` function to transliterate a give string. A sample implementation for your case would be:

```
function YOUR_MODULE_views_query_alter(&$view, &$query) {
  // To debug comment out the following line (Devel module is required).
  //dpm($query);

  if ($view->name = 'YOUR_VIEW' && !empty($view->exposed_raw_input['YOUR_FIELD']) {
    $transliterated = transliteration_get($view->exposed_raw_input['YOUR_FIELD']);
    // Traverse through the 'where' part of the query.
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        // If this is the part of the query filtering on your field, change the
        // condition value to the transliterated string.
        if ($condition['field'] == 'YOUR FIELD') {
          $condition['value'] = $transliterated;
        }
      }
    }
  }
}

```

---
Tags: 7, views
---


# Question
Title: How to write a rule for 'After sending email'?
I have to write a rule for the event 'After sending email'. How can I do that?

For example there are three users user1, user2, user3. I need to enable a flag on a content type after admin sending email to those three users.

# Answer
There is no Rules ***Event*** like "\*after sending eMail". However, you can create a Rules ***Component*** for sending an eMail. For a sample of such Rules Component, refer to the answer to "Rule to store user's last post date and scheduled rule based 30 day reminder".

If you then "***invoke this Rules component***" any time a rule has to send an eMail, you basically created the equivalent of the Rules Event you're asking for. All that's left to do is to expand that Rules Component with additional Rules logic that you want to happen "*after sending eMail*" (... as in your question).
> 0 votes

---
Tags: rules
---