# Question
Title: How to apply some rules to fields in native contact form?
I use the native Drupal 8 contact form with different custom fields.

I need to apply some rules more precise than the classic "required". For example, telephone number accepts only numeric characters and needs to be filled with 10 characters.

What is the best approach to do that with Drupal in a native way ? Is there a module that can do it ?

I can do it with jQuery but i would like to do it on a server side way.

# Answer
If your real case is the telephone example, you need to enable the Telephone module that comes with Drupal 8 Core. Then add the telephone field to your contact form in "Manage Fields".

If you think you're doing something "popular" chances are high that someone already did it (ie Telephone module), so don't rebuild the wheel.

If your scenario is some special use case, then you want to do a custom form validation for your form field. See How do I add a custom validation to an existing form/field?
> 1 votes

---
Tags: forms, rules
---


# Question
Title: How to get Fixed Navigation when scrolling to the top
I am using this module Single Page Site to get a single page and it works well. However I want to get the navbar fixed when scrolling up the page but I cannot figure out how and where to put this jquery code in my site.

```
$(document).ready(function () {

  var navbar = $('.navbar');
  var origOffsetY = navbar.offset().top;

  function scroll() {
     if ($(window).scrollTop() >= origOffsetY) {
         $('.navbar').addClass('.navbar-fixed-top');
         $('.main-container').addClass('menu-padding');
     }
     else {
        $('.navbar').removeClass('.navbar-fixed-top');
        $('.main-container').removeClass('menu-padding');
     }

  }

  document.onscroll = scroll;
  });

```

Actually what I am trying to achieve is something similar to this website http://www.orisnv.be which itself using the modules Single Page Site.

I appreciate any help or hint.

Thanks.

# Answer
> 0 votes
It turns out the answer is simple. I just declare the javascript inside .info file. And by using Drupal.behaiors I implement the jquery that target the navbar to fix upon scrolling.

---
Tags: javascript
---


# Question
Title: Email notification based on purchased item
I am working on the magazine site using Ubercart. In this site individual magazines can be bought or subscribed to. When a new issue of a magazine which the customer has subscribed to is created, I need to send a notification to all the customers who have subscribed to that magazine.

Can I achieve this using the messaging and notification module? Is there any other way?

# Answer
Have you tried rules? The trigger would be when new content is added, and the condition would be that the content type is appropriate. Not sure how you've stored the data connecting subscribers to their magazine, but that will be needed for the action. I *don't think* you'll be able to do this out of the box (specifically I'm not sure if you can send an email to multiple addresses using rules) - so you might need to write a custom action.
> 1 votes

# Answer
You may try the Notify module. It allows users to subscribe and also unsubscribe (usefull feature) to your mass mailing. You can also setup multiple mass mailing. You can also mass mail everyone on your site.

Some more details about this module (from its project page):

> The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.
>
> Even if this feature is not configured for normal site users, it can be a useful feature for an administrator of a site to receive notification of new content submissions and comment posts.
>
> The notifications are sent out in batches (digest style) at a frequency determined by the administrator. The administrator also decides what content type(s) to make available for notification subscriptions.
>
> In the Drupal 7 version, ordinary users can turn notifications on and off, whether to receive just headlines, teasers, or complete nodes/comments, and what content types to subscribe to. (The Drupal 6 version only offer some of these options.)
> 0 votes

# Answer
Maybe the Who Bought What|Ubercart module can be useful for your case.

> This is for Ubercart. If you are using Ubercart to sell tickets or entries to an event or perhaps a race, it's very helpful to have a list, per item, of who bought what. For a competition, this will become an entry list. For a performance, this may become your will-call attendance list.

The Drupal 8 version has been created as separate project: Who Bought What (Ubercart).
> 0 votes

# Answer
@Andy

I am using \[Commerce Invoice/Reciept\]\[1\] module.

with a php code in main template file **commerce-order-invoice-view.tpl.php** something like below :

```
   $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $order->commerce_line_items['und'][0]["line_item_id"]);
   $product_sku = $line_item_wrapper->commerce_product->sku->value();

    if($product_sku =="ONCE_OFF")
    {
      include 'commerce-order-invoice-once-off.php';
    }
    else
    {
      include 'commerce-order-invoice-recurring.php';
    }

```

After that you can create new files for emails. FYI : $order object will be available in both files.

Hope this helps.

```
  [1]: https://www.drupal.org/project/commerce_invoice_receipt

```
> 0 votes

---
Tags: 7, ubercart, emails, notifications
---


# Question
Title: Custom text in a View that Links to a PRODUCT (not a node)
I'm using Drupal Commerce and a View that displays all my products of a certain type.

The first item displayed in the view (for each product) is the Title and it is helpfully linked to the product page.

I also want to add another link to the product page that says 'Register Now' but I can't figure out how to create custom text that also links to the product page!

I've tried adding the product UUID, ID, and 'Link to Product' fields in my View...and putting them above my 'Custom Text' field...but none seem to work.

When I use {{ id }} for example (as the link in the custom text field), it just makes the link '/id' ...but that's not the actual link to the product, so naturally I get an error. The same problem persists for the other referenced fields.

So...anyone know how to create custom text that links to the actual product?

# Answer
Option A)

You could add another `Title` and then simply override the `title` so it says `Register Now` by Rewriting the results of the field.

Option B)

Add `path` as a field and exclude from display.

Add a `Custom Text` and checkmark display this field as a link and use `{{ path }}` as your url.
> 1 votes

---
Tags: views, 8, commerce
---


# Question
Title: Is it possible to turn off Ajax load for Commerce Coupon Module?
I am getting a bunch of issues with the Commerce Coupon module 7.x-2.0-rc3. Mainly there are inconsistencies with the forms updating and also intermittent timeouts. I'm assuming it's an Ajax load issue.

Is there a way to turn off the Ajax load when a coupon is applied, and just get a regular page load?

# Answer
Maybe you run into this bug https://www.drupal.org/node/2412549.

Apply the two patches mentioned in comment #9

> If you really want to turn of AJAX, you need to hook all the corresponding forms and unset #ajax.

**i would not suggest this thoe !**
> 0 votes

# Answer
The site is in production, but it is broken at the moment. I would advise :

1. Disable the faulty module, for a while, so that the site continues to run and people are not seeing a mess.
2. using `drush ard`, get a an archive of the current site and run it locally.
3. Check what modules you can update related to the commerce layer, especially coupons and shipping. Do this one by one and look at when your problem is solved.
4. Do the same update directly on prod with : `drush up module_name1 module_name2` (If you don't have command line access you are good with the normal upgrade process from the backend also)
5. Special advise : you should use this opportunity to update also all modules with a security alert after have tested offline if this doesn't break anything.
6. As mentioned by rémy, disabling ajax is likely to be very hazardous, however it is possible to do that on specific modules, and for this you can refer to Disable AJAX in a form
> 0 votes

---
Tags: commerce, ajax
---


# Question
Title: Is it possible to search a view of views?
I have a View that is a list of users. One of the fields is an Include View field.

This field includes another View which has a contextual filter for the user, and shows the node that was created in a certain month by that user (if it exists).

These nodes have categories and I would like to have a filter on the main view where I can sort out which users have a node in a certain category. But due to the nature of included Views, I can't find a filter that works.

Is there a way to search a view that is an Include View?

# Answer
> 0 votes
Under Advanced (located on the right side), for Relationships add `Content Authored`

Then in Filter (located on the left side) add `Content Type` and expose the filter.

---
Tags: 7, views
---


# Question
Title: Using Rules to create a Comment with multiple fields formatted in the Main Body Text
I'm trying to create a Rule that will create a comment on another post when a node is created. I would like the comment to contain a number of fields from the original post in a formatted manner.

For example: I have a content type called "Project Status Reports" which has 3 text area fields: `field_preparation`, `field_methods` and `field_outcomes` and a node reference field: `field_project_node`.

When a Project Status Report is created, the user selects a node to associate it with (in `field_project_node`) and fills the 3 text areas.

I would like to create a Rule that gets triggers when a Project Status Report is created, which will then make a comment on the node referenced in `field_project_node`. I would like the body of the comment to look something like this:

```
<h4>Preparation</h4>
<p>[node:field_preparation]</p>
<h4>Methods</h4>
<p>[node:field_methods</p>
<h4>Outcomes</h4>
<p>[node:field_outcomes]</p>

```

I have created the Rule successfully and have it triggering however I am unable to work out how to fill the `Main Body Text` of the comment with formatted text which will do the replacements. All I can seem to do is either add static html or have it post a single field.

Is this possible? Thanks in advance

# Answer
### Step 1: Getting around a known comment body limitation

I think the core of your question relates to what's written in Comment # 10 of the Rules (support) issue titled "Access and Set Comment extra fields", i.e.:

> ... `param_comment_body` doesn't assume any data types except 'formatted text' ...

This issue includes a Rule example that looks like so:

```
{ "rules_test" : {
    "LABEL" : "Comment bot",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_update" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : "zzz",
            "param_node" : [ "node" ],
            "param_author" : [ "node:author" ],
            "param_comment_body" : { "value" : {
                "value" : "This text will be replaced in the next action.",
                "format" : "filtered_html"
              }
            }
          },
          "PROVIDE" : { "entity_created" : { "new_comment" : "New comment" } }
        }
      },
      { "data_set" : {
          "data" : [ "new-comment:comment-body:value" ],
          "value" : [ "node:field-status" ]
        }
      }
   ]
  }
}

```

The clue to solve your issue (= work around?) is to rework your exported rule (as in revision 1 of your question) so that it uses that last Rules Action starting with "`data_set`".

### Step 2: Combining 3 fields

However, since in your case you want to combine those 3 text area fields, you should also include these extra Rules Actions (prior to that Rules Action starting with "`data_set`"):

* `Add a variable` (to use as your comment-body later on), say with machine name like `variable_for_comment_body`.
* 3 (similar) Rules Actions to `Set a data value`, for variable `[variable-for-comment-body]` (added in the prior Rules Action), whereas each of these 3 Rules Actions will refer to the value of each of your 3 text area fields.

For an example rule where you can see this technique at work, refer to my answer to "How to use Rules to send an eMail with a body containing all items of a field collection?" (you don't need a Rules loop though, just those 3 similar Rules Actions.

And with the above logic in place, theh value in your last Rules Action starting with "`data_set`" simply becomes `[ "variable-for-comment-body" ]`.
> 2 votes

---
Tags: 7, entities, rules, comments
---


# Question
Title: Auto-increment field based on value of another field
How can I have a computed field (field B) that has an auto-incremental number but based on the value of another field (field A).

For example: I create a node with value "Location X" in field A. Field B should get value X001, I create a second node with value "Location Y" in field A. Field B should get value Y001. I create a third node with, again, value "Location X" in field A. Field B should get value X002. And so forth

# Answer
Checkout hook\_node\_presave() here you can set the values dynamically. And variable\_get() and variable\_set() for the increment.

With str\_pad() you can add the starting zeros to the increment.

```
hook_node_presave($node) {
  if ($node->field_A[LANGUAGE_NONE][0]['value'] == 'Location X') {
    $increment = varibable_get('LocationX_increment', 0);
    $increment++;
    $node->field_B[LANGUAGE_NONE][0]['value'] = 'X' . str_pad($increment, 3, '0', STR_PAD_LEFT);
    variable_set('LocationX_increment', $increment);
  }
}

```

You don't need to save the node in this hook, just change the value of the field.
> 1 votes

# Answer
I have a solution for you. Create a custom module and do some coding like given below. In my case my module name is `comm_support` content type name is `Field Depen (Machine name: field_depen)` and fields are `Field A (Machine name:field_field_a)` and `Field B (Machine name: field_field_b)`. Also install jQuery Update module.

Use `hook_form_alter()` to define a custom form after build function.

````
/**
 * Implements hook_form_alter().
 */
function comm_support_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'field_depen_node_form') {
    $form['#after_build'][] = '_custom_after_build';
  }
}

````

After this implement custom after build function a add a custom js file to your node form. After adding custom js file we will pass base url to our custom js file so that we can use base url on our ajax call url parameter.

````
/**
 * Implements custom after build function.
 */
function _custom_after_build($form, &$form_state) {
  global $base_url;
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'comm_support') . '/js/comm_support.js',
  );
  drupal_add_js(array('comm_support' => array('base_url' => $base_url)), array('type' => 'setting'));

  return $form;
}

````

Now create a js file inside `your_module/js/comm_support.js` and paste this code to js file.

````
/**
 * @file
 * A JavaScript file for the comm_support module.
 */
(function ($, Drupal, window, document) {
    'use strict';
    Drupal.behaviors.comm_support = {
        attach: function (context, settings) {

            // Place your code here.
            $('input[name="field_field_a[und][0][value]"]').on('change', function () {
                var field_a = $(this).val();
                var base_url = Drupal.settings.comm_support.base_url;
                $.ajax({
                    url: base_url + '/comm-support/get-field-b/',
                    type: "post",
                    dataType: 'json',
                    data: { "field_a" : field_a },
                    success: function (d) {
                        var field_b_val = field_a.split(' ');
                        $('input[name="field_field_b[und][0][value]"]').val(field_b_val[1] + '00' +  (d + 1));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(errorThrown);
                    }

                });
            });
        }
    };

})(jQuery, Drupal, this, this.document);

````

Implement `hook_menu()` for registering ajax callback path.

````
/**
 * Implements hook_menu().
 */
function comm_support_menu() {
  $items['comm-support/get-field-b'] = array(
    'page callback' => '_get_field_b_value',
    'access callback' => true,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

````

In ajax callback function fetch if Field A have exiting node with same location and get result count.

````
/**
 * Implements callback function to fetch field A value count.
 */
function _get_field_b_value() {
  $str = check_plain($_POST['field_a']);
  $query = db_select('field_data_field_field_a', 'f');
  $query->fields('f', array('entity_id'))
      ->condition('bundle', 'field_depen')
      ->condition('field_field_a_value', $str);
  $result = $query->execute()->rowCount();

  echo drupal_json_encode($result);
}

````

Now clear the cache and this is the complete solution.
> 0 votes

# Answer
You could try Rules and PHP to get this done. After a node is created, execute some PHP code where you query the database and count the number of nodes with the same Field A value (using a token for the current value of the node saved). Then you get your auto-increment value (eventually stored in an hidden field as "Location number"). You may modify the display with sprintf() to get your leading zeros. Then you add a second Rules action to set a data value and create your field B value as field A value token + Location number token.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Display values in the order they are in the form field
I created a field called *Authors*, that can take multiple values (*Users* registered on the site). I would like to display the authors in the same order I add them in the field.

They are currently displayed with no logical order (it is neither the order they appear in the field, nor the alphabetical order, nor the UUID of the users...)

# Answer
> 0 votes
Finally I've found the cause of the problem : the use of *Selection list* or *Chosen* as widgets for the field.

Using the *Autocomplete* widget, it works fine : the order of the values in the back-end is conserved in the front-end.

---
Tags: entities, users
---


# Question
Title: Is there a way to alter output/markup for a field in node edit view?
I am looking for a way to alter field output when rendered in the normal edit view.

I have looked at the hook\_quickedit\_render\_field function which helps out in quick edit mode but are there something similar for the normal edit view? Drupal 8.

# Answer
You can use hook\_form\_alter or hook\_form\_FORM\_ID\_alter

You'll need the ID to target specific forms; otherwise, you will endup altering every single form. See How can I find the form ID of a form?

Example of hook\_form\_FORM\_ID\_alter:

```
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if ($node->getType() == 'article') {
    // Alter the 'article' form here.
  }
}

```
> 2 votes

---
Tags: 8
---


title: Custom form block not working

text:
# Question
Title: Custom form block not working
In my custom module I have created custom for like below: Path: custom\_module/src/Form/UserType/UserType.php

```
<?php
/**
 * @file
 * Contains \Drupal\resume\Form\UserType.
 */
namespace Drupal\custom_module\Form\UserType;

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

class userType extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_type_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $user_types = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('user_type');
    $user_type_options = array();
    foreach ($user_types as $user_type) {
        $user_type_options[$user_type->tid] = $user_type->name;
    }

    $form['user_type'] = array(
      '#type' => 'select',
      '#options' => $user_type_options,
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }
}

```

Then I created a block in following path: custom\_module/src/Plugin/Block/UserTypeBlock.php

```
<?php
/**
 * @file
 * Contains \Drupal\custom_module\Plugin\Block\UserTypeBlock.
 */
namespace Drupal\custom_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;
/**
 * Provides a 'user_type' block.
 *
 * @Block(
 *   id = "user_type_block",
 *   admin_label = @Translation("User Type block"),
 *   category = @Translation("Custom")
 * )
 */
class UserTypeBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\UserType');
    return $form;
   }
}

```

But after assign the block in to a region I'm getting following error:

> InvalidArgumentException: The form argument Drupal\custom\_module\Form\UserType is not a valid form. in Drupal\Core\Form\FormBuilder-\>getFormId() (line 190 of C:\wamp\www\www\_mysite\_com\core\lib\Drupal\Core\Form\FormBuilder.php).

# Answer
> 2 votes
The php file of the form is in a subfolder, but the class name in getForm() does not reflect this.

Change the location of the php file from

```
custom_module/src/Form/UserType/UserType.php

```

to

```
custom_module/src/Form/UserType.php

```

and

```
namespace Drupal\custom_module\Form\UserType;

```

to

```
namespace Drupal\custom_module\Form;

```

---
Tags: forms, blocks
---


# Question
Title: Disable ajax from exposed form filter only
Is it possible to disable the Ajax from the exposed form filter only and not the whole view action \[sorting - paging\] !?

# Answer
You can use better exposed filter module for this Set Use AJAX to Yes under Advanced -\> other section Set Exposed form style to Better Exposed Filters and keep auto submit option disabled in BEF Settings.
> 1 votes

# Answer
If you can use js then this code will help you

```
$("<filter field Id>" ).change(function() {
        event.preventDefault();
        $( "<filter form id>" ).submit();
    });

```
> 1 votes

---
Tags: views
---


# Question
Title: How do i add a background image to a imput submit button in my module?
So i have a input submit button that needs an image.

I've been looking at the module styling documentation where it says i can attach the styling to a render array of a block plugin. What does this mean and how do i do this? I'll include the trimmed down code where i want to include this styling.

LoginBlock.php:

```
class LoginBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('plugin.manager.pixelpin_openid_connect_client.processor'),
      $container->get('form_builder')
    );
  }

  public function build() {
    return $this->formBuilder->getForm('Drupal\pixelpin_openid_connect\Form\LoginForm');
  }

}

```

LoginForm.php:

```
class LoginForm extends FormBase implements ContainerInjectionInterface {

  public function buildForm(array $form, FormStateInterface $form_state) {

        //submit button that i want to add styling too

          $value = 'Log in Using PixelPin';
          $label = 'Log in Using PixelPin';

          $form['pixelpin_openid_connect_client_pixelpin_login'] = array(
            '#type' => 'submit',
            '#value' => t($value, array(
              '@client_title' => $client['label'],
            )),
            '#name' => $client_id,
            '#prefix' => '<div>',
            '#suffix' => '</div>',
          );
    }
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    //code
  }

}

```

pixelpin\_openid\_connect.libraries.yml:

```
pixelpin_logo:
  version: 1.x
  css:
    theme:
      css/style.css: {}

```

style.css:

```
#edit-pixelpin-openid-connect-client-enable-login {
  background: #f0f0f0 url(/ppicon.png) no-repeat center;
  cursor: pointer;
  height: 26px;
  margin-left: 0;
  margin-right: 0;
  overflow: hidden;
  padding: 0;
  text-indent: -9999px;
  direction: ltr;
  width: 34px;
}

```

# Answer
You can attach it to any render array; the submit button itself seems as good as any:

```
$form['pixelpin_openid_connect_client_pixelpin_login'] = [
  ...
  '#attached' => [
    'library' => [
      'pixelpin_openid_connect/pixelpin_logo',
    ],
  ],
  ...
];

```
> 1 votes

---
Tags: theming, 8, plugins
---


title: How do I add a subheading to a view?

text:
# Question
Title: How do I add a subheading to a view?
I have created a custom content type to upload documents in English and French.Currently using views module I am listing the uploaded files based on date of creation,now I have to categorize the files on list view based on the language(en/fr).

**Existing view**

Docs

* French1
* French2
* English1
* French3

I have to separate the listing based on document language and display it as two blocks with different title.

**Required view**

French Docs

* French1
* French2
* French3

English Docs

* English1
* English2
* English3

**Edit**

I have achieved this using View module itself.

* First I have created the option to choose uploaded language and sort order in the content type.
* Created a view to display French Docs in the required order.
* Included the view block for English in the Footer section of views for French like : Global: View area (Global: View area)

# Answer
> 1 votes
Well, drupal can't know the language used in uploaded files unless the user or an admin specifies so.

A simple way to achieve what you want is to-

1) Have a checkbox field holding the values "English or French" in your custom content-type.

2) And then you can create two views, one holding **"English docs (filter:Checkbox=English)"** and the other **"French docs (filter:Checkbox=French)"**.

3) Embed one view into the other as a view field using Views Field View.

> views\_field\_view allows you to embed one view into another view and pass arguments along.

---
Tags: views, 8
---


title: How can I make user:name to link?

text:
# Question
Title: How can I make user:name to link?
I would like to create a user list which there are usernames as links in.

I create a view: Format show: rendered entity. In panelizer I put the "user:name" in content. But is doesn't display as link.

If I set "panel fields" instead of "rendered entity", than I can set it linkable.

But in panelizer there are not such setting.

How can I solve this?

# Answer
You can do this via rules:

1. Create a view, lets say unformated list with fields.
2. Add the **username** field and the path field
3. In the **path** field settings select **exclude from display** box and in the rewriting results, check the box **use absolute url**
4. Go to **username** settings field and then goto rewrite results and click on the box: **generate field as link.**
5. Small textbox will appear, write inside: **\[path\]**
6. Make sure to **reorder** the field so that the path field will be above the username field
7. From here you can use your view inside your panel.
> 0 votes

---
Tags: views, users, panels, navigation
---


# Question
Title: Translation of select field allowed values
I have a field that has just one option to choose. It's:

Online|This product will be delivered online

I'm struggeling to make it translatable, but with no luck. I've checked everywhere and I stucked. So, in database there is core locales\_source table that holds english phrases. There is a source and context of this phrase:

```
lid: 39
location: field:field_product_delivery:#allowed_values:Online
textgroup: field
source: This product will be delivered online
context: field_product_delivery:#allowed_values:Online
version: 1

```

There is also locales\_target table that contains translations and there is:

```
lid: 39
translation: Este producto se ofrece online
language: es
plid: 0
plural: 0
i18n_status: 1

```

Still, the value is displayed in English on Spanish node view page. How to force it to use correct translation, not the english phrase. By the way, my default language set in Drupal is Spanish.

# Answer
> 2 votes
Make sure you enabled the *Field Translation* module, a submodule (i18n\_field) of the i18n module. Some more details about it (from the Community documentation):

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

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

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


# Question
Title: Views doesn't split content into seprates list items
I need to produce a list of images with views 3 but these group items in only one li element...like this:

```
    <ul class="rslides">
       <li class="views-row views-row-1 views-row-odd views-row-first views-row-last">
              <div class="field-item field-item-0">
<img src="//xxx:3000/sites/all/media/imagecache/MG_illustration_170x310/diapo_lycee/2017/22/abstract-h-c-1107-1142-8.jpg" alt="Lycée Marie Gasquet" title="Lycée Marie Gasquet" width="170" height="310" ></div>
    <div class="field-item field-item-1">
<img src="//xx:3000/sites/all/media/imagecache/MG_illustration_170x310/diapo_lycee/2017/22/city-q-c-640-480-4.jpg" >
</div>
  </li>
          </ul>

```

How can I force it to put items in is proper li element?

# Answer
> 1 votes
Assuming all of these images are in a multi-value field:

1. Make sure your view is showing "Fields" instead of "Teaser" or some other display setting
2. Add your multi-value image field through the Fields section "Add" button
3. Configure the field by clicking on it. You should see a pop-up window with collapsible sections at the bottom - the top section is "Multiple Field Settings". Open that section. Turn on the setting "Display all values in the same row"; when you click that, it'll open the "Display Type" options, for which you'll pick either "Ordered list" or "Unordered list" (assuming unordered list, since you use in the question's code).

---
Tags: views, theming, 6
---


title: drupal 8 tablesorting not working

text:
# Question
Title: drupal 8 tablesorting not working
I am using the code below in a custom drupal 8 module to produce a table but the table does not sort when I click on the header, although the little arrow changes direction and the url indicates the sort order is different.

```
$headers = array(
      array('data' => t('Name'), 'field' => 'name', 'sort' => 'desc'),
      array('data' => t('Date'), 'field' => 'changed_date')

      );
$order = tablesort_get_order($headers);
         $sort = tablesort_get_sort($headers);
         $rows = array();
         foreach ($directoryData as $entry) {
          $rows[] = array(

             array('data' => $entry['name']),
             array('data' => $entry['changed_date']),

          );
       }
       $table_element = array(
            '#theme' => 'table',
            '#header' => $headers,
            '#rows' => $rows,
            '#empty' =>t('Your table is empty'),
        );

        $html=drupal_render($table_element);

```

Anyone know what i can do to debug why the sorting is not working?

# Answer
> 0 votes
the reason the sorting that comes with drupal core doesnt work is that it only works for query based content. If the content is static or otherwise not query based that you need to sort you have the use the client side tablesorting.js as explained here http://tablesorter.com/docs/

---
Tags: 8
---


title: CKEditor scayt Plugin module

text:
# Question
Title: CKEditor scayt Plugin module
I'm trying to build a scayt module to be able to use the CKEditor scayt Plugin. I tried to use this module but it did not work for me. https://github.com/nikhildodeja/scayt I created my own but I get a WSOD when I veiw a node creat page. The module is below. What am I doing wrong?

```
        <?php

    /**
    * @file
    * Definition of \Drupal\scayt\Plugin\CKEditorPlugin\Scayt.
    */

    namespace Drupal\scayt\Plugin\CKEditorPlugin;

    use Drupal\ckeditor\CKEditorPluginBase;
    use Drupal\editor\Entity\Editor;

    /**
    * Defines the "Scayt" plugin.
    *
    * @CKEditorPlugin(
    *   id = "scayt",
    *   label = @Translation("Scayt CKEditor")
    * )
    */

    class Scayt extends CKEditorPluginBase{

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getDependencies().
    */
    function getDependencies(Editor $editor) {
    return array('panelbutton','floatpanel','menu','menubutton','dialogui','button');
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getLibraries().
    */
    function getLibraries(Editor $editor) {
    return array();
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::isInternal().
    */
    function isInternal() {
    return FALSE;
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getFile().
    */
    function getFile() {
        return 'libraries/scayt/plugin.js';
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginButtonsInterface::getButtons().
    */
    function getButtons() {
    return array(
      'Scayt' => array(
        'label' => t('Spell Check'),
        'image' => 'libraries/scayt/icons/scayt.png',
      ),
    );
    }

    /**
    * Implements \Drupal\scayt\Plugin\CKEditorPluginInterface::getConfig().
    */
    public function getConfig(Editor $editor) {
    return array();
    }
    }

```

# Answer
> 0 votes
Without seeing the error it's difficult to know, but you do at least need to extend `CKEditorPluginBase` rather than `PluginBase`:

```
use Drupal\ckeditor\CKEditorPluginBase;

class Scayt extends CKEditorPluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface {

```

Otherwise the required interface methods won't be satisfied.

---
Tags: 8, wysiwyg, plugins
---


# Question
Title: Run lazy-builders of sub-keys in the render array
Our page and region templates need to access fields from the custom blocks inside that region.

Unfortunately, `{{ region.block_id.field_x }}` doesn't work, because `region.block_id` only contains a `#lazy_builder`, and therefore the actual variables inside that render array aren't available until we're in the block template itself (at which point it's not possible to inject variables back into the parent template).

Basically, it looks like what we need is a `theme_preprocess(&$variables)` that iterates over all child elements and recursively evaluates their lazy builders / pre-render hooks, so that all nested elements are available to parent templates. Is there an easy way to do this, or are we stuck with re-implementing parts of the render API here?

# Answer
> 3 votes
This seems like an anti-pattern. Normally you would configure and theme separate instances of the block for the fields you want to display in each region.

If you need block fields in the page template, get the fields directly from the custom block content and put them in variables in page preprocess, see Programmatically accessing block content, or use the module Twig Tweak:

```
{{ drupal_field('field_example', 'block_content', 1) }}

```

# Answer
> 1 votes
Actually, it seems there's an only moderately hacky way to do this via the renderer.

As the renderer service takes the render array by reference and prepares it, all we need is a twig extension function analogous to `render_var()` that returns the render array instead of the rendered output.

```
  function prepareVar($data) {
    $this->renderer->renderRoot($data);
    return $data;
  }

```

The result of the Twig expression `prepare_var(data)` will contain basically the same keys as the variable scope available to the template normally responsible for rendering `data`,

(As this array will also have populated `#markup` keys, nothing should be rendered more than once, either.)

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


title: Two displays with an exposed filter

text:
# Question
Title: Two displays with an exposed filter
I have a view using one exposed form in a block with a couple exposed filters. I would like the same result set to be used in two displays that have a slightly different format.

1. One of my exposed filters is not being "remembered" from one display to the other, even though the other filter fields are.
2. When I navigate from one display to the other, the problematic exposed filter (a single checkbox) gets rechecked if it was unchecked.
3. It appears that the query is being re-run when I go from display to display. I don't really want that to happen since I am using the same result set. I figured the query only should get run when you hit the SUBMIT button, not change displays.

I have tried to use a number of the `hook_views_xxx` functions to set and reset my `exposed_input` array value for the filter field, but I can't seem to get anything to work. I have also tried using the `$_SESSION` variable for the field to fix it, but no luck.

If I can understand what is supposed to happen with Views, I can keep trying to solve this myself, but I am really stuck and into this about 10 hours.

# Answer
Edit your view displays, make sure the common exposed filters have the same Filter identifier. You can find this when you click the filter, and in the "More" fieldset.
> 0 votes

---
Tags: views
---


title: Add/Fix composer in an ongoing project

text:
# Question
Title: Add/Fix composer in an ongoing project
We are having an ongoing project on OpenSocial, which is a profile based on Drupal 8. The project was installed using composer. However, later several modules were installed and updated via Drush.

Due to this, the composer file and the actual application is not in sync. What would be the best way to get out of this situation? Is there any way to fix composer?

# Answer
> 1 votes
Try the Drush Composer Generate project. If you have your composer.json committed to a vcs, you can run composer-generate and then compare the results and fix up anything that it might mis-apply.

---
Tags: drush, composer
---


# Question
Title: How to create Page variant Selection rule "if URL contains"?
I want my variant to apply to all pages if the URL contains a certain string, eg: "cars".

So the cars variant should apply to `cars`, `cars/toyota`, `cars/toyota/camry`, etc.

Is there a way to use a wild card (`cars/*`?)?

I can't find any documentation on this.

Thanks

# Answer
`/*` works. The issue I was having was I was separating them by commas, where's they had to be separated by line breaks.
> 0 votes

# Answer
Try under Variant -\> Selection rules, in the pulldown Select:URL Path then Add. In the new dialog box, select "Allow access to the following pages" then enter "cars/\*" in the textarea, then save. According the description below the textarea which says

```
The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog.

```
> 0 votes

---
Tags: 7
---


# Question
Title: How to get a remote file and set it as a value for a file field using entity metadata wrappers?
I am trying to get a remote pdf file from a web service and save it as a field's value using `entity_metadata_wrapper`, but somehow I couldn't get it working.

I can successfully retrieve the file using `system_retrieve_file` and save it locally. However, I couldn't set the file field's value to this newly retrieved file.

Here is my code (simplified):

```
// Retrieve the file from the web service.
// This works, I can see and open the retrieved file.
$file = system_retrieve_file($file_url, 'public://path/', TRUE);
$file = (array) $file;
var_dump($file);

$ewrapper = entity_metadata_wrapper('node', $nid)

// Set this file as a value for the node's file field.
// I've tried following lines individually and they both failed.
$ewrapper->field_pdffile->set($file);
$ewrapper->field_pdffile->set(array($file));

```

Both methods I've tried raised the following error:

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

I'm setting in the same code block other fields as well and they are set and saved without any error if I skip the file field.

For example, the following lines are working in the same code block for other fields:

```
// I'm getting the text from the web service
$ewrapper->field_text->set($some_text);
// I'm getting a term from web service
// Creating it if it doesn't already exist, and saving the 'term id' like:
$ewrapper->field_term->set($tid);
// A few more various fields are successfully set like that...
// Except that file field, which returns the above exception:
$ewrapper->field_pdffile->set($file);

```

What could it be, that I'm doing wrong?

## UPDATE:

I've added a `var_dump($file)` and I'm getting the following output, which seems alright to me:

```
array(17) {
  'fid' => string(5) "13037"
  'uid' => string(1) "1"
  'filename' => string(31) "sample.pdf"
  'uri' => string(54) "public://path/sample.pdf"
  'filemime' => string(15) "application/pdf"
  'filesize' => string(6) "129804"
  'status' => string(1) "1"
  'timestamp' => string(10) "1409924961"
  'type' => string(8) "document"
  'uuid' => string(36) "a06f6bf7-61e1-48fd-bfc7-8bff6e72705f"
  'metadata' => array(0) {}
  'alt' => string(0) ""
  'title' => string(0) ""
}

```

# Answer
Since @xurshid29 never post the correct answer here, I am posting it cause I find it "hard" to retrieve the comments:

(from @ЕлинЙ post)

```
// Retrieve file from web service (this works, I can see and open the retrieved file)
$file = system_retrieve_file($file_url, 'public://path/', TRUE);
$file = (array) $file;
$file['display'] = 1;
$file['description'] = '';

$ewrapper = entity_metadata_wrapper('node', $nid)

// Set this file as a value for the node's file field.
$ewrapper->field_pdffile->set($file);

```

*More info on system\_retrieve\_file*

And thanks to both of you for your work!
> 1 votes

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


# Question
Title: Maximum upload size for file is not working
I have set file filed with 25MB Maximum upload size. But when i upload more then 25mb file it is uploading. How to stop this.Can we create any custom module for file size.

# Answer
> 3 votes
In Drupal 7 you can achieve by using **.htaccess**

* In your .htaccess file:

+ php\_value post\_max\_size 8M
    + php\_value upload\_max\_filesize 8M

Check this link for more information

# Answer
> 0 votes
Below module helps admin or user with similar admin privileges to change file upload limit on a website without changing php.ini file & restarting the server.

https://www.drupal.org/project/change\_file\_upload\_limit

---
Tags: files
---


# Question
Title: Is it possible to have a single date exposed filter with date range?
In my existing exposed filter, I have two field (Start and End Date) filter, Is it possible to create as one field?

# Answer
> 0 votes
yes, there is a module for that, views\_between\_dates\_filter, from module:

> This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
>
> It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.

---
Tags: 7, views
---


# Question
Title: How to select multiple values from a list block and perform search?
I am a newbie to Drupal.

I have created a block that contains tags of the important topics on my website so how do I insert a search option for the user so that he can select multiple tags from that block and perform the search operation.

# Answer
Assuming it's a view, you have to do a couple of things after constructing the view.

1. Click on the Filter Criteria as seen in the screenshot below:
2. Click on Expose this filter, Grouped filters and Allow multiple selections in this order (they will only appear if you click in this order). Please see the screenshot below:
> 0 votes

---
Tags: search
---


# Question
Title: Add a field programmatically to taxonomy
We have a `field.storage.taxonomy_term.field_name.yml` file that adds the storage configuration for our custom field. The field is available to be added from the GUI to each vocabulary.

The issue we are facing is adding the field to every taxonomy automatically.

We have added the field from GUI and exported the configuration in order to change the form and we place the exported configuration in a file named `field.field.taxonomy_term.field_name.yml`, the problem that we are facing is modifying this config file in order to add them on all taxonomies. In the configuration exported where we found the vocabulary name we switch it to `*` and also the bundle property had the vocabulary name, that property can't be removed since it throws an error.

# Answer
You can use yaml files only if you create new vocabularies. Adding a field to existing vocabularies is the same as doing this for content types, both are bundles, content types for nodes and vocabularies for taxonomy terms. See this question:

8 Add content type field programmatically
> 0 votes

---
Tags: 8, entities, taxonomy-terms
---


# Question
Title: How do I calculate field_1 + field_2 in Twig?
I have two fields. `{{ content.field_1 }}` is 2; `{{ content.field_2 }}` is 5.

How do I multiply them to obtain 10, in a template file?

# Answer
> 1 votes
In `{{ content }}` are render arrays which produce the output "2" and "5", but you can't do arithmetics with these render arrays.

You can try to do this with the database values from the node (if it is a node template):

```
{{ node.field_1.value * node.field_2.value }}

```

---
Tags: theming, entities
---


# Question
Title: Conditionally unpublish a nodes more than latest 20
I want to show the latest updated 20 nodes and unpublish rest of the nodes more than 20 for particular content types.

Here is my code I Have done for a single node

```
public function unpublishednode() {
   $all_content_types = NodeType::loadMultiple();
    foreach ($all_content_types as $machine_name => $content_type) {
      if($machine_name == 'events') {
        $node = Node::load(389);
        $node->setPublished(FALSE);
        $node->save();

      }
    }
}

```

# Answer
> 2 votes
You need an entity query to get the nodes filtered by the content type, sorted by the changed or created date and starting with the 21th node:

```
  $query = \Drupal::entityQuery('node');
  $nids = $query
    ->condition('type', $type)
    ->sort('changed', 'DESC')
    ->range(20, PHP_INT_MAX)
    ->execute();
  $nodes = Node::loadMultiple($nids);

```

You could also add a condition for published nodes, so that you don't load nodes that don't need to be unpublished:

```
    ->condition('status', NodeInterface::PUBLISHED)

```

---
Tags: 8, nodes, database
---


# Question
Title: Entity difference between fields defined in the entity itself and the external fields
When defining an entity (using e.g. Drupal console) some fields are created in the entity, these fields are stored in the entity-table. Afterwards you can add fields to an entity, these fields are stored in separate tables. I see that in the entity-source you can add fields later on.

What is the difference between 'internal' fields and 'external' fields??

# Answer
> 1 votes
The 'internal' fields are base fields, defined in the entity type definition. The 'external' fields are bundle fields, defined in configuration, which can be exported and imported to yaml, and is configurable in UI.

Content entities that have no bundles can have bundle fields, for example the `user` entity. In this case the id of the bundle is that of the entity.

More information https://www.drupal.org/docs/8/api/entity-api/introduction-to-entity-api-in-drupal-8, especially this chapter https://www.drupal.org/docs/8/api/entity-api/defining-and-using-content-entity-field-definitions.

---
Tags: entities
---


title: Inject a service inside a block

text:
# Question
Title: Inject a service inside a block
I need to inject a service inside a block. Since I need some logic before displaying the block, it feels dirty to do it inside the block itself, not to mention it's not actually related to the block itself.

Normally I'd inject a service by using the `create()` method available in the controller, but blocks don't seem to have this method.

How do I use a service from a block?

# Answer
> 3 votes
You do it the same way, the only difference is that you need to make your block class aware of the container first.

Example:

```
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
...
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $aliasManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->aliasManager = $alias_manager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('path.alias_manager')
    );
  }
}

```

---
Tags: blocks, symfony-services
---


# Question
Title: How do I pass parameters as JSON format to the HTTP client request?
How can I pass parameters to the http client get request in json format:

```
$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

$params = '{"data1":"",
"data2":"mydata"
"data3":"mydata",
"data3":"mydata",
"data5":"mydata"}';

$url = 'https://myendpointurl';
try {
  $response = $client->get($url, array(
      'headers' => array('Accept' => 'text/plain'),
    )
  );
  $data = json_decode($response->getBody());
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e->getMessage());
}

```

Where I need to put `$params` variable in my code?

# Answer
> 2 votes
You can add it to the request like so:

```
use Drupal\Component\Serialization\Json;
...
$response = $client->get($url, [
    'headers' => ['Accept' => 'text/plain'],
    'json' => Json::decode($params),
]);

```

---
Tags: 8, http-request
---


title: System Settings Form and array values

text:
# Question
Title: System Settings Form and array values
In the following bit of code i am using hook\_form\_alter to add some more form values to a system\_settings\_form.

If i add a basic text field, then the variable gets saved, however placing the following items in an array, nothing is getting saved.

I have tried using #tree as specified on the parent container containing the array items.

Sorry for the big code dump, but my math teacher always told me to show my work!

```
function mymodule_booking_coupons_form_alter(&$form, &$form_state, $form_id, $no_js_use = FALSE) {

  if ($form_id == 'mymodule_booking_ui_admin') {

    $form['coupons'] = array(
      '#type' => 'fieldset',
      '#title' => t('Coupons'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#weight' => 1,
    );

  $form['coupons']['coupon_container'] = [
    '#type' => 'container',
    '#weight' => 80,
    '#tree' => TRUE,
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="js-ajax-elements-wrapper">',
    '#suffix' => '</div>',
  ];

  $deltas = variable_get('coupon_deltas' , 0);
  for ($delta = 0; $delta <= $deltas; $delta++) {
    $form['coupons']['coupon_container'][$delta] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['container-inline'],
      ],
      '#tree' => TRUE,
    ];
    $form['coupons']['coupon_container'][$delta]['coupon_' . $delta . '_code'] = [
      '#type' => 'textfield',
      '#title' => t('Coupon Code'),
      '#size' => 10,
      '#default_value' => variable_get('coupon_' . $delta . '_code', ''),
    ];
    $form['coupons']['coupon_container'][$delta]['coupon_' . $delta . '_discount'] = [
      '#type' => 'textfield',
      '#title' => t('Discount'),
      '#size' => 10,
      '#default_value' => variable_get('coupon_' . $delta . '_discount', ''),
    ];
    $form['coupons']['coupon_container'][$delta]['coupon_' . $delta . '_type'] = [
      '#type' => 'select',
      '#title' => t('Type'),
      '#options' => array(
            0 => t('Fixed'),
            1 => t('Percentage'),
       ),
      '#default_value' => variable_get('coupon_' . $delta . '_type', 0),
    ];
    $form['coupons']['coupon_container'][$delta]['remove_coupon'] = [
      '#type' => 'submit',
      '#value' => t('x'),
      '#submit' => ['mymodule_booking_coupons_add_more_remove'],
      '#ajax' => [
        'callback' => 'mymodule_booking_coupons_add_more_remove_callback',
        'wrapper' => 'js-ajax-elements-wrapper',
      ],
      '#weight' => 50,
      '#attributes' => [
        'class' => ['button-small'],
      ],
      '#name' => 'remove_coupon_' . $delta,
    ];
  }

  $form['coupons']['coupon_container']['add_name'] = [
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => ['mymodule_booking_coupons_add_more_add_one'],
    '#ajax' => [
      'callback' => 'mymodule_booking_coupons_add_more_add_one_callback',
      'wrapper' => 'js-ajax-elements-wrapper',
    ],
    '#weight' => 100,
  ];

  }

}

function mymodule_booking_coupons_add_more_remove($form, &$form_state) {
  $delta_remove = $form_state['triggering_element']['#parents'][1];
  $k = array_search($delta_remove, $form['coupons']['coupon_deltas']);
  unset($form['coupons']['coupon_deltas'][$k]);

  $deltas = variable_get('coupon_deltas' , 1);
  $deltas = $deltas - 1;
  variable_set('coupon_deltas', $deltas);

  $form_state['rebuild'] = TRUE;
  drupal_get_messages();
}

function mymodule_booking_coupons_add_more_remove_callback($form, &$form_state) {
  return $form['coupons']['coupon_container'];
}

function mymodule_booking_coupons_add_more_add_one($form, &$form_state) {
  $deltas = variable_get('coupon_deltas' , 1);
  $deltas = $deltas + 1;
  variable_set('coupon_deltas', $deltas);

  $form_state['rebuild'] = TRUE;
  drupal_get_messages();
}

function mymodule_booking_coupons_add_more_add_one_callback($form, $form_state) {
  return $form['coupons']['coupon_container'];
}

```

**Update:** I have placed a dpm($form\_state) in the submit handler, and it shows the following array of submitted values - so they make it to this stage, they just dont get saved.

# Answer
I added my own submit handler and looped through the array saving the values.

```
foreach ($form_state['values']['coupon_container'] as $delta => $value) {
        variable_set('coupon_' . $delta . '_code', $form_state['values']['coupon_container'][$delta]['coupon_' . $delta . '_code']);
        variable_set('coupon_' . $delta . '_discount', $form_state['values']['coupon_container'][$delta]['coupon_' . $delta . '_discount']);
        variable_set('coupon_' . $delta . '_type', $form_state['values']['coupon_container'][$delta]['coupon_' . $delta . '_type']);
    }

```
> 0 votes

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


# Question
Title: How to perform a page redirect after submitting node with conditions?
I have a select list which contains A and B. If users choose A, then (after submitting the node) the users are redirect to URL A; if users select, they are redirected to URL B. I'm using Rules and adding conditions to try this but no avail.

Maybe I'm wrong in choosing the conditions because I'm so confused right now and there's no documentation for this.

I've considered to use the Conditional Rules module, but since this project not covered by Drupal, I'm hesitating to use it.

# Answer
> 2 votes
### Solution for option A:

Below is a sample of a rule (in Rules export format) that should allow you to specify a Rules Condition related to a specific value selected via a selection list (and when a new node is created):

```
{ "rules_new_node_with_special_optionlist_value_a" : {
    "LABEL" : "New node with special optionlist value A",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value = Advanced" } }
    ]
  }
}

```

Some more details to further explain the above above sample:

* The Rules event I'm using is "After saving new content" (replace this event by whatever fits your case).
* In my case I have a selection list field with machine name `field_optionlist`.
* This field actually has 2 possible values, like so:
    + A (=Advanced).
    + B (=Basic).
* As a sample, I decided to use as condition "The selected value must be `Advanced`".
* If that value is selected, then (as Rules Action), a message is shown like `A new node got created with option list value = Advanced`. Feel free to change that to whatever Rules action, this is how I often "unit test" new rules I write. In your case you want to make it a redirect to your URL A.

The "clue" to make this rule work is the condition `Entity has field`. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*".

Note that I've not added a Rules Condition here about selected content types, that's probably an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the `Entity has field` condition should be sufficient already.

### Solution for option B:

Clone the rule you created for option A into a similar rule, this time to check for the value of "B", and to perform a Rules Action to redirect to your URL B.

With those 2 rules in place, your disered logic is implemented, and you don't need the "Conditional Rules" module either.

---
Tags: 7, nodes, rules, redirection
---


# Question
Title: Block with articles from the same author
My websites publishes articles by third party authors. Articles are inserted by an admin. Every article has its author. The authors' info are in a content type called Bio, which has these fields: title (full name of the author), picture, body, links to social networks. The path to each author's bio is /author/. In each author page, I want to show all the articles this author has already published on my website. So I made a view that should display a block in each of those pages.

The problem with the view is that it works in preview, when I manually enter the name of the author, but it isn't working when in the page as a block. It doesn't retrieve the from the url, I guess.

Here's some screenshots of my view:

# Answer
> 0 votes
Don't use `Content Titolo` use `Contenuto: Identificativo uid dell'autore`

and use the following settings

# Answer
> 0 votes
I solved this issue by adding a new field to the Bio content type that acts as a "primary key" between the Article and the Bio content type. I also use this field to create the path of the author's bio, so that I can get that value through contextual filter (Raw value from URL).

---
Tags: 7, views
---


title: where to find html code of a page

text:
# Question
Title: where to find html code of a page
I am using Opigno (a LMS based on drupal) and I want to edit a page. I am looking for its HTML but when I open the code for the page this is what I found.

```
<?php print render($page['content']);
<?php print render($page['content_bottom']); ?>

```

I try to use print\_r function in PHP and it displays an array of stuff.

How could I change the page if it is from php.

Thanks!

# Answer
> 0 votes
I have never used Opigno but since it's based on Drupal, I'd say that you should change/edit the content of a page from its corresponding form once you're logged in.

If you want to edit the HTML, than you have to look for the page templates in your theme folders. This link may help you: https://www.drupal.org/search/site/theme%20template

---
Tags: 7, theming
---


# Question
Title: Where to find custom Content type related files in Drupal directories?
I have a localhost Drupal 7.x installation on my system. I have just explored with UI and created a custom Content type which defines a form with radio boxes. (Home --\> Structure --\> Content types --\> Add Content Type, and so on.)

I am assuming these custom content types will be stored in local directories of Drupal core. I am not able to figure out where exactly these stay. I am curious to make changes to that file and see if there is any reflection, though I am not sure if it works that way.

# Answer
Actually, content is managed through the database, so you won't find a specific dir named Content Types in the drupal folder.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Can't update core with composer: "Your requirements could not be resolved to an installable set of packages"
I am not able to perform a security upgrade of Drupal core with composer. I get "requirements could not be resolved." Here is my composer.json: https://pastebin.com/KxEQdPkt

Here is the response:

```
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2].
    - drupal/core 8.3.2 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.3 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.4.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - Conclusion: don't install symfony/psr-http-message-bridge 1.0.x-dev
    - Installation request for drupal/core ^8.3.2 -> satisfiable by drupal/core[8.3.2, 8.3.3, 8.3.x-dev, 8.4.x-dev].

```

# Answer
The solution in my case was to delete the vendor directory and delete composer.lock.

I am not totally sure I needed to delete the vendor directory, because I tried that first without deleting composer.lock, and it didn't work. Deleting composer.lock was necessary.

I also changed the minimum-stability to "stable" before deleting vendor and composer.lock, but I doubt that was necessary. In any case, I now have...

> "minimum-stability": "stable",
> 2 votes

---
Tags: 8, composer
---


# Question
Title: How to add a colon for Webform field labels?
I know you can add colon in field.tpl.php for site wide content type node fields, but looks like it's not webform field related.

And webform doesn't have any webform-field.tpl.php type of templates to edit?

By default, webform fields has no colons e.g. `Full Name` label needs to be `Full Name:`.

I know I can add that with CSS, e.g.

```
.form-item label:after {
  content: ":";
}

```

But this won't work because I need colons to be printed in subnmitted email template too.

And emails dont support `::after` `::before` CSS I think, or there is complication with various web email providers, etc.

I know you can add a manually `:` when creating the label name and like that for every field (but its tiring if multipage long forms), but that's impractical for various reasons like e.g. https://www.drupal.org/node/1922550

# Answer
With D7 webforms, you should be able to access the parts of the webform (rendered within webform-form.tpl.php) within a form alter:

```
function mymodule_form_alter( &$form, &$form_state, $form_id ) {}

```

If you have the devel module enabled, you can use it to print out the variables within the $form\['submitted'\] array - for example, to edit the title of a form component, you would use:

```
$form['submitted']['my_form_component']['#title'] = 'My new title';

```

To add a colon to the end of each component's attribute (i.e. to add a colon at the end of the #title attribute) you could set

```
$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";

```

If you use a variable instead of the specific 'my\_form\_component' name, you can set the form\_alter function to loop over and add the ":" to the end of all component titles.

Small example here: https://www.drupal.org/node/1558246
> 0 votes

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


title: How to use % in the path of the view?

text:
# Question
Title: How to use % in the path of the view?
I created a view that displays my shop (mathieu) in a table. I want to display this view with the following path :

/shop/mathieu/shop

I have to do this for several shops. How to use% in the path of the view ?

# Answer
If you use contextual filters, you should use paths like store/%/boutique, where % is the value passed to the contextual filter.

If you have a contextual filter based on a node id, the path could be store/123/boutique, where "123" is a nid.
> 2 votes

---
Tags: views, 8
---


# Question
Title: How to solve the apostrophe problem in node title? (' -> ')
Node title includes **'** (apostrophe) and it appears normal while viewing the node. But in page source it appears as `'`.

And for the same reason when I want to share this node on Twitter with some custom code put into node.tpl.php (`<?php print urlencode($title) ?>`) it also shows the ' as `'`.

How to solve this problem?

# Answer
Your issue seems similar to what's written in issues such as this or this.

The solution appears to be to use `decode_entities`, e.g. something like this:

```
$node->title = decode_entities($node->title);

```
> 2 votes

# Answer
I had the same issue. I was using a Token to capture my field and send it to Twitter. I solved it by changing which Token format I was using.

For example:

*Use*

`[node:field-twitter-message]`

*Instead of*

`[node:field_twitter_message]`
> 1 votes

---
Tags: 7, theming
---


title: Fatal error - Media module

text:
# Question
Title: Fatal error - Media module
I keep getting the following error for some reason:

> Fatal error: Cannot redeclare media\_views\_invalidate\_cache() (previously declared in /var/www/html/sitename/sites/all/modules/media/media.views.inc:140) in /var/www/html/sitename/profiles/dkan/modules/contrib/media/media.views.inc on line 140

Is there any reason I'm getting the error?

I'm using Drupal 7.54.

# Answer
> 1 votes
Looks like you have media installed twice. Once as part of your installation profile (or distribution) and once as a 'loose' module. Which I suppose occurred because there was a security update and you did not want to wait for the distribution to update.

Make a backup and remove `/sites/all/modules/media`. That should solve it.

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


title: Entity reference view

text:
# Question
Title: Entity reference view
I have an entity reference view setup that currently pre-populates a content authors user name into the content form. This field has to stay the same no matter which user edits it in the future.

It works however it only works for editing content, nothing is pre-populated when creating new content with the form. I've tried adding the current user ID to the form but that will only work for creating new content and it is overridden each time the node is edited.

I can figure out how to do both the things I need but they refuse to play together. It seems like it's has to be one or the other. But there must be a way!

How would I filter the view to show the content author and the current logged(or original author) in user for use on both the edit and create new content pages? Here is a screenshot of my view: And the contextual filter settings:

# Answer
> 1 votes
The problem is (as your comment indicated) the user id from route. That uses the node id, or user id from the url. On an edit page that is `node/123/edit`, so it can load the node and obtain the user. For the create page `node/create`, there is no such id.

Can't you use the `User ID from logged in user` filter instead? That should work.

---
Tags: views, 8
---


# Question
Title: How to include "File upload" field in the webform composite element?
I have created a custom composite element, I want to include "File upload" field...The field is visible to the user and the file is uploaded. But it is nowhere saved.

# Answer
Depends on the destination folder. This webform FAQ might help you.

Edit: Webform Composite Elements do not support File elements yet. Reference on drupal here

Follow these issues (active as of 6/20/2017) to find release updates- https://www.drupal.org/node/2883734 , https://www.drupal.org/node/2884624
> 1 votes

---
Tags: 8, webforms
---


title: Views Tables on Responsive Layout

text:
# Question
Title: Views Tables on Responsive Layout
I have a views table block within a panel.

The table is overflowing the panel and I am trying to understand how to constrain it. I have tried setting it's CSS to various widths but they are always ignored. I can change individual column widths, colours etc but not the width.

Do views tables ignore these settings and just display to the width of their content? What is the best way to set their width?

Any tips for using views tables in responsive themes(within panels)?

I'm using Drupal 7.23 , Views 7.37 , Panels 7.33 , Omega-4

**Update:** In my CSS for this table I have previously tried setting `table {
 width: 100%;` (and with !important). I know it is being applied to the table as when I have very colums it increase the width of the whole table to 100% of it's panel.

The problem occurs when there are a lot of columns and the content text of the column is wide. Then the table overflows past 100%. I can make it thinner by changing font size but I am trying to understand how the views table width is set.

In terms of Views table plugins / modules I am looking at FooTable , Responsive Tables and (sandbox) Better Views Tables. None of these are mature modules so I am quite nervous about using them.

# Answer
Set the table width to 100% with css. If some other rule is overriding this, you may have to increase the specificity or add !important.

If you need more control of your table columns, there is a cool module for responsive tables: https://drupal.org/project/responsive\_tables. Haven't yet tried it myself.
> 3 votes

# Answer
Have a look at the Views Responsive Grid module, with close to 20K reported installs, and an official D7 version, which IMO is pretty 'mature'.

Here is a quote about it (from its project page):

> ... provides a views plugin for displaying content in a responsive (mobile friendly) grid layout. Rather than trying to force the standard Views grid display to work for mobile this provides the same functionality, but in DIVs instead of tables. Provided is also the ability to specify a horizontal or vertical grid layout which will properly stack the content on a mobile display.
>
> Features:
>
> * Horizontal or vertical grid layouts
> * Custom classes for use with responsive themes
> 2 votes

# Answer
I've had good success with the Responsive Tables Filter module. It's a mature module with both 7 and 8 versions. It automatically makes Views tables responsive, and also makes tables inserted with a WYSIWYG editor responsive, a huge plus for the site I needed it for. It uses the Tablesaw method for responsive tables.
> 0 votes

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


title: hook_block_info_alter() is not working?

text:
# Question
Title: hook_block_info_alter() is not working?
I am creating a custom Drupal profile and put down the following code.

```
function erc_360_min_hook_block_info_alter(&$blocks, $theme, $code_blocks) {
  $theme = 'erc_generic';
  $blocks['user']['login']['status'] = 1;
  $blocks['user']['login']['region'] = 'footer_first';
}

```

As far as I can tell, this is correct in terms of what Drupal is asking for, but after the installation, and going to look in my structure-\>blocks page, it does not update the blocks region at all.

Why isn't it working? The theme is correct.

# Answer
There are two errors in the code you show.

* If *erc\_360\_min* is the machine name of the profile, the correct name of the implementation of that hook is `erc_360_min_block_info_alter()`
* Setting `$theme` in that hook doesn't have any effect outside that function, since the parameter is not an object nor is it passed as reference; you rather use that parameter to check you are altering the blocks shown for a specific theme

See `dashboard_block_info_alter()` as guide to write your code.

```
function dashboard_block_info_alter(&$blocks, $theme, $code_blocks) {
  $admin_theme = variable_get('admin_theme');
  if (($admin_theme && $theme == $admin_theme) || (!$admin_theme && $theme == variable_get('theme_default', 'bartik'))) {
    foreach ($blocks as $module => &$module_blocks) {
      foreach ($module_blocks as $delta => &$block) {
        // Make administrative blocks that are not already in use elsewhere
        // available for the dashboard.
        if (empty($block['status']) && (empty($block['region']) || $block['region'] == BLOCK_REGION_NONE) && !empty($code_blocks[$module][$delta]['properties']['administrative'])) {
          $block['status'] = 1;
          $block['region'] = 'dashboard_inactive';
        }
      }
    }
  }
}

```

Setting the region for the block is correct, but it's not correct what I previously described.
> 0 votes

---
Tags: 7, blocks, installation-profiles
---


# Question
Title: How to set Blocks settings in a Drupal Installation Profile?
Is there a way to have my blocks pre-assigned a region and also enabled / disabled in a profile installation? I don't want to go to the structure / block page and assign these blocks individually each time, but would rather have them setup on site installation.

# Answer
You can use hook\_block\_info inside your custom module to add all of your blocks programmatically. Look at this SE Post for an example to use the hook\_block\_info to assign it to the right region and also enable/disable it by declaring status=\>true/false.
> 0 votes

---
Tags: 7, blocks, installation-profiles
---


# Question
Title: Show Block when Listing one Content type
I have a silly question, i have one content type "ABC" and i have create a view page for listing all contents of that type with path "/abc". Next, i create a block which is listing all content of type "DEF", and configure the block "DEF" to show only when i'm listing the content "ABC", but not work.

Only work when i'm configure the block and put on "pages" restriction page like "/abc" path.

I'm doing something very wrong.

Any hint?

# Answer
> 0 votes
Please follow these instructions carefully:

1) Go to /admin/structure/block and click on "Pleace block" button in the region you want to add your view block, for example "Content" region.

2) Now you will see at least three tabs:"Content types", "Pages", "Roles"

3) In tab "Content types" select "DEF" type content

4) Be sure on tab "Pages" is selected the radio button option "Show for the listed pages", leave empty the text area on this tab.

5) Save block.

Hope this help.

---
Tags: views, blocks
---


# Question
Title: Calling function from other module does not work with module_load_include
I'm building a custom module that uses functions from other modules. Specifically the node\_clone module. I'm building a custom module to clone a certain content type from a selected user to another selected user.

In my custom module I'm adding those lines:

```
module_load_include('inc', 'node_clone', 'clone.pages');
clone_node_save($nid);

```

The function clone\_node\_save is defined in the module "node\_clone", in the root folder of that module,

```
function clone_node_save($nid, $account = NULL) {
//Function Content
}

```

inside a file called clone.pages.inc

yet those 2 lines of code give me the error **Fatal error: Call to undefined function clone\_node\_save()**

I also tried making a function inside node\_clone.module that calls clone\_node\_save but that gets the same error.

This is drupal 7

# Answer
You don't include the file extension in the third argument.

So this:

```
module_load_include('inc', 'node_clone', 'clone.pages.inc');

```

Should be this:

```
module_load_include('inc', 'node_clone', 'clone.pages');

```
> 2 votes

# Answer
I was using the wrong name for the module. The .info file says project = "node\_clone", which I assumed was the machine name of the module (its also the name of the folder). But the actual module is called clone.module, And I noticed this name in the System table when I was checking the path for the clone module.

Cheers!
> 0 votes

---
Tags: 7, hooks
---


title: sql-dump failing when run as cron

text:
# Question
Title: sql-dump failing when run as cron
I have a shell script that executes `drush sql-dump`, compresses the result and then sends it to a backup server.

It works fine when run from the command line as root but it is failing silently and dispatching an empty file when run as part of a scheduled cron job.

This script has worked previously for me on another website as a cronjob and so I am somewhat confused what would be wrong now.

I work with Drupal 8.3.1 and Drush Version 8.1.11.

Any suggestions?

# Answer
> 3 votes
After much frustration I have resolved the issue and will post the answer in case it is of use.

Cron seems to not always have access to the same PATH information as when a normal user - or even root - runs a drush command in a command line.

The solution came from comment #7 in this drush thread.

You need the path to drush. You can find this with the command:

```
which drush

```

In my case it was `/usr/local/bin/drush`

Then add the path info to the top of the shell script.

```
export PATH=$PATH:/usr/local/bin

```

And then it worked perfectly.

Additionally, it appears if your local mail is not set up correctly cron discards output from scripts which is why the `drush: command not found` error was not turning up in logs. To make sure you get logs from cron configure it for local mail. See this post.

---
Tags: drush, cron
---


# Question
Title: hook_node_insert, hook_entity_insert, hool_node_presave not triggering
I just got a drupal 7 site with a custom theme handed over to me.

I have to do some stuff when a curtain content type is created by a user, but i am so far unable to get any related hooks working.

So far i tried to add the following to the tempalte.php file

```
function MYTHEME_node_insert($node) {}

function MYTHEME_entity_insert($entity, $type) {}

function MYTHEME_node_presave($node) {}

```

Changing MYTHEME to the name of my theme. I doubbledchecked and the template.php file is used.

# Answer
Only certain theme-related hooks, and alter hooks, can be implemented by a theme. The hooks you're trying to implement aren't in that list, as they're unrelated to theming.

You'll need to create a custom module and implement he hooks there instead.
> 2 votes

---
Tags: 7, hooks
---


# Question
Title: Data export import failed to import into Drupal 7
I using "Data Export Import" module to export all articles from site Drupal 6 and import it to site Drupal 7.

I export all taxonomy terms in site Drupal 6 and import the dataset into site Drupal 7.

The error messages:

> There is a mismatch between the vocabularies in the dataset file and the current vocabularies - vocabulary name: News The Taxonomy Terms dataset file 20150824\_113732\_taxonomy\_terms.dataset was not imported.

How should I correct the error?

# Answer
> 0 votes
It is possible you can't since this module wasn't created for 6-7 migration. (It's too bad, too.)

From the *Data Export Import* project page:

> NB - This module has primarily been developed to move data between the same versions of Drupal - to move data between a live site and a development/beta site.
>
> It may be possible that the taxonomy terms and users data files exported from Drupal 6 can be imported into a Drupal 7 site (or the other way around). This has not been tested yet and any feedback would be gratefully received.

You could try contacting the maintainer through the issue queue, see if it's a small thing they can fix, but since the project is currently looking for a new maintainer I wouldn't expect a quick response.

# Answer
> 0 votes
On D7, This issue can be fixed up by matching vocabulary(id) on both sites. Just create only vocabularies(not terms) with same vid and machinename as live site has.

Thanks!

---
Tags: 7, importing-exporting
---


# Question
Title: How to call Ajax callback on form submit to display results
I want to get results, after validating and add fields as well in result like i want to add checkbox in result

```
function afaf_custom_form($form, &$form_state) {
  $form = array();

  $form['d_id'] = array(
    '#type' => 'textfield',
    '#title' => t('D id'),
    '#size' => 60,
    '#maxlength' => 60,
    '#required' => TRUE,

  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#ajax' => array(
     'callback' => 'v_custom_ajax_handler',
     'wrapper' => 'display-dept-ajax',
     'method' => 'replace',
     'effect' => 'fade',
   ),
  );
$form["prefix"] = array(
    "#markup" => "<div id='display-dept-ajax'></div>");
$form["suffix"] = array(
    "#markup" => "</div>");

  return $form;
}

function v_custom_ajax_handler($form, &$form_state) {

  if (!empty($form_state['input']['d_id'])) {

  $form["department name"] = array(
    "#markup" => "<div id='display-dept-ajax'>Department Id : ""</div>

");

  return  $form["department name"];
  }
}

```

# Answer
> 2 votes
Basic working code example for validation or submit form with ajax.

```
 function afaf_custom_form($form, &$form_state) {
  $form['d_id'] = array(
    '#type' => 'textfield',
    '#title' => t('D id'),
    '#size' => 60,
    '#maxlength' => 60,
    '#required' => TRUE,

  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#ajax' => array(
     'callback' => 'v_custom_ajax_handler',
     'wrapper' => 'display-dept-ajax',
   ),
  );

  $form['#prefix'] = '<div id="display-dept-ajax">';
  $form['#suffix'] = '</div>';
  if (isset($form_state['values'])) {
    $form['output'] = array('#markup' => 'thankyou message');
  }
  return $form;
}

function afaf_custom_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

function v_custom_ajax_handler($form, $form_state) {
  $form_errors = form_get_errors();
  if ($form_errors) {
    return $form;
  }
  else {
    $thank_you_html = drupal_render($form['output']);
    $commands[] = ajax_command_insert(NULL, $thank_you_html);
    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );
  }
}

```

---
Tags: ajax
---


# Question
Title: How to get nodes with term programmatically
I have Vocabulary and Custom Content Type which has field Term reference.

How can I get all nodes of particular term in my module?

Something like this? This doesn't work.

```
$field = field_info_field('field_game');
$results = new EntityFieldQuery;
$results->fieldCondition($field, 'field_game_tid', '5')
  ->execute();

$nids = array();
foreach($results as $result) {
  $nids[] = $result->nid;
}

$nodes = node_load_multiple($nids);

```

# Answer
> 14 votes
You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

```

Here's a good example of an entity query like this (and more field conditions)

# Answer
> 4 votes
There is an API function `taxonomy_select_nodes()` for that:

```
$tid = 5;
$nids = taxonomy_select_nodes($tid, FALSE); // FALSE for paging.
$nodes = node_load_multiple($nids);

```

---
Tags: 7, database
---


# Question
Title: How to display unanswered questions when using the Answers module?
I am using the Answers module 7.x-4.0-rc2. I would like to have links to different displays of the questions view so that one link goes to only unanswered questions and the other link shows all. When I go to filter options, I'm not sure how to filter the content by if there is an answer or not.

This is done on the demo site but out of the box, the 7.x-4.0-rc2 version of the module doesn't have any special views. See screenshot of the demo site below.

Edit: When attempting to import views from https://www.drupal.org/node/2783513#comment-11516603 as suggested, I get the following errors for rankings.txt, repeated:

> * Style plugin datatables is not available.
> * Field handler userpoints\_total.points is not available.
> * Field handler userpoints\_total.last\_update is not available.
> * Sort criterion handler userpoints\_total.points is not available.
> * Unable to import view.

When importing questions.txt, I get:

> * Style plugin datatables is not available.
> * Field handler userpoints\_total.points is not available.
> * Field handler field\_data\_field\_tags.field\_tags is not available.
> * Relationship handler userpoints\_total.uid is not available.
> * Unable to import view.

I attempted installing `answers_userpoints` (which is uninstalled) but could not do so because it depends on `userpoints_rules`, which couldn't be found or downloaded.

Edit 2: I took a look at the code for the exported view for unanswered questions, and believe that section I need to replicate is the following portion; this issue I am having is that `COUNT(Flags: Flagged)` doesn't seem to be available as a filter but I do have flag enabled.

```
/* Filter criterion: COUNT(Flags: Flagged) */
$handler->display->display_options['filters']['flagged']['id'] = 'flagged';
$handler->display->display_options['filters']['flagged']['table'] = 'flagging';
$handler->display->display_options['filters']['flagged']['field'] = 'flagged';
$handler->display->display_options['filters']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['filters']['flagged']['group_type'] = 'count';
$handler->display->display_options['filters']['flagged']['operator'] = '!=';
$handler->display->display_options['filters']['flagged']['value']['value'] = '1';

```

# Answer
> 3 votes
The demo site related to the 7.x.-4.x version of the Answers module uses a further enhanced version of the most recent dev release. Some of the views have been enhanced and will be pushed to D.O soon. These views are available already in Views Export format via files attached to comment #5 in issue #2783513).

The (new) view related to the questions has a tab titled "unanswered", which contains the list of all questions that are "unanswered".

So to actually answer your question, I suggest you experiment a bit with the updated view of questions as contained (in export format) in the issue mentioned above.

Disclosure: I'm a co-maintainer of this module.

---
Tags: 7
---


title: Set the title for a node view panel

text:
# Question
Title: Set the title for a node view panel
I am trying to use panel in Drupal 8 node view template. I have enable Node view panel and added a new variant for Basic page view. But I couldn't mention in panel page to take the title as current node title. Where I can mention it in panel configuration?

**Drupal 8**

Even I have created the panel variant in Drupal 7. Here title is taking by default node title.

**Drupal 7**

# Answer
> 4 votes
FYI: Page Manager is in beta, but that doesn't affect the solution; see below.

You should first check if the `node` context is available in your Variant. Here is an example screenshot for that:

If that is the case, then you can simply use the following token in the page title field:

> \[node:title\]

should look like this:

Good luck!

---
Tags: 8, panels
---


title: The "X" plugin does not exist

text:
# Question
Title: The "X" plugin does not exist
I've exported features in a multisite setup in site A, which I now want to import into site B. Though, I keep getting errors like:

* The "entity\_embed" plugin does not exist
* The "bef" plugin does not exist

I've checked if the modules are enabled in advance, but still, I keep getting this error.

# Answer
> 0 votes
I'm afraid I've been short sighted: I've checked the existence of these modules through `drush en MODULE` assuming that Drush connect to the site basing on the site folder. It seems you now have to explicitly tell it to connect to a specific site: `drush -l SITENAME en MODULE`.

---
Tags: 8, features
---


# Question
Title: How do I translate the tab menu of a view?
I cannot translate the tabs menu shown in a view. Does anyone know how to do it?

# Answer
> 1 votes
Go to admin/config/regional/translate/translate and search for the tab titles you want to translate. Since you have the required modules installed you should be able to find them there.

---
Tags: 7, views
---


title: Date with time not viewing on Form

text:
# Question
Title: Date with time not viewing on Form
If I set a date programatically with this code:

```
$currentDateString=date("Y-m-d H:i:s", strtotime($current_date));
 $static_media->set('field_posted' , $currentDateString);

```

the data in field is there , when I do a `get->` i can see the date, but it does not show up in the edit view of the entity. (just shows as blank)

If I modify the date in the edit view, when I do a 'get-\>' the date comes out with the EDT timezone in the time , and then it does show up in the edit form.

I tried inserting it with the EDT Timezone, but I get a message that the data is too long

```
Drupal\Core\Entity\EntityStorageException: SQLSTATE[22001]: String data, right truncated: 1406 Data too       [error]
long for column 'field_pup_posted_value' at row 1: INSERT INTO {media__field_pup_posted} (entity_id,
revision_id, bundle, delta, langcode, field_posted_value) VALUES (:db_insert_placeholder_0,
:db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4,
:db_insert_placeholder_5); Array
(
    [:db_insert_placeholder_0] => 562729
    [:db_insert_placeholder_1] => 1045632
    [:db_insert_placeholder_2] => published_products_static
    [:db_insert_placeholder_3] => 0
    [:db_insert_placeholder_4] => en
    [:db_insert_placeholder_5] => 2017-06-08EDT17:19:31
)

```

# Answer
> 1 votes
I had to insert it with a T in between the date and time as follows:

```
$currentDateString=date("Y-m-d", strtotime($current_date))."T".date("H:i:s", strtotime($current_date));

```

---
Tags: 8
---


# Question
Title: how to create a user programmatically using comment_presave hook?
I am using this code.

```
function MY_MODULE_comment_presave($comment) {
  $name = 'test';
  $email = 'test@test.com';
  $password = user_password(8);
  $fields = array(
    'name' => $name,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => '',
    'roles' => array(
      DRUPAL_AUTHENTICATED_RID => 'anonymous user',
    ),
  );
  $account = user_save('', $fields);
}

```

I get the following error.

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users}

How do I solve this error?

# Answer
There are some errors in the code you are using, but the main error, which is causing the error message you quoted is that the code is creating users always with the same username, which is not allowed in Drupal: Every user needs to have a unique username.

If you are showing exactly all the code you are using for that hook, it's not clear why you keep creating an account before a comment is saved. You aren't checking which user is creating the comment, which means the user account is created even if the comment is created from the admin user.

To avoid that error message, you need to first verify the account you are going to create doesn't already exist, or you create a different username every time a comment is created. (It doesn't make sense, though.)

In the first case, you use `user_load_by_name()` passing the username; if the function returns `FALSE`, it means a user with that username doesn't exist, and it can be created.
In the second case, you just add a random number to the username, to make it unique; even in this case, I would verify there isn't already an account with that username.

As for the other *errors*:

* The *roles* array should be the following one:

```
'roles' => array(
  DRUPAL_AUTHENTICATED_RID => 'authenticated user',
),

```
* The first argument of `user_save()` is an object, not an empty string, for example the value returned from `new stdClass()`
> 1 votes

---
Tags: comments
---


# Question
Title: Access denied for custom configuration form translation
I get access denied for just the translation page of a config form. I can access the configuration form and update it. No problem there. The form lists in config-translation page as well, but when I click on **Translate** it gives access denied. I'm logged in as Admin. Below is the code as suggested here in my custom module (samplewil.module).

*samplewil.links.menu.yml*

```
samplewil.set_admin:
  title: 'sample settings'
  parent: system.admin_config_system
  description: 'Configure sample settings'
  weight: -10
  route_name: samplewil.set_admin

```

*samplewil.routing.yml*

```
samplewil.set_admin:
  path: '/admin/config/sample-settings'
  defaults:
    _form: '\Drupal\samplewil\Form\SampleForm'
    _title: 'Sample'
  requirements:
    _permission: 'administer site configuration'

```

*samplewil.settings.yml*

```
message: 'Hello'
 langcode: 'ar'

```

*samplewil.config\_translation.yml*

```
samplewil.set_admin:
  title: 'Example Translatable config'
  base_route_name: samplewil.set_admin
  names:
    - samplewil.config

```

*samplewil.schema.yml*

```
samplewil.config:
  type: config_object
  label: 'Example config'
  mapping:
    message:
      type: text
      label: 'Message'

```

My default language is Arabic and I've given 'ar' in settings.yml. Any idea why I'm not able to translate?

# Answer
> 2 votes
Got it finally working. The 'name' array in config\_translation was not matching with the actual file.

samplewil.settings.yml file should be renamed to samplewil.config.yml :)

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


# Question
Title: How can I programmatically set the default export path?
In Drupal 7, you can set the default export path for the features module by setting the variable 'features\_default\_export\_path':

```
variable_set('features_default_export_path', 'sites/all/modules/custom/features');

```

What is the equivalent in Drupal 8? Can the export path be set in the features.settings configuration object?

# Answer
It looks like configuration for the features module is managed in the features.settings configuration object. This settings can be viewed and change via drush.

Viewing the features configuration directory:

```
drush cget features.settings

```

Setting the features configuration directory:

```
drush cset features.settings export.folder "custom/features"

```
> 0 votes

---
Tags: features
---


# Question
Title: Filter search results based on user field
I have previously created a view to search my different content types and it behaves like I want it to.

Now, I would like to limit the search results based on a user profile field. Each content type has an access level field. The access fields are tiered as follows:

A: every one can see it B: only authenticated users can see it C: only authenticated users with a certain profile property can see it

C users can see everything. B users can see B and A content.

My first attempt at this was using a contextual filter and this sort of works. However, it only returns nodes that match the access tier.

I did this with PHP contextual filter code:

```
$memberAccessLevel = 'Public';

if (!empty($argument->field_membership['und'][0]['value'])) {
    $memberAccessLevel = $argument->field_membership['und'][0]['value'];
}

return $memberAccessLevel;

```

My question is, how can I set up the view so that tier C members can see all content?

---

# Answer
Okay, I found the answer. If my keys are A,B,C, I can return A+B+C to return all nodes marked with either A, B, or C. Basically, you need to concatenate the keys you want with + and that will achieve the desired effect.
> 0 votes

---
Tags: views
---