# Question
Title: Implementing an age check using InboundPathProcessorInterface
I'm trying to create an age checker for a Drupal 8 site.

I've created a custom module which has a form where the user enters their DOB and my form submit saves a cookie so I know they have passed the age check. Code is as follows:

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $day = $form_state->getValue('day');
  $month = $form_state->getValue('month');
  $year = $form_state->getValue('year');

  $timezone = new \DateTimeZone('Africa/Johannesburg');
  $age =
    \DateTime::createFromFormat('d/m/Y', $day . '/' . $month . '/' . $year,
      $timezone)->diff(new \DateTime('now', $timezone))->y;

  if ($age < '18') {
    // if less than 18 display the age_check.fail route
    $url = Url::fromRoute('age_check.fail');
    $form_state->setRedirectUrl($url);
  } else {
    // set cookie so we know this user has passed the age check
    setcookie('age_checked', 1, time()+3600, '/');

    $original_path = $_COOKIE['age_checked_prev_path'];

    if (!empty($original_path) && $original_path != '/') {
      $redirect_url = Url::fromUserInput($original_path);
      // Add a redirect to requested page. Using $form_state built in redirects.
      $form_state->setRedirectUrl($redirect_url);
    } else {
      // For everything else, redirect to homepage.
      $form_state->setRedirect('<front>');
    }
  }

}

```

Cool that is working fine i get redirected to a age-check-fail page if under 18. If over 18 I should be redirected back to the page I originally wanted to go to. Now I've tried to implement this using a Path Processor.

```
   /**
   * Path processor for age_check.
   */
class AgeCheckPathProcessor implements InboundPathProcessorInterface {

/**
 * {@inheritdoc}
 *
 */
public function processInbound($path, Request $request) {
  $alias_manager = \Drupal::service('path.alias_manager');
  $request_alias = $alias_manager->getAliasByPath($request->getRequestUri());
  // set cookie with original request path
  setcookie('age_checked_prev_path',$request_alias, time()+3600, '/');

  //get all cookies
  $cookies = $request->cookies->all();

  if(!array_key_exists('age_checked', $cookies) && empty($cookies['age_checked'])){

      // paths to skip age check
      $skip_path = [
        0 => '/admin',
        1 => '/user',
        2 => '/user/login',
        3 => '/age-check',
        4 => '/age-check/fail'
      ];

      // loop through each skip path and if match to current request return it
      foreach ($skip_path as $key => $path) {
        $url = trim($path);
        $url_alias = $alias_manager->getAliasByPath($url);

        if ($url == $request_alias || $url_alias == $request_alias) {
          // Leave $path intact.
          return $request_alias;
        }
      }

    // show the age check page.
    return '/age-check';
  }
  return $request_alias;
}

```

This isn't working as intended. One main problem is that coming from the home page, submitting the age check form correctly it still redirects me back to the age check form, if i then enter the url to an article I am allowed access to the site as intended, but trying to go back to the home page still shows the age checker form.

Am I using the Inbound Path Processor class correctly?

# Answer
> 3 votes
**service:**

```
  blah.preserved_system_paths_redirect:
    class: Drupal\blah\Redirect\PreservedSystemPathsRedirect
    tags:
      - { name: event_subscriber }

```

--

```
<?php

/**
 * @file
 * Contains \Drupal\blah\Redirect\PreservedSystemPathsRedirect.
 */

namespace Drupal\blah\Redirect;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\RouteMatch;

/**
 * Class PreservedSystemPathsRedirect.
 */
class PreservedSystemPathsRedirect implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST] = 'checkSystemPaths';
    return $events;
  }

  /**
   * Redirect from original system paths to their new locations.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkSystemPaths(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();

    switch ($route_name) {
      // Regional settings are now available in the blah/site settings form.
      case 'system.regional_settings':
      // Maintenance mode is now available in the blah/site setting form.
      case 'system.site_maintenance_mode':
        $url = \Drupal::url('blah.settings');
        break;
    }

    if (isset($url)) {
      $returnResponse = new RedirectResponse($url, Response::HTTP_MOVED_PERMANENTLY);
      $response->setResponse($returnResponse);
    }
  }

}

```

---
Tags: 8, path-aliases, redirection, cookies
---


# Question
Title: How do I replace a string when using hook_node_view()?
I am trying to use `hook_node_view()` to replace, in the front page, `<div>:placeholder1:</div>` with the content of `$string`.

```
function mymodule_node_view(&$node, $view_mode, $langcode){
  $string = "I am here";
  $node->field_column_second['und'][0]['value']['#markup'] = array(
     '#markup' => str_replace(':placeholder1:', $string, $node->field_column_second['und'][0]['value'])
);

```

I also cleared Drupal cache, but I don't see any change.

What am I doing wrong?

# Answer
> 0 votes
1. According to the doc, the first parameter should be $node, rather than &$node.
2. The replacement code should look something like this: `$node->content['body'][0]['#markup'] = str_replace($old, $new, $subject);` so you missed \[0\] in your code, when in doubt, do a `dsm($node)` and check the variable you want.
3. Complete code:

`function test_node_view($node, $view_mode, $langcode){
 if (drupal_is_front_page()) { // check if necessary
 $string = "new";
 $node->content['body'][0]['#markup'] = str_replace('old', $string, $node->content['body'][0]['#markup']);
 }
 //dsm($node);
}`

---
Tags: nodes, hooks
---


# Question
Title: How to create a multisite from an existing Drupal site
I have an existing drupal 7 site that we want to convert into a multi site. I want the new database to have the same content structure as the existing site. What would be the steps I have to take?

# Answer
> 0 votes
with Acquia dev desktop , you can click on "More" at the bottom and create a multisite from an existing site. Other wise I also found this https://www.drupal.org/project/multisite\_wizard

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


# Question
Title: Theming mini panel using MYTHEME_preprocess_panels_pane
I'm trying to edit the content of a mini panel using MYTHEME\_preprocess\_panels\_pane but when I use Devel to dsm $variables, I just get data for the pane that holds the mini panel.

Is there a function to get into the mini panel?

At first I thought hook\_panels\_pane\_content\_alter might work but I'm getting nothing when I drop it into my template.php

# Answer
> 0 votes
You can get at the content on a mini panel using hook\_panels\_pane\_content\_alter.

It needs to be called in a custom module (see https://www.drupal.org/developing/modules/7)

---
Tags: 7, theming, panels
---


# Question
Title: How do I use Gitlab server as a central staging server?
I just installed a Gitlab instance on my LAN.

I want to use it as the central repository for a Drupal dev-\>test-\>prod staging setup.

So, 1st step, I want to push my local "dev" workspace to the Gitlab repo.

Following instructions at Gitlab docs, I try

```
cd ./drupal8
git remote add origin https://gitlab.example.com/user1/drupal8-test.git

```

But that fails and returns

```
fatal: remote origin already exists.

```

Checking in the drupal dir

```
cd ./drupal8
git remote -v
    composer        https://github.com/drupal-composer/drupal-project.git (fetch)
    composer        https://github.com/drupal-composer/drupal-project.git (push)
    origin  https://github.com/drupal-composer/drupal-project.git (fetch)
    origin  git@github.com:drupal-composer/drupal-project.git (push)

```

I want to be able to push to the Gitlab repo, but I still obviously want composer etc to work in my dev env.

What's the right setup & workflow for using Drupal with a central Gitlab repo, making sure that I keep the ability to manage my site in 'dev' with composer?

# Answer
> 3 votes
Usually, people set up a remote named "upstream" for the source, in this case it would be https://github.com/drupal-composer/drupal-project.git. Remote "origin" should be the git URL of your Gitlab repo. So for you, here is a sample workflow:

The setup:

```
git remote rm origin
git remote rm composer
git remote add composer https://github.com/drupal-composer/drupal-project.git
git remote add origin https://gitlab.example.com/user1/drupal8-test.git

```

The result:

```
$ git remote -v
composer    https://github.com/drupal-composer/drupal-project.git (fetch)
composer    https://github.com/drupal-composer/drupal-project.git (push)
origin  https://gitlab.example.com/user1/drupal8-test.git (fetch)
origin  https://gitlab.example.com/user1/drupal8-test.git (push)

```

Get upstream files:

```
git fetch composer
git merge composer/8.x

```

Adding your own files:

```
touch myfile.txt
echo "hello world" > myfile.txt
git add foo.txt
git commit -m "Added my file."
git push origin master

```

---
Tags: 8, configuration, version-control, staging
---


# Question
Title: how to use token in "Execute custom PHP code" in a rule
I used "**Execute custom PHP code**" in my pricing rule.

However I got Notice when I checkout:

> Notice: Use of undefined constant testsku - assumed 'testsku' in eval() (line 7 of /var/www/jmu/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code). Notice: Undefined variable: line\_item in eval() (line 7 of /var/www/jmu/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).

I know there must be something wrong with my token replace code:

```
$line_item_label = token_replace([commerce-line-item:line-item-label],array('commerce_line_item' =>$line_item));

```

I used "line-item-label" as product sku's machine name

Anyone have any idea about this?

# Answer
At the very beginning, I just saw "$commerce\_line\_item" can be used in php code, but I wanted to use `[commerce-line-item:line-item-label]` value which showed in the token place. So I tried to use token\_replace to get this value.

Finally, I figure out how to get that value and use it in PHP Code.  Although it isn't showed in the variable name place, we can still use `$commerce_line_item -> line_item_label` in the PHP Code. This works for me.
> 0 votes

---
Tags: 7, rules, tokens
---


# Question
Title: How to hide input from user inside a textfield
I need text inside a textfield FAPI form element to be obscured visually, just like the password field when you type into it.

password FAPI form element does not have proper functionality for what i need, I need textfield functionality but with the ability to hide the input from user.

Is this possible with Drupal 7 FAPI?

# Answer
You can add a CSS style to implement this.

However, currently, only Chrome supplies "-webkit-text-security" could do this. I find someone has some sample code: https://jsfiddle.net/estelle/8WpNg/
> 1 votes

---
Tags: 7, forms
---


# Question
Title: author_picture twig variable outputting title and bio?
Reading the D8 documentation, it says the appropriate twig for displaying the author's picture is:

{{author\_picture}}

When I use that, however, I'm getting the author's title, and description as well. Is there a way to fix that other than CSS fixes to render the other fields invisible? Or is there something I'm missing?

# Answer
According to the documentation, {{author\_picture}} is showing the node author user entity, rendered using the "compact" view mode.

In other words, you can adapt it by browsing to `http://your_site/admin/config/people/accounts/display/compact`
> 1 votes

---
Tags: theming, 8
---


# Question
Title: How know inside hook_entity_presave() if it's a create or update?
How know inside hook\_entity\_presave() if the entity is create or update please ? Thanks.

Note: I want use presave and not update and insert hook.

# Answer
> 12 votes
Like this:

```
if ($node->isNew()) {

}

```

Note that this only works before saving, in insert/update, it will always return TRUE, because the node has already been saved and is no longer new.

# Answer
> 0 votes
In addition to the above answer, you also could check

```
if (!empty($node->nid)) {

}

```

# Answer
> 0 votes
An updated entity will always contain a copy of the original entity:

```
if (isset($entity->original)) {

}

```

---
Tags: hooks, 8
---


# Question
Title: How do I get a field rendered with translated labels?
I have a node I render with the following code.

```
$render_controller = \Drupal::entityManager()->getViewBuilder($node->getEntityTypeId());
$render_output = $render_controller->view($node);
echo \Drupal::service("renderer")->render($render_output);

```

The rendered field labels are always in the original language (for example, German), even if I use `$node->getTranslation("en")`.

I find it difficult to get translated labels to render properly. I've searched through the source code all the way from back to front to find an answer. I see my translated field label in the frontend under "/admin/config/regional/config-translation/node\_fields" so it must be stored *somewhere*.

How do I access it or even better render the whole field correctly?

Neither `$field->getLabel()` nor `$language_manager->setConfigOverrideLanguage($language) helped. Somehow Drupal must think it's very clever and uses some default language I don't want. I want to pick a specific language and render that. I would expect that using`getTranslation()\` on the node really gives you everything in the right language, but it doesn't happen. Why?

# Answer
> 2 votes
You have the change the current config translation language. user\_mail() has an example for that:

```
  $language_manager = \Drupal::languageManager();

  $language = $language_manager->getLanguage('en');
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Do your thing here.

  $language_manager->setConfigOverrideLanguage($original_language);

```

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


# Question
Title: Display terms in relation to the terms of the page
I created product sheets related to the terms of taxonomy. How to display a block of view, the products in relations with the currently visited page? For example if my page is linked with the term "soap" requires that all products associated with the term "soap" appear in the block view.

I made a block view with a pop filter "tid" but I do not know how to parameterize.

version D7

# Answer
> 0 votes
1) Create a view of your products

2) Under Advanced, add a RELATIONSHIP of Taxonomy terms on node

* Checkmark ☑ require relationship

3) Add a CONTEXTUAL Filter of Has taxonomy term ID

* Select provide default value
* Select Taxonomy term ID from URL
* Checkmark ☑ load default filter from node page

---
Tags: 7, views, taxonomy-terms
---


title: Create new content type on hook_install

text:
# Question
Title: Create new content type on hook_install
Can someone show me a proper example of how to create a new content type in a module's hook\_install method?

I'd also like to know if/what I should do during hook\_uninstall to clean up my mess; I read there is some debate about simply removing the content.

I haven't been able to find an example of the proper method of accomplishing this task, any help would be appreciated!

# Answer
To answer your questions exactly:

**Creating a content type in hook install**: You use node\_type\_save() to create the content type, here's an example from webform.install:

```
  // Create the default webform type.
  $webform_type = array(
    'type' => 'webform',
    'name' => st('Webform'),
    'base' => 'node_content',
    'description' => st('Create a new form or questionnaire accessible to users. Submission results and statistics are recorded and accessible to privileged users.'),
    'custom' => TRUE,
    'modified' => TRUE,
    'locked' => FALSE,
  );

  $webform_type = node_type_set_defaults($webform_type);
  node_type_save($webform_type);
  node_add_body_field($webform_type);

```

**What do do in hook\_uninstall**: Basically just cleanup after yourself, so delete variables your module created (using variable\_del()), delete any files uploaded by the module (using file\_unmanaged\_delete\_recursive()), delete defined content types (using node\_type\_delete()), etc.

Hope this helps!
> 7 votes

# Answer
One of the best ways to keep this information in code is to use features. Feaures can put into code:

* Content types
* CCK fields
* Permissions
* Roles

The list goes on.

One nice feature about features is the drush integration

`drush features` will give you a list of all features on the site, and their status
`drush features revert all` will revert all features back to what is in code (really handy for running after deployments)

Help this helps
> 11 votes

# Answer
Check out the D7 Examples module. node\_example has install & uninstall.

You may be able to flesh out the type with the interface tools and then make a feature (with features module) & extract relevant parts into the install function of your custom module.
> 3 votes

# Answer
If you want to create a new content type with some fields, you can use the below code.

This code works for me perfectly.

```
function HOOK_install() {

 /* CREATE THE CONTENT TYPE */
 $t = get_t();
 $node_example = array(
    'type' => 'slider',
    'name' => $t('Slider Content'),
    'base' => 'node_content',
    'description' => $t('Add slider content.'),
    'body_label' => $t('Slider Description')
 );
 $content_type = node_type_set_defaults($node_example);

// Create a custom Field with our required field-type.
$field = array(
  'field_slider_images' => array (
    'field_name' => 'field_slider_images',
    'type' => 'image',
  ),
 'field_slider_links' => array (
   'field_name' => 'field_slider_links',
   'type' => 'text',
   'entity_types' => array('node'),
  ),

);
foreach ($field as $fields) {
  field_create_field($fields);
}

// Create a instances of that Field.
$instance = array(
'field_slider_images' => array (
  'field_name' => 'field_slider_images',
  'entity_type' => 'node',
  'bundle' => 'slider',
  'label' => t('Slider Image'),
  'description' => 'Add Slider Image.',
  'settings' => array(
    'file_directory' => 'field/document',
    'file_extensions' => 'png PNG jpg jpeg JPG JPEG',
    'max_filesize' => '10MB',
    'title_field' => '',
  ),
  'widget' => array(
     'type' => 'image_image',
     'weight'=> 10,
  ),
  'formatter' => array(
    'label' => t('label'),
    'format' => 'image'
  ),
  'settings' => array(
    'file_directory' => 'slider-image', // save inside "public://photos"
    'max_filesize' => '4M',
    'preview_image_style' => 'thumbnail',
    'title_field' => TRUE,
    'alt_field' => FALSE,
  )
),
'field_slider_links' => array (
  'field_name' => 'field_slider_links',
  'entity_type' => 'node',
  'bundle' => 'slider',
  'label' => t('Slider Link'),
  'widget' => array('type' => 'text_textfield'),
 ),
);

foreach ($instance as $fieldinstance) {
 field_create_instance($fieldinstance);
}

$status = node_type_save($content_type);
node_add_body_field($content_type);

// Replacement rule for the messages.
$t_args = array('%name' => $content_type->name);
if ($status == SAVED_UPDATED) { // update case
 drupal_set_message($t('The content type %name has been updated.', $t_args));
}
 elseif ($status == SAVED_NEW) { // create case
   drupal_set_message($t('The content type %name has been added.', $t_args));
   watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
}

}

```
> 0 votes

# Answer
I did this in the MySpace Sync module.
I remember piecing that together from various sources, but I don't remember what all the sources were. You can browse the git repository there to see what I did, but it's basically an export of each content type with CCK's Content Copy module on install, and then deleting all nodes before deleting the content type on uninstall.
> -1 votes

# Answer
Try the link below, it will be helpful.

Drupal 7 Field API - Setup a new content type on install and add fields
> -1 votes

---
Tags: 7, hooks
---


title: Title in url instead of tid?

text:
# Question
Title: Title in url instead of tid?
How can I display the title in URLs instead of the taxonomy ID?

`www.abc.com/search-page?tid=01` should be `www.abc.com/search-page?title=this-is-the-first-post`.

I am using Taxonomy Terms as Search in Views (Configure filter `criterion: Content: Has taxonomy term`). When I click on taxonomy, I will find more button; when I click i will find "Filter identifier" by default "tid" is present.

When i tried to change that to *title*, it displayed *Page not found*.

On *Views \>\> Advanced \>\> Contextual Filters*, I added the field for the title, but even this is not working.

Thanks

# Answer
> 8 votes
I have fixed this, just for other guys who are facing the same issue, I thought to post this.

1. created a Taxonomy Page with tag selected
2. save and edit
3. FIELDS -\> add your necessary fields
4. FILTER CRITERIA -\> add: Taxonomy term: Name (exposed)
5. click on Advance tab to the right side
6. RELATIONSHIPS -\> add : Taxonomy term: Content with term
7. CONTEXTUAL FILTERS -\> add : Taxonomy term: Name

I'm using exposed form "Exposed form in block:Yes" to be displayed as a block and can be assigned to the page.

**Search Result in URL : drupal-7/search-new-1?name=tag**

# Answer
> 1 votes
You can achieve this by the module - TVI

https://www.drupal.org/project/tvi

Install the module from the above link.

After enable this module, remove the filter criteria just remain the contexual filter with validation criteria of taxonomy id.

Now, go to the taxonomy edit page, there is one checkbox generated by that module, check that and select the view from the dropdown.

Clear all the cache.

This works for me, i hope this helps you.

---
Tags: views, taxonomy-terms, search, uri
---


title: hook_entity_view_alter - redirect

text:
# Question
Title: hook_entity_view_alter - redirect
First up I'm very new to the Drupal way of things but have jumped on board with Drupal 8 and quite excited about the possibilities.

What I'm trying to do is redirect the default node view route (i.e. **/node/12345/**), for a specific content type, to a route I've setup in my module i.e. **/module\_name/view/12345/**

Currently I've done this via a hook which I'm 99.9% is the wrong way to do it but it does work. However I'm getting warnings in my log file as other Drupal commands (including drush) occasionally trigger the hook.

Here is my code so far:

```
function gst_return_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if($entity->bundle() == 'gst_return') {
        header('Location: /gst_return/view/' . $entity->id());
        exit;
    }
}

```

Two questions really:

1. Is there a better way to be doing this? I'm sure there is.
2. If the above is acceptable then what can I add to it so that the header redirect (which probably should be a Drupal core redirect?) so that it is only triggered in the context of someone viewing the site.

Thanks for any assistance.

# Answer
> 0 votes
Instead of using header redirect try using **RedirectResponse** class which comes together with the **Symfony HttpFoundation**.

```
use Symfony\Component\HttpFoundation\RedirectResponse;

 function my_menu_callback_foo() {
    //....
    return new RedirectResponse(\Drupal::url('user.page'));
 }

```

Refer link for more details.

---
Tags: nodes, hooks
---


# Question
Title: Is my code valid and how does it relate to the coding standards?
How does the below piece of code relate to the Drupal (7) coding standards? Notice that the function is not returning anything.

```
$a = foo();

function foo() {
  // Doing everything except returning.
  drupal_func();
}

```

Somebody claims that:

1. the assignment to the variable is for the future because that way it is easier later to refactor the foo(). However the code now never uses `$a`.
2. Drupal people do this kind of practice often and it's even in Drupal core.

So the real question is: "***Is this valid, should this be kept in the code***"? We agreed to keep Drupal coding standards in our project. I was doing a code review of my friend's code and he insisted on keeping that code (using arguments that it is used inside Drupal core - but I couldn't find an example myself) while I was trying to convince him to remove the `$a`. We couldn't reach an agreement so I decided to reach out for help.

# Answer
> 2 votes
*A lot of this is my opinion, I should say that up front...*

Drupal's coding standards don't have any provisions for the type of pattern you've described.

You may be falling foul of "Naming Conventions", because you haven't prefixed the global function with the name of the module that "owns" it, but apart from that, and other small points that are only valid because the code is only an example, no, you don't seem to be breaking any specific Drupal standards with that code.

But just because it doesn't specifically break one of the generalised standards doesn't make it "good" code. Polluting the global scope is almost always bad, especially just for the sake of it with an unused var, and assigning a `NULL` returning function to a variable is an obvious code smell to me.

In short, it's a weird pattern, not one that I'm familiar with in any language/framework (though I'm sure it's been used, most things have). There are sort-of-similar patterns used elsewhere, e.g. the CTools plugin system, but that works because the calling code includes the file and actually makes use of the `$plugin` variable in scope. So the vars is used; and `NULL` functions aren't assigned to vars in that context either.

I highly doubt you'll find an example of this pattern in core, but if your friend can provide one, I'd be interested to see it.

# Answer
> 0 votes
There is one module Coder for check the drupal standard for every module and its file.

Configure it properly and after run the test it will show you the errors and suggestions.

You can run the test for your custom module directly from the module listing page, there is an option besides your module to run the test.

Install this Coder Module from the below link.

https://www.drupal.org/project/coder

Just try this module, it is really helpful for developers.

Hopefully this may help you.

---
Tags: 7, coding-standards
---


# Question
Title: I can't show the body content with full HTML
My fresh installed Drupal 8 site can't display articles that use full HTML.

Is that normal?

Using the *Full HTML* input format, it appears like this.

>

I have to change the input format to *Basic HTML*, to make the body appear.

>

>

Is my installation complete?

### Notes

* I also tried pasting a different paragraph from a different website to see what happened, but the body content did not display.
* I'm currently using Drupal core 8.1.3. What does *missing filter* mean? I found this in the information of text format.

> Full HTML: Missing filter. All text is removed.

# Answer
> 3 votes
You have to check at least one filter in `admin/config/content/formats/manage/full_html`

Below image shows the default filters for **Full HTML**

---

More explanation can be found from the answer by @kiamlaluno♦

> Full HTML: Missing filter. All text is removed.

Above error message displayed because there is enabled filter of a input format missing. It could be happened by uninstalling module. You can find a issue in Drupal core for this.

You can just save the input format once again, which will help to remove the reference of missing filter.

# Answer
> 4 votes
The error message you see (*Full HTML: Missing filter. All text is removed.*) means that one of the filters you selected on admin/config/content/formats/manage/full\_html is missing; this usually happens when you uninstall the module implementing it. As explained in Missing filters result in Exception when the format is used, in those cases, Drupal doesn't show the text using the input format containing the missing filter.

That is not a problem. Just go to admin/config/content/formats/manage/full\_html and save; the reference to the missing filter will be removed, and you will be able to see the body text again. In fact, the form builder for the input format form contains the following code. (See `FilterFormatFormBase::form()`.)

```
  // Create filter plugin instances for all available filters, including both
  // enabled/configured ones as well as new and not yet unconfigured ones.
  $filters = $format->filters();
  foreach ($filters as $filter_id => $filter) {
    // When a filter is missing, it is replaced by the null filter. Remove it
    // here, so that saving the form will remove the missing filter.
    if ($filter instanceof FilterNull) {
      drupal_set_message($this->t('The %filter filter is missing, and will be removed once this format is saved.', array('%filter' => $filter_id)), 'warning');
      $filters->removeInstanceID($filter_id);
    }
  }

```

The message clearly says *The filter is missing, and will be removed once this format is saved.* So, saving should fix the issue.
If this doesn't work, remove another filter from the input format, save, re-add the same filter you removed, and save again. At least, this should clear the eventual cache Drupal uses for filters or input formats.

---
Tags: nodes, 8, input-formats
---


# Question
Title: How can I delete a row from the database?
I would like to delete all rows from the database that is older than 1 month. How can I do that in Drupal 8?

> DELETE FROM myTable WHERE MyColumn \< DATEADD(MONTH, -1, GETDATE())

# Answer
You can do it by using this code

```
$query = \Drupal::database()->delete('table');
$query->condition('some column', 'some condition');
$query->execute();

```
> 15 votes

---
Tags: 8, database
---


# Question
Title: Cache sometimes is not being updated on saving operations
I'm maintaining a pretty big news site, with many nodes and with many users who can create and edit nodes. The site is using the Paragraphs and the Memcache modules.

Editors can rearrange the blocks on the front page, add and edit articles. The problem is that occasionally (and sometimes pretty often) when editors do something on the site, the changes won't be immediately visible; they won't be even visible in the edit form when editors try to edit the node again. It will appear after few edits.

I know the change is effective since the first edit, as a call to `dmemcache_object()->flush()` makes the changes visible. This makes me think it's a problem with Memcache. However, replacing it with Redis doesn't fix the issue.

Core cache is basically disabled as we are caching everything in the CDN, but editors have direct access to the site, without CDN, and experience this problem there, so it's not CDN related. The following is the cache configuration.

>

I cannot reproduce the problem locally, even if I'm also using Memcache/Redis.
Sometime, when editors create a new node with paragraphs, the node appears "empty." During the edit, there are also no paragraphs. However `dmemcache_object()->flush()` seems to fix this problem. (I tried it few times.) Adding a call to `dmemcache_object()->flush()` in a save/update hook implementation doesn't help, though.

What can I do to diagnose and fix this problem? It is particularly hard to approach because it happens only on the production server.

When I use the Redis module and add the following lines to the settings.php file, I get a problem with the path aliases, which aren't shown anymore.

```
$conf['path_inc'] = 'sites/all/modules/contrib/redis/redis.path.inc';

```

When that line is removed and the cache is cleared, the path aliases are correctly shown.

Also, the database is located on a different server.

# Answer
> 0 votes
Try Expire module instead you try to clear cache manually.

> This module provides configurable actions upon events that will expire URLs from caches like reverse proxy caches, internal page caches, etc.This module make more sense when Minimum Cache Lifetime setting is set to a value other than none.
>
> There is now integration with the following modules:
>
> ```
> Boost - deletes expired pages (files) from the file system.
> Varnish - integrates over an administrative socket.
> Fastly - Varnish/CDN caching
> Purge - expires urls by sending purge requests to Varnish, Squid and Nginx over HTTP.
> Acquia Purge - allows Drupal sites hosted on Acquia Cloud to automatically purge pages from their Varnish powered load balancers..
> Memcache Storage - allows to delete pages that were cached in a memcached instances.
> Akamai - provides an integration with the Akamai Cache Control Utility (CCU) Web Service
> Recacher - Page cache warmer.
>
> ```

and Memchache Storage mdoule

**Features**

```
This module is an alternative to Memcache API and Integration module focused on different set of features. Available features (D7):

    You can move all cache to the memory.
    You can move users' sessions to the memory.
    You can move lock system to the memory.
    Module can store cached pages for anonymous users as a plain text, so proxy servers (like Nginx with enabled ngx_http_memcached) can get such pages directly from memcached pool and avoid heavy requests to the backend.
    You can clear data from single cache bin, cache cluster or flush all cached data from Drupal UI (screenshot).
    You can find helpful nice debug output (screenshot).
    Integration with Drush
    Integration with Administration menu. Module provides link for flushing memcached data from navigation toolbar.
    Active development and support.

```

---
Tags: 7, caching
---


# Question
Title: Getting author_picture component values in twig
I'm making a theme where the author picture needs to be in one div, but some other fields from the user profile need to be in another.

The fields are all available in the author\_picture variable - but I'm a little unclear in Twig how to split it apart into it's relevant pieces.

The author's pic appears to be called user\_picture, and the fields are called field\_bio and field\_title.

I've tried different variations like

`{{ author_picture.field_bio.value }}` or `{{ author.picture.user_picture.value }}` etc - but to no avail. What am I missing?

# Answer
> 0 votes
No Sssweat has right. When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my\_field }}. If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field.

---
Tags: theming, 8
---


# Question
Title: How to prevent term URL in webform email template (Webform References Module)?
I've configured a webform to send a custom email after submit. One of the fields in the webform is a taxonomy select (via the Webform References module). So the value in the email template looks something like this:

```
[submission:values:vocabname]

```

When the email gets sent, the selected taxonomy term gets printed out along with a reference to its URL listed at the bottom... like this:

```
Term Name [1]

```

And then at the bottom of the email is the URL:

```
[1] http://www.example.com/vocab-name/term-name

```

How do I prevent the URL from being included automatically in the email? I just want term name alone.

# Answer
When returning field value Webform References Module, add link to field output using theme function (theme\_webform\_display\_term\_reference\_field()), which you can override in your theme's template.php and then clear Site Cache. Check sample code below, which you can write in your theme's template.php:

```
/**
 * Format the output of data for this component.
 */
function [THEME_NAME]_webform_display_term_reference_field($variables) {
  $values = (array) $variables['element']['#value'];
  $items = array();
  foreach (array_filter($values) as $value) {
    $tid = check_plain($value);
    if ($tid) {
      // Do not pass 2nd argument, keep it default i.e. FALSE.
      $items[] = _webform_references_get_term_name($tid);
    }
  }
  $output = count($items) > 1 ? theme('item_list', array('items' => $items)) : (isset($items[0]) ? $items[0] : '');
  return $output;
}

```

**NOTE : This will also remove the Term field link on view submission page.**
> 1 votes

---
Tags: 7, taxonomy-terms, webforms, emails
---


# Question
Title: How do I add the edit link of a content in a custom view mode?
I have a content type (*Sample*) which includes a field (*A*) whose widget type is *View*. I'm using the Entity Reference View Widget View module for this.

The output of this field is having only the title of the node added from the view, but I want also the *Node Edit link*.

As far as I know, the output of *Entiy Reference View Widget View* can be printed with any custom view mode. I'm trying to add the node edit link in this custom view mode.

Do you have any idea on how to add a custom field having the edit link in the view mode?The steps which i followed are:

Step 1:I selected the particular view mode in the content type field settings A: Here is the screen shot:

Step 2: In Display suit fields(admin/structure/ds/fields) i have added custom edit link field like `<a href="node/edit/[node:nid]">Edit</a>` I can see Edit link in the output ,but the token value i provided \[node:nid\] is not fetching the node id. Link is redirecting to `node/edit/%5Bnode%3Anid%5D` .Can anybody help me in this? Please the below screenshot

Correct me if i'm wrong. Any other approach or method is also fine.

# Answer
> 2 votes
You can enable views\_ui in module page, then go to structure/views and edit the views you are using for the widget. Add `Content: Edit link` in fields and save it. It will got the edit links for each entity as above image.

---

# Override theme function by custom module

There is no easy way to add the edit link for the widget on node page. But you can still make it happen by overriding the theme functions provided by Entity Reference View Widget View

Below is the sample snippet with assuming the name of your custom module is `mymodule`. You can copy and paste it into a custom module for testing. (Remember to change the `mymodule` if you have different name for your custom module.)

```
<?php

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['entityreference_view_widget_widget']['function'])) {
    $theme_registry['entityreference_view_widget_widget']['function'] = 'mymodule_entityreference_view_widget_widget';
  }
  if (isset($theme_registry['entityreference_view_widget_rows']['function'])) {
    $theme_registry['entityreference_view_widget_rows']['function'] = 'mymodule_entityreference_view_widget_rows';
  }
}

/**
 * Override theme_entityreference_view_widget_widget().
 */
function mymodule_entityreference_view_widget_widget($variables) {
  $widget = $variables['widget'];
  $settings = $widget['add_more']['#ervw_settings'];
  $order_class = drupal_html_class($settings['element'] . '-delta-order');
  $required = !empty($settings['instance']['required']) ? theme('form_required_marker', $variables) : '';

  $header = array(
    array(
      'data' => '<label>' . t('!title !required', array('!title' => $widget['#title'], '!required' => $required)) . "</label>",
      'colspan' => 2,
      'class' => array('field-label'),
    ),
  );
  $header[] = array(
    'data' => "<label>" . t('Edit link') . "</label>",
    'class' => array('field-label'),
  );
  if ($settings['field']['cardinality'] !== '1') {
    $header[] = array(
      'data' => t('Order'),
      'class' => array('tabledrag-hide'),
    );
  }
  $rows = array();

  // Sort items according to '_weight' (needed when the form comes back after
  // preview or failed validation)
  $items = array();
  foreach (element_children($widget) as $key) {
    if ($key === 'add_more') {
      $add_more_button = &$widget[$key];
    }
    else {
      $items[] = &$widget[$key];
    }
  }
  usort($items, '_field_sort_items_value_helper');

  // Add the items as table rows.
  foreach ($items as $item) {
    $item['_weight']['#attributes']['class'] = array($order_class);
    $delta_element = drupal_render($item['_weight']);

    $cells = array(
      array('data' => '', 'class' => array('field-multiple-drag')),
      drupal_render($item),
    );

    $target_id = $item['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $cells[] = array(
      'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
    );

    if ($settings['field']['cardinality'] !== '1') {
      $cells[] = array('data' => $delta_element, 'class' => array('delta-order'));
    }
    $rows[] = array(
      'data' => $cells,
      'class' => array('draggable'),
    );
  }

  if (empty($rows)) {
    $rows[][] = array(
      'data' => t('No items have been added yet. Click "Add items" to launch the widget.'),
      'colspan' => '3',
    );
  }

  $output = '<div class="form-item">';
  $form_errors = form_get_errors();
  $classes = array('field-multiple-table');

  // Add an error class to the table in case of error.
  if (isset($form_errors[$settings['element']])) {
    $classes[] = 'error';
  }

  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array(
      'id' => $settings['table_id'],
      'class' => $classes,
    ),
  ));
  $output .= $widget['#description'] ? '<div class="description">' . $widget['#description'] . '</div>' : '';
  $output .= '<div class="clearfix">' . drupal_render($add_more_button) . '</div>';
  $output .= '</div>';

  if ($settings['field']['cardinality'] !== '1') {
    drupal_add_tabledrag($settings['table_id'], 'order', 'sibling', $order_class);
  }

  return $output;
}

/**
 * Override theme_entityreference_view_widget_rows().
 */
function mymodule_entityreference_view_widget_rows($variables) {
  $zebra = array('even' => 'odd');

  $settings = $variables['rows']['#widget_settings'];
  foreach (element_children($variables['rows']) as $row) {
    $output[$row]  = '<tr class="draggable ' . current($zebra) . '">';
    $output[$row] .= '<td class="field-multiple-drag"></td>';
    $output[$row] .= '<td>' . render($variables['rows'][$row][$settings['column']]) . '</td>';

    $target_id = $variables['rows'][$row]['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $output[$row] .= '<td>' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '</td>';

    if ($settings['cardinality'] !== '1') {
      $output[$row] .= '<td class="delta-order tabledrag-hide">' . render($variables['rows'][$row]['_weight']) . '</td>';
    }
    $output[$row] .= '</tr>';

    $zebra = array_flip($zebra);
  }

  return implode("\n", $output);
}

/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}

```

The key concept here is programmatically override the 2 theme functions with hook\_theme\_registry\_alter:

* `theme_entityreference_view_widget_widget()`
* `theme_entityreference_view_widget_rows()`

So we can now modify the table output.

## Add a new column header

```
$header[] = array(
  'data' => "<label>" . t('Edit link') . "</label>",
  'class' => array('field-label'),
);

```

## Add link for new column

For static output.

```
$target_id = $item['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$cells[] = array(
  'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
);

```

For dynamic output. (ajax callback)

```
$target_id = $variables['rows'][$row]['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$output[$row] .= '<td>' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '</td>';

```

## Helper function to build edit link

```
/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}

```

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


# Question
Title: How to create a controller that runs query?
I have a query:

```
$sub_query = \Drupal::database()->select('test_file_discovery', 'f')
  ->fields('f', ['nid'])
  ->condition('extension', 'pdf');
$or = $sub_query->orConditionGroup()
  ->condition('path', \Drupal::database()->escapeLike('_TT'), 'LIKE')
  ->condition('path', \Drupal::database()->escapeLike('_OT'), 'LIKE')
  ->condition('path', \Drupal::database()->escapeLike('_AT'), 'LIKE');
$sub_query->condition($or);

$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->condition('nid', $sub_query, 'IN');
$query->range(0, 10);

```

But I don't know how to create a controller / page where I can display this query's results in a table, "Name" and "Actions" as labels / headers.

Anyone can give me assistance?!

# Answer
@asrob, Please refer the basic docs provided by Clive to create a controller in drupal 8 with route to access the same or this link to create a custom module in drupal and follow this sample code below to display your data in table format along with a pager:

```
  <?php

  /**
   * @file
   * Contains \Drupal\custom_module_name\Controller\DetailsController
   */

  namespace Drupal\custom_module_name\Controller;

  use Drupal\Core\Controller\ControllerBase;

  /**
   * Description of DetailsController
   *
   * @author aaditya.walawalkar
   */
  class DetailsController extends ControllerBase {

    const RECORDS_PER_PAGE = 10;

    /**
     * {@inheritdoc}
     */
    public function getRecords() {

      $records = $query_result_from_query;

      // total records
      $totalRecords = $total_records_count_from_query;
      $recordsPerPage = self::RECORDS_PER_PAGE;
      // initialize pager
      $page = pager_default_initialize($totalRecords, $recordsPerPage);

      $offset = $recordsPerPage * $page;

      $data = array();
      foreach ($records as $delta => $details) {
        $data[] = array('data' => array(
          $details['name'],
          $details['remarks'],
        ));
      }

      $recordsToDisplay = [];
      $recordsToDisplay[] = [
        '#theme' => 'table',
        '#header' => array($this->t('Name'), $this->t('Remarks')),
        '#rows' => $data,
        '#empty' => $this->t('No Records(s) Found.'),
      ];

      // Finally, add the pager to the render array, and return.
      $recordsToDisplay[] = ['#type' => 'pager'];
      return $recordsToDisplay;

    }
  }

```
> 2 votes

---
Tags: 8, database
---


title: Create Block Programmatically

text:
# Question
Title: Create Block Programmatically
I am learning Drupal 8, i know how to create block programmatically in Drupal 7.

Can anyone please suggest how can u create block and render that block in more than one region in Drupal 8?

# Answer
> 2 votes
The 'id' property in the annotation defines the unique, machine readable ID of your block.

The '`admin_label`' annotation defines the human readable name of the block that will be used when displaying your block in the admin interface.

The 'Category' defines which section belongs to under block listing page.

The Drupal block manager scans your module's classes for a class that contains the @Block Annotation (a special comment right above your class declaration)

```
<?php
/**
 * @file
 * Contains \Drupal\article\Plugin\Block\XaiBlock.
 */
namespace Drupal\article\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'Article' Block
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article block"),
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => 'This block list the article.',
    );
  }

```

custom block programatically

# Answer
> 1 votes
Creating a custom block require following steps:

Create a block plugin using Annotations Extend the Drupal\Core\Block\BlockBase class. In Drupal 8, We need to keep the keep our custom, contributed module in root directory

modules/custom

module/contrib

Step 1: An essential part of a Drupal 8 module, theme, or install profile is the .info.yml file (aka, "info yaml file") to store metadata about the project.

In Drupal 8, .info file changes to .info.yml. Old .info files have been converted to YAML.

Added name, description, core, package, dependencies, type (The type key, which is new in Drupal 8, is required and indicates the type of extension, e.g. module, theme or profile.

Step 2: We should follow the PSR-4 standard code for custom block(s) & that has to be placed into article/src/Plugin/Block/ and named based on the class it contains. If we're going to define the class ArticleBlock this file would be article/src/Plugin/Block/ArticleBlock.php

Create a file ArticleBlock.php under modules/custom/article/src/Plugin/Block folder structure

Annotation contains just the id and label:

The 'id' property in the annotation defines the unique, machine readable ID of your block. The 'admin\_label' annotation defines the human readable name of the block that will be used when displaying your block in the admin interface. The 'Category' defines which section belongs to under block listing page.

The ArticleBlock extends BlockBase class. This class provides generic block configuration form, block settings and handling of user defined block visibility settings.

Save the file and enable the module. To enable a block visit /admin/structure/block and click on “place block” under one of the region. i’m selecting “Sidebar Second” for my visibility or search for your block “Article block” click on “place block” and configure it.

I hope this helps.. :)

---
Tags: 8, blocks
---


# Question
Title: Unsubscribe users from Simplenews from a specific Newsletter category
I send newsletters from my Drupal-7 website using Simplenews module. I have a general category, that has all my site users and it is the category I use the most.
Although, some of the newsletters are sent to a smaller target group (women-only, men-only etc).
My problem is that when users click on the unsubscribe link from a newsletter that is not from my general category, then they unsubscribe from this category only and not the general.
What I want to achieve, is that when a user is unsubscribed from any newsletter category, to automatically unsubscribe him from the general category also.

# Answer
I think it should work. Use hook\_simplenews\_unsubcribe\_user which will

```
/**
 * Invoked if a user is unsubscribed from a newsletter.
 *
 * @param $subscriber
 *   The subscriber object including all subscriptions of this user.
 *
 * @param $subscription
 *   The subscription object for this specific unsubscribe action.
 *
 * @ingroup subscriber
 */
function hook_simplenews_unsubscribe_user($subscriber, $subscription) {

}

```

Add this in your custom module. I think $mail and $tid will be available in $subscrption variable.

```
function module_simplenews_unsubscribe_user($subscriber, $subscription) {
  simplenews_unsubscribe_user($mail, $tid, FALSE, 'website');//$tid -s your genral category tid.
}

```
> 0 votes

---
Tags: 7, emails
---


# Question
Title: How to create a single form for donations?
I have a commerce module setup which allows for donations on a site I'm working on. Everything runs smoothly - you make a donation, it gets added to your cart, and when you're done you go to your cart, you click the checkout button, you enter cc info and bob's yer uncle (USAePay is the cc vendor).

However, the client is asking that one single page not do it this way at all - they want the information to all happen on one single page. You enter all your info - billing info, name/email info, cc info, donation amount, all on the same page. And clicking "**Donate now**" does everything that you previously did in a few steps. And by everything, I do mean **everything** \- not a different chunking of panels, I mean it all happens on one page.

It really seems like clicking a link is creating a new cart of its own and taking you directly to checkout, and the styling of the checkout page is maybe different from other ones. Not sure how I'd accomplish that, though.

Questions:

* is this even possible? I don't want to lead them on and let them think it's possible when it's not.
* if it IS possible, how? And please don't just say "a module."

# Answer
You can try the Commerce Buy One Click module.

> Commerce Buy One Click Module allows customers to checkout directly from the product page with just one click, skipping the annoying checkout steps.
> 0 votes

# Answer
If "*I have a `commerce` module setup*" means that you're using Drupal Commerce (because its project namespace is `commerce` also), then have a look at the Commerce Donate module. From its project page:

> This module provides a donation line item type along with a donation product and product display. This is partially based on Randy Fay's excellent screencast at http://commerceguys.com/blog/using-custom-line-items-provide-donation-fe...
>
> It uses the Select or Other module to provide the donation amount form field. If you need to modify the default donation option values, then install the Commerce Customizable Products module in order to modify the line item type form settings.
>
> In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

Here is a screenprint (from its project page also) of how that ***checkout pane***:

So selecting an option for "***Donate to us!***" that differs from `None`, is the only action needed to allow for donations, and similar to what is written in your question:

* it does everything that you previously did in a few steps.
* not a different chunking of panels.
* it all happens on one page.

**Note**: refer to the tutorial/screencast "Using Custom Line Items To Provide a Donation Feature to Drupal Commerce" for a great introduction to this module.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How do I update multiple rows in one single function call?
I want to update multiple rows in one query, for example as with the following code.

```
db_query("update bestsellers set count = 4 where product_id = 30; update bestsellers set count = 5 where product_id = 32; update bestsellers set count = 1 where product_id = 34;")->execute();

```

The server returns a 500 error. Is there any way to achieve this?

# Answer
While you can probably update multiple rows using one call to `db_query(...)->execute()` (if you use a single SQL query that will updates multiple rows), that's not what the OP code shows. The code try to execute multiple SQL queries with a single call to `db_query(...)->execute()`, which is not supported by the API. Also, as stated in its documentation for Drupal 7, `db_query()` should not be used for update queries. Instead, use `db_update()`.

The following would be the clean and safe way to do it with multiple `db_update()` queries

```
$counts = [
  30 => 4,
  32 => 5,
  34 => 1
];
foreach ($counts as $product_id => $count) {
  db_update('bestsellers')
    ->condition('product_id' => $product_id)
    ->fields(['count' => $count])
    ->execute();
}

```

It may also works with a query using a `CASE` in in the `SET` clause

```
db_query("
    UPDATE bestsellers
    SET count = CASE product_id
        WHEN 30 THEN 4
        WHEN 32 THEN 5
        WHEN 34 THEN 1
    END
    WHERE product_id IN (30,32,34)
")->execute();

```
> 4 votes

---
Tags: 7, database
---


title: Add form field with AJAX

text:
# Question
Title: Add form field with AJAX
Here is the form:

```
function payment_form($form, &$form_state) {
  $form['#tree'] = TRUE;

  // since credit card is also an option, the gift card section is contained in this div.
  $form['payment']['giftcard'] = array(
    '#type' => 'container',
  );

  // there are additional fields above here, but trimmed them out since they are not relevant to the issue.
  $form['payment']['giftcard']['giftcards'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'class' => array('giftcards'),
    ),
    '#prefix' => '<div class="giftcards-wrapper">',
    '#suffix' => '</div>',
  );

  // initialize the gift card field counter
  if (!isset($form_state['gift_cards'])) {
    $form_state['gift_cards'] = 1;
  }
  // build the fields
  for ($i = 0; $i < $form_state['gift_cards']; $i++) {
    $form['payment']['giftcard']['giftcards']['gift_card_number'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Gift Card Number'),
      '#title_display' => 'invisible',
    );
  }
  // validate the current gift card and add another field.
  $form['payment']['giftcard']['giftcards']['validate'] = array(
    '#type' => 'submit',
    '#value' => t('Validate'),
    '#ajax' => array(
      'callback' => 'validate_giftcard_add_field',
      'wrapper' => 'giftcards-wrapper',
      'method' => 'replace',
    ),
  );

```

Here is the callback function for the AJAX call. There is no validation currently, just trying to get it to add another field. If I add print statements in this function they are being output in a javascript alert, so this function is being called. However it is not returning any new fields.

```
function validate_giftcard_add_field($form, $form_state) {
  $form_state['gift_cards']++;

  return $form['payment']['giftcard']['giftcards'];
}

```

What is the right way to add new fields via ajax?

Additionally, all instances of `'#required' => TRUE,` have been removed during my testing. I have not done anything with the validate or submit callbacks either.

# Answer
> 2 votes
There were a couple of issues here. The first was with the wrapper, changed the class to and id:

```
// there are additional fields above here, but trimmed them out since they are not relevant to the issue.
$form['payment']['giftcard']['giftcards'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => array('giftcards'),
  ),
  '#prefix' => '<div id="giftcards-wrapper">',
  '#suffix' => '</div>',
);

```

The second issue is missing the submit callback for the ajax button:

```
// validate the current gift card and add another field.
$form['payment']['giftcard']['giftcards']['validate'] = array(
  '#type' => 'submit',
  '#value' => t('Validate'),
  '#submit' => array('validate_giftcard_add_field_submit'),
  '#ajax' => array(
    'callback' => 'validate_giftcard_add_field',
    'wrapper' => 'giftcards-wrapper',
    'method' => 'replace',
  ),
);

```

Updated ajax callback:

```
function validate_giftcard_add_field($form, $form_state) {
  return $form['payment']['giftcard']['giftcards'];
}

```

Defined the ajax submit callback:

```
function validate_giftcard_add_field_submit($form, &$form_state) {
  $form_state['gift_cards']++;
  $form_state['rebuild'] = TRUE;
}

```

# Answer
> 2 votes
`#ajax->wrapper` refers to an ID. Where as you have `class="giftcards-wrapper"`. Change it to ID and it should replace it.

---
Tags: 7, forms, ajax
---


# Question
Title: How to create a Content Type that reuses data from existing Content Type?
I have a specific use case that does not seem to be covered by existing Drupal 7 modules. I need to be able to create a "content type" that is created by choosing from a list of existing content.

Use Case:
A company that trains new pilots needs two content types:
Type 1: **Schedule a training flight.**
Type 2: **Post training flight details.**

Type 1 has the following fields:
(*flight\_id,trainer\_name, plane\_name, new\_pilot\_name, date, airport, flight\_status*)

**IMPORTANT:**
Type 2 is created when an admin clicks on the flight\_id from a list of scheduled flights.

Type 2 **is required** to contain the following data/fields:
(*content from type 1, trainer\_notes, new\_pilot\_grade*)

# Answer
> 5 votes
You can use Entity reference:

> Provides a field type that can reference arbitrary entities:
>
> * A generic entity reference field
> * Four widgets:
>     + Two implemented on top of the Options module (Select and Radios/Checkboxes),
>     + Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

And the Inline Entity Form module:

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

***Others similar modules to Inline Entity Form:***

Entityreference Autocreate

> A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

> Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

> Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

> It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
>
> The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

**EDIT**: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.

# Answer
> 2 votes
You can use the field node References module

With it you can add the content types you want as fields in your new content type and then use views to display it.

---
Tags: 7, entities
---


# Question
Title: Is it still a partial port or does it take a different approach?
At the moment of this question, I am using:

* Drupal 8.1.3
* Panels 8.x-3.0-beta4
* Page Manager 8.x-1.0-alpha23
* Layout plugin 8.x-1.0-alpha22

I am having difficulties replicating what was easy with Drupal 7, and I am not sure if the reason is simply that the ports of Panels and Page Manager are still incomplete, or that the approach has changed and I am not getting it.

**In Drupal 7**, you could create panels, and insert content into panes:

You could really add anything into a pane.

**In Drupal 8**, it looks like I can only add blocks:

What I want to achieve is being able to override a basic page (I'm overriding `/node/{node}`), and for example have a simple 1-column layout to display:

---

```
          <node title>

```

---

```
           <block 1>

```

---

```
          <node body>

```

---

```
           <block 2>

```

---

It could be more complex than that of course.

So, back to my question: is it just a matter of waiting for a complete port of Panels, or am I missing something?

# Answer
> 4 votes
It looks like you've forgotten to install one of the modules that implement panels.

From: drupal.org/project/panels

> Panels in Drupal 8
>
> We’re actively working on Panels for Drupal 8 which works with the new layout\_plugin module and mainly is an interface to configure and store these layouts.
>
> **Panels is an API in Drupal 8**
>
> **In order to use panels, you must use an implementing module. Currently, Page Manager and Panelizer implement panels.**
>
> If you’re interested in following the Drupal 8 port in detail, follow #2169319: \[meta\] Drupal 8 port of Panels in the issue queue OR join us on IRC every Tuesday at 12 noon CDT (UCT-0500) in the #drupal-scotch channel for our weekly meetings.

---
Tags: 8, panels
---


# Question
Title: How to set a checkbox using POST request with Services Module?
I am trying to set a checkbox in a display using a post request by setting the value of the mark field to 1, specifically field\_mark\_as\_discounted. But I can't seem to be able to achieve that. Note: The checkbox functions well when set manually. If anyone has come across this issue of setting a checkbox using post request please share.

# Answer
> 0 votes
This probably is the JSON you need for that field when **POST**ing:

```
field_foo: { und: [ { value: 1 } ] }

```

Remember, the Services module is dependent on which widget you have selected on the *Manage Fields* page for your entity/bundle.

---
Tags: 7, commerce, services
---


# Question
Title: Extracting the values of Field Collection
I have created a foreach loop in my node template in Drupal 8 where values of the field collection are being printed as 1 and 2. Instead I want the content of the field collection which includes an image and two text fields to be printed here. How do I achieve that? Complete code would be helpful. My code:

```
 {% for member in content.field_robot['#items'].getValue()  %}
   <div class="robot-member">
      {{member.value}}
   </div>
 {% endfor %}

```

I have no experience of playing in the .theme file but can follow basic instructions.

# Answer
You probably can find a way to solve the problem in the UI; look at Berdir's suggestions. If you want to add you own markup in the templates, you can try another strategy. You can use the Twig templates that come later, when the build array in content is processed.

First, put the field or field collection at any position where you want in the node template.

```
{{ content.field_robot }}

```

You can exclude this field from the content adding `without()` to avoid double content.

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

```

Then enable twig debugging, and look at the source in the browser, which Twig templates the field collection and the fields that are in this collection are calling and change these templates.

You would probably find that the Twig code you are trying to put into the node is already in other templates, that you can see in the Twig debugging text. So there is no need to hack the render array in content, which can change at any time, when you update Drupal or install modules, or change the configuration of the node display.
> 1 votes

# Answer
Do you want to access the *values* or the rendered output of those field collections?

For the second, you're supposed to configure the view display to display the fields of the collection. I don't know how it works exactly. Looking at the code, the field collection itself should have a view display UI, just like the node itself, where you can configure each field.

If you want to access the values, then you should do the following:

1. Do not use getValue(). It returns non-computed properties only and it returns them as a simple array. You want the field item object.
2. `content` is the rendered output, `node` is the node object with the values. So, you'd use `for item node.field_robot`. Looking at the code, it seems you'd need to use `item.getFieldCollectionItem()` and from there, access a certain field again, e.g. `item.getFieldCollectionItem().yourfield.value`.

But... from looking at the code a bit and that it has two major 8.x branches and not even an alpha release yet... it might be too early to use that project. Maybe you want to look at Inline Entity Form (8.x-2.x actually seems to depend on that) together with e.g. a node type or custom entity type or Paragraphs. We use the second quite actively and it's pretty well progressed for Drupal 8.
> 3 votes

# Answer
I got this to work using Berdir's advice. For example, I have a field collection called `field_sponsors` and I want the value of the field `field_sponsor_role` output in a node.html.twig file. So I write `{{ node.field_sponsors.0.getFieldCollectionItem().field_sponsor_role.value }}`. Note the `0` for just extracting the first item in the field collection. You could choose to loop through all of the items instead.

If the field is actually an entity reference, then you have to go deeper. In my field collection mentioned above, the field `field_company` is an entity reference. The `value` would just be the entity ID. But I want the name. So instead, I write `{{ node.field_sponsors.0.getFieldCollectionItem().field_company.entity.label }}`

Hope this helps.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"
We have the Payment Method Example module turned OFF. And, we only have one payment type set up (Authorize.net) in the Enabled Payment Method Rules.

Yet, when we add just one product to the cart and click submit (without going to checkout, so without filling in any payment fields) we can go to orders/shopping cart and see that a payment with the following fields has been added to the order in process:

Date: "6/25/2015" (even though today is 6/22/2016) Method: "Unknown" Remote ID "-" Result Message: - Number: 4111--------1111 Expiration: 06/2015 Amount: $1,788 (which is $4.00 less than the total for this particular order. Note that this amount will vary, though.)

This causes the following Authorize.net issues:

1) In the above example, Authoize.net comes in and accepts a transition for $4.00. The order balance is then zero, based on the above $1,788 "unknown" payment plus the $4.00 from Authorize.net.

OR

2) Authorize.net comes back with the below error when the "Unknown" method payment is larger than the actual order:

REJECTED: A valid amount is required. AVS response: AVS not applicable for this transaction CVV match: -

If it helps, here are the rules that fired on the product submit page:

Commerce Pricing Attributes (default) Calculate taxes: Sales tax (default) Calculate taxes: VAT (default) Reset the cart order status on product add or remove (default) Add to Cart message (overridden) Redirect after product add to Cart (custom) - a page redirect after submit

So - I need some help to debug/fix this:

1) Is there anything obvious I should look at? I have analyzed the setup of all modules, rules, etc.

2) How would what looks like an example payment type be added before even going to any checkout page - when we have the Payment Method Example module turned OFF.

3) And, since there is no error message - where do I even begin to debug this (I am a novice)?

4) Will Devel help? It seems you need some code added to a module. How do I figure out what module, what code, and where to add the code?

Thanks! Any help you can give would be highly appreciated!

# Answer
Fixed it!

When you delete an order on the order page, the associated payment does NOT get deleted. And, once the order is deleted, there is no way to delete the payment in Drupal commerce, since you only have a view of the orders.

Then, when you create a new order, the order number you deleted can get 'reused'. So, the old payment is then associated with this new order. That is why we saw the errant payments on the new orders.

So, I fixed this issue by going into the database and manually deleting all of the errant example payments in the commerce\_payment\_transaction table. So far, so good….

Bottom line: NEVER delete an order once live. Or, minimally, always delete the order's payment FIRST, then the order.
> 0 votes

---
Tags: commerce
---


# Question
Title: How to create a rule triggered when saving a node to schedule sending an email at specified date?
I have a node of content type **task** which has a field **reminder date**. When the node is saved or updated, I want to schedule sending an email to list of users on reminder date.

I have used the Rules module for that, like so:

* Rules events:
    + after node is saved
    + after node is updated
* Rules conditions:
    + node is of type task
    + data comparison: site current date greater than reminder date
* Rules actions:
    + add a variable
    + field list of users(it is entity reference field user is the entity)
    + new. variable members to email
    + added a loop
    + to variable members to mail
    + add action to loop : send mail

The problem encountered is as follows: if I set current date equal to reminder date, then the email is never sent. But when I set a reminder date greater than current date, the mail notification is not sent on the reminder date. I.e. after the current date becomes greater than reminder date, even if the cron is run, the mail is not sent.

I think I need to use `Rules Scheduler` for that, right? How can I go about it?

I also saw a Using fields for setting evaluation time, which mentions these steps:

> * Using flags to load user lists in Rules
> * Scheduling a rules component from a triggered rule
> * Some words about rescheduling the evaluation if the event date should change
> * Using conditions to make fields available in Rules configuration
> * Using a date field to set evaluation time
> * Adding an offset to the evaluation (-1 day)
> * Verifying the configuration by executing the action set manually

How can I implement this?

I also tried the Date Reminder module but it has a limitation that you can send email only if you manually enter the email address or it will send only to drupal user.

# Answer
# Part 1 - Make sure to include "Entity has field"

First eliminate the possibility that the missing piece to make your rule work is because you didn't include a Rules Condition like "*Entity has field*" (related to your **Reminder date** field), as the first Rules Condition.

If you didn't do that yet, then to Rules it is like the value of your **Reminder date** is simply blank. If needed, enable Rules debugging to double check if the value of that Reminder data has indeed the value that you expect. Refer to my answer to "How can I display the value of a variable inside a condition?" for more details about Rules debugging.

# Part 2 - Rework your rule to use the Rules Scheduler

This seems to be a perfect case to actually use the Rules Scheduler (sub-module of Rules). Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", which contains an example of how to use the Rules Scheduler for a variation of your question. The variation is that it is to only eMail 1 user instead of a list of users as in your case, though it uses a field that is similar to your Reminder date field.

The approach using the Rules Scheduler differs from what you tried to do (but couldn't get to work):

* it does NOT use a Rules Condition like "check if this the right moment to send such eMail (now)".
* instead it performs appropriate Rules Action to schedule such eMails for somewhere in the future. Moreover, it takes into account that the actual date for that eMail may even change in between (ie if the Reminder date field gets updated, then don't send that previously requested eMail anymore).
> 1 votes

# Answer
My approach is something like this (without Rules module):

1. assuming that we've installed Elysia Cron module and configured.
2. configured Crontab
3. SwiftMailer library exists in our module directory (or you can register it by Libraries module)

Implementation of Elysia Cron api;

```
function MY_MODULE_cronapi($op, $job = NULL) {
  $items['my_custom_task'] = array(
    'description' => '',
    'rule' => '*/10 * * * *',
    'callback' => 'my_custom_task',
    'arguments' => array(),
  );

  return $items;
}

// example business logic, change this with Yours
function my_custom_task() {

  $node_query = db_select('node', 'n');
  $node_query->join('field_data_field_reminder', 'fdfr', 'n.nid = fdfr.entity_id');
  $node_query->join('field_data_field_sent', 'fdfs', 'n.nid = fdfs.entity_id');
  $node_query->fields('fdfr', array('field_reminder_value'));
  $node_query->fields('n', array('nid', 'title'));
  $node_query->condition('fdfs.field_sent_value', 0, '=')
    ->condition('fdfr.field_reminder_value', array(time()-60*5, time()+60*5),'BETWEEN');
  $node_result = $node_query->execute()->fetchAll();

  $user_emails = db_select('users', 'u')
    ->fields('u', array('init'))
    ->execute()
    ->fetchField();

  if(!empty($node_result)) {
    require_once drupal_get_path('module', 'MY_MODULE') . '/lib/swiftmailer/swift_required.php';

    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
      ->setUsername('GMAIL_USER')
      ->setPassword('GMAIL_USER_PASS');

    $mailer = Swift_Mailer::newInstance($transport);

    foreach($node_result as $key => $value) {
      $message = Swift_Message::newInstance('MY MESSAGE SUBJECT')
      ->setFrom(array('no-reply@'.$_SERVER['SERVER_NAME'] => 'MYWEBSITE.COM'))
      ->setTo($user_emails)
      ->setBody($node_result[$key]->title . ' is reminding!!', 'text/html');

      $mailer->send($message);

      $sent_node = node_load($node_result[$key]->nid);
      $sent_node_wrapper = entity_metadata_wrapper('node', $sent_node);
      $sent_node_wrapper->field_sent->set(1);
      $sent_node_wrapper->save();
    }
  }
}

```

// Improve this callback

By this way you can run Cron job on every 10 mins.. This doesn't provide the full functionality which you need (send by 1 or 2 seconds, but you can set cron job even 5 min)..
> 0 votes

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


title: Rhythem Theme for Drupal Commerce

text:
# Question
Title: Rhythem Theme for Drupal Commerce
Hi does anyone here use Rhythm Theme for Drupal Commerce. I have a problem when I upgrade to the latest version of commerce in that when I go to create a Product Display it only lists 10 products instead of the many products I have. Not sure if this is a problem with commerce or with the theme I am using.

# Answer
> 0 votes
This is actually due to a change in Commerce 1.13 that we didn't have a great way to overcome initially. (More information at: https://www.drupal.org/node/2697017). The issue is with the settings for the product reference field on your node type. If you edit it, you'll find an options list limit setting that you can increase to see the more complete list of products again. Sorry for the regression. :-/

---
Tags: theming, commerce
---


# Question
Title: Which table contains all of the module permission data?
I'm coming into an existing project and the previous developer totally messed up the site. There was a custom module made for a custom field and it shows up in the People \> Permissions page. I cannot set this new entity type to Viewable by anonymous users via the gui interface. I would need to go into the database to make this change. Which tables do I need to look at to find this setting?

# Answer
To modify the permission data via drush command line. I first had to find the permission name by right click the checkbox on the module page and inspect element, in my case it was **3\[view any office office\]**

The table responsible for permissions is: **role\_permission**

I then goto the terminal and insert the following query:

```
drush sqlq 'insert into role_permission values(3,"view any office office", "office")'

```

3 is the role number then the name of the permission (view any office office) and then the module name (office).
> 1 votes

---
Tags: 7, users
---


# Question
Title: Some templates are not properly compiled to Twig
I have a few templates that are failing when compiling them in twig. What is happening is that the **\Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::save** method will create a temporary file like **files/php/twig/.0c781c5196** and then it tries to rename this file into something like **files/php/twig/DIRECTORY/FILE.php** but it fails with **No such file or directory**.

The target directory exists, it even has .htaccess. On each page refresh, I get different temporary and target file names.

I tried to manually copy and rename the file but on each page load the ID's change so it never works.

The template hasn't been edited and it always worked just fine(it renders properly even without compiled twig). Any idea what can be causing this?

---

It looks like this is only a single template issue. Due to the ever changing IDs, I thought there were more.

This is happening on my local windows machine right now so I though there might be an issue with those crazy long directory and file names but I can manually rename the file.

The length of the directory name is 134 characters which are well below 260 maximum.

---

**UPDATE 27.6:** I have experienced this same issue on another Drupal 8 project. So it looks like it is not a unique problem but rather universal but I still haven't figured out what the issue is.

# Answer
> 1 votes
OK! So I have figured it out. I think this is a Windows-specific bug because, on another project where I have experienced this as well, people with macs do not have this issue.

Anyway, what is causing it is `\Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::getFullPath`, specifically `return $directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';`

If the template name is too long, **which can easily happen with theme suggestions**, it will cause PHP to fail to perform the `rename()` operation successfully. I don't know why it stores the code in a temporary file and then it copies it into target directory instead of creating it directly in the target directory and/or file but that's how it is.

I have no idea why we need so freaking **long** directory and file names when they only hold a single file but beside this, Drupal 8 is great.

# Answer
> 0 votes
Something lower than the PHP level is obstructing `rename()` from moving the temp file to a PHP file. Without knowing more details about the hosting environment (e.g. is WIMP/WAMP, VM, etc.?), one could only guess at what's causing the problem.

It sounds like something is preventing the PHP/server process from writing \*.PHP to your server directory. For example, a naive security mechanism, seeing a server process writing PHP files to your web server, might be stopping it as potential code injection attack. But again, that's a guess.

Since you know where it's occurring (and presumably how to recreate it), the battle is already half won. The next step is to look at anything in your hosting environment that might be causing the problem, and try to tweak/relax restrictions until PHP is able to perform the operation.

# Answer
> 0 votes
I'm glad you figured out the main culprit, I believe the solution here is to limit windows native stuff as much as possible, unless, and only, if your online server will also be windows?

Try Aquias dev box app https://www.acquia.com/products-services/dev-desktop

The awesome Kalabox (still in heavy development).
http://www.kalabox.io

Create your own (or use existing) drupalized virtual server similar to your online environment with the VirtualBox app. https://www.virtualbox.org

With all of the above free options, you can still use Drush, git, git-bash and windows CLI or puTTy to manipulate your sites.

The only caveat...
if your chosen setup from above uses shared folders synched between the two os's, which is useful for easy edits and locally running SASS compilers, grunt, and all the other CLI and NPM goodies. Sometimes with these shared folders you can have trouble trying to delete long named directories if for some reason the virtual server didn't delete directories leaving behind garbage on your windows os.

First try to log into your virtual server and delete the files from that CLI, if you cannot for some reason, then you'll have to use windows command line tools to overcome the limit, or bulk rename all the folders to short name etc. Windows can deal with deep large named directories just fine, but for some odd reason they put a cap for simple user delete functionalities.

---
Tags: theming, 8
---


# Question
Title: Search API / Facet API hierarchy based on taxonomy term reference across vocabularies
With Search API \+ Facet API it is possible to create search facets for taxonomy term reference fields, that reflect the hierarchy of terms in the vocabulary, based on the taxonomy\_term\_parent table. (With Facet API Taxonomy Folding it is even possible to browse these hierarchies as folders.)

Sometimes hierarchical information is not represented in the taxonomy\_term\_parent table, and the relations exist between terms of different vocabularies.

E.g. in a site I am building, a "Product series" has a term reference field to "Product family", which has a term reference to a "Supplier". Suppliers, Product families and Product series are 3 distinct taxonomy vocabularies.

Some products only have a supplier. Others have a supplier and a product family. And some have all three. If a product has a series, then its product family is the same as that of the series. And if it has a product family, then the supplier is the same as that of the product family.

I would like to expose this structure as one hierarchical facet, similar in appearance and behavior to that for a single hierarchical vocabulary.

Any ideas?

What I managed so far is to assemble the terms from different vocabularies into a common entity property. I also managed to unify the two different "parent term" relationships (series -\> family, family -\> supplier) into a common entity property. But then what?

# Answer
> 0 votes
One alternative, which is not quite the same, is to use dependencies between facets.

So, the product families facet is shown only if a supplier is chosen. And the product series facet is shown only if a product family is chosen.

With hook\_block\_view\_alter() one can rewrite the block title, so that the product family facet block says e.g. "Acme product family", if "Acme" is chosen as a supplier.

Again, this is not quite the same. But it provides an acceptable user experience, I would say. And it might be a suitable solution for some visitors of this question.

---
Tags: search
---


# Question
Title: How do I override the title with the username?
I am creating a view that will be visible under /user/%/blog, and I am trying to override the view's title with the username (e.g. *kiamlaluno's blog*), but the description of the field doesn't tell me what I can use to override the title.

>

I only get I can use Twig syntax, but that doesn't help much.

I used *Content: Authored by* as contextual filter. I also added *author* as relationship, but I didn't see any change.

How can I override the title with the name of the user authoring the nodes being shown from the view?

# Answer
> 4 votes
You can switch the node's uid argument plugin to `Drupal\user\Plugin\views\argument\Uid`, and get the same behaviour from that field instead. It would take a small amount of code in a custom module.

```
function MYMODULE_views_data_alter(&$data) {
  $data['node_field_data']['uid']['argument']['id'] = 'user_uid';
}

```

Alternatively, if passing the author's username in the view URL is not a problem for you, since you have the author relationship set up, you can use the `User: User ID` field for your filter instead of the one you're currently using. Because of the way its handler treats requests for titles, using `{{ arguments.uid }}` in the "Override title" field will actually provide you with the username(s) instead of the ID(s).

# Answer
> 5 votes
1. Make *Fields* the format used by the view

>

Alternatively, if you are using the rendered entity row plugin check the *Force using fields* in *Format | Settings*

2. In *Relationship*, add *Content author*

* Checkmark ☑ *Require relationship*
3. In *Fields*, add *Name*

* Checkmark ☑ *Exclude from display*
    * Uncheck ☐ *Link to the user*
4. For *Title* put `{{ name }}'s blog`

>

You could put it as contextual filter; even though `{{ name }}` is not listed as a replacement pattern, it works (as long as you do step 1, 2, and 3)

>

## Result

>

### Bonus

If you want to capitalize the first letter of the user name use `{{ name|capitalize }}'s blog`.

You can also add a *Rendered Entity* as a field.

>

>

---
Tags: views
---


title: How to show dates and times separately?

text:
# Question
Title: How to show dates and times separately?
I have set up events with calendaring on my site along with an agenda view. Each event has a date, possible start time, possible end time, and possible end date/time.

Therefor I have two date fields associated with this content type - field\_date(value, value2) where value is the start date/time and value2 is the end date/time.

How can I show dates and times separately so that I can use CSS to make a pretty agenda view using something like the following markup?

```
<div class="item even">
<span class="event-month-day">September 21</span><br>
<span class="event-title">Fall Solstice (all-day-event)</span>
</div>

<div class="item even">
<span class="event-month-day">October 18</span><br>
<span class="event-title">Fall Festival</span><br>
<span class="event-time">10:00 am to 11:00 pm</span>
</div>

<div class="item even">
<span class="event-month-day">October 21-25</span><br>
<span class="event-title">Sign up for pie eating contest</span><br>
<span class="event-time">9:00 am to 4:00 pm</span>
</div>

```

I've looked at using the formatter module (explained here: how do I add extra classes to a date field at views?) but could not figure out how to use the formatter with two date variables for my Event content type.

Any help?

# Answer
I had to do something similar recently. I created a views page and outputted the same Date field twice. I also had two different date formats set up. One showing only Month and Day, and the other format only showing time. Then I assigned the first "Date" field the date format, and the other the "time" format. Afterwards I was able to style them as I pleased.

In the field date settings, I had it to where it also showed multiple, but only first and last with a " - " seperator in order to output "September 11 - September 14" for example. The same can be done for the time formatted field.
> 1 votes

# Answer
Create two Formats under the below link one for the date and second for the time.

admin/config/regional/date-time/formats/add

After Create 2 formats as suggested, Add Date types of those two format under the below link

admin/config/regional/date-time/types/add

Now go to your view page and add that date field twice with one format of date and one format of time.

Make one of that field exclude from the display and in the other field you can use rewrite result and pass the structure what you want.
> 1 votes

---
Tags: theming, datetime
---


# Question
Title: How to change the image style for image preview in node-add/edit form?
IN a related question, "How to set image style for media browser in node edit form?" one response noted that "Once you have chosen the image and clicked save and the overlay is closed, images are display in the "Media thumbnail" image style."

How can I change this automatic behavior such that the preview image is displayed in my custom image style?

# Answer
**If you are** using the Media module, I couldn't find a way to change it so it doesn't use the "Media thumbnail" image style. But what you could do is edit the "Media thumbnail" image style by going to `/admin/config/media/image-styles/edit/media_thumbnail` and clicking on the `override` button which will let you edit it to your liking. (Tested on Drupal 7)

---

If **you're not** using the Media module, you can by going to your content type's Manage Fields and clicking on edit for your image field. Scroll down a bit until you see **Preview image style**
> 0 votes

---
Tags: media
---


# Question
Title: Search API- Force taxonomy terms to be indexed as one language
I have a non-multilingual taxonomy on a multilingual site. All of the terms in the taxonomy are in English.

However, since this is a taxonomy of locations, some of the translations of the names of states/prefectures are in the database as part of the general interface translations.

I have a search index in Search API that indexes the taxonomy terms (field reference on a node) as type **taxonomy term**. Somehow, Search API is sometimes picking up the translations when it is doing the index, so I get results like this:

* Tokyo (50)
* 東京 (25)

These are both Tokyo, just some of the entries are converted into Japanese. The only thing I can think is that the author language is set to Japanese for the nodes that are coming up as Japanese. However, when I display the data in a view, all of it shows up in English.

So, how can I force Search API to ignore translations when indexing taxonomy terms?

# Answer
> 0 votes
One workaround: since I didn't need the translations in my case, I could go to the Translate UI screen and search for them and delete them one-by-one. A real pain, but at least it cleared up the problem.

---
Tags: search
---


# Question
Title: How to show difference between views page and views block
I have created a view page, to this same page I will add a block by clicking on add button. So whatever changes I will do in the block is affecting the view page also. So how can I configure this, so that my block changes should apply only to block and not to page.

# Answer
Using **This page override** option in view field configuration instead of **All display**
> 0 votes

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


title: Creating a job portal system

text:
# Question
Title: Creating a job portal system
I want to create a job system with the following workflow:

1. Administrator can add the jobs.
2. A page for job listings.
3. On detail job there should a link of apply for this job.
4. The form will contain the fields and upload application form.
5. **The back end must display the number of application received for respective job.**
6. On click on number of application received for respective job the see the list of Application received list for particular job category.

I have tried it with the Views and the Webform module.

Created a view for job listing and use webform for apply form. But **what should I do with the trackers in point 5?**

# Answer
I would implement this in the following manner:

1. Two content types: Job opening & Job application
2. Job openings to have fields like : Job description, current CTC, expected CTC, etc.
3. Job application to have fields like : Cover letter, experience, resume (file upload), etc.
4. **Important**: In job application content type, add an entityreference field that refers to Job openings.
5. Give permission to company user to create job opening; and normal user to create job application.

With this architecture, you should easily be able to build the views as entityreference module provides two very powerful relationships:

1. Entity reference: Referenced entity (Job opening)
2. Entity reference: Referencing entity (Job application)
> 4 votes

# Answer
I've never used the Webform module, so this is just a hypothetical / shot in the dark suggestion (assuming somehow your webform links with your Job opening node).

Add a Numeric field to your Job Opening content type.

With Rules and Webform Rules you can react when a Webform is submitted. So when webform is submitted, Add action of set a data value, you can add an offset of +1 to your numeric field. (you may need to click on `Switch to something input mode` to get the offset option)

The tricky part in the rule would be linking your webform with the correct job posting node. If you can figure out this part, you're golden.

Lastly, you would just add the numeric field to your view.

> **BONUS**: You could use Field Permissions to hide your numeric field from node edit view.
> 0 votes

---
Tags: 7, views, webforms
---


# Question
Title: When making a new core release, how do mantainers tag the core modules and update their info files?
When Drupal maintainers make a new core release, how do they tag the core modules and update their info files? I have noticed that all the core modules of Drupal 7.43 have a section in their info files that looks like this:

```
version = "7.43"
project = "drupal"
datestamp = "1456343506"

```

Is there an automated procedure that runs GIT to merge branches, tag releases and updates the info files accordingly?

# Answer
> 2 votes
Yes, it is an automated process, check below:

> The version string will be added by drupal.org when a release is created and a tarball packaged. However, if your module is not being hosted on the drupal.org infrastructure, you can give your module whatever version string makes sense (eg. see Release naming conventions).

**NOTE: The above description is exact copy paste from Drupal.org link.**

---
Tags: version-control
---