# Question
Title: How to delete a content type, programmatically?
I programmatically created a **content type** during a module installation (using field storage configuration).

I want to delete that content type while **uninstalling** the module.

Is there any way to do this with Drupal 8?

# Answer
Just make sure that the node type depends on your your module, then Drupal will delete it automatically for you.

See node.type.book.yml in the book module for an example, this is the relevant part:

```
dependencies:
  enforced:
    module:
      - book

```

Note that users will have to delete all content of that type before they can uninstall the module then.
> 16 votes

# Answer
This seems to do it for me.

```
$content_type = \Drupal::entityManager()->getStorage('node_type')->load('MACHINE_NAME_OF_TYPE');
$content_type->delete();

```
> 11 votes

# Answer
To trigger some action upon uninstallation of a module you have to implement `hook_uninstall` in your module's `*.install` file. Prior to deleting the content type you might want to ensure all nodes of that content type got deleted as well. Finally, after uninstalling the module and having the content type deleted don't forget to export the updated config.

```
/**
 * Place a short description here.
 */
function MYMODULE_uninstall() {

  // Delete all nodes of given content type.
  $storage_handler = \Drupal::entityTypeManager()
    ->getStorage('node');
  $nodes = $storage_handler->loadByProperties(['type' => 'MACHINE_NAME_OF_TYPE']);
  $storage_handler->delete($nodes);

  // Delete content type.
  $content_type = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->load('MACHINE_NAME_OF_TYPE');
  $content_type->delete();
}

```
> 4 votes

---
Tags: nodes, 8
---


title: Adding a new user directly in database

text:
# Question
Title: Adding a new user directly in database
I've been given the files to a Drupal site so I can create a new theme. I haven't, however, been given the Drupal admin user/password date so I can't sign in to the admin area. Is there a way I can create a new user directly in the database or some other way?

# Answer
You can create a new user by added a row to the users table. The password field must contain an MD5 hashed password. You can use online MD5 generators or, if you are using PHPMyAdmin, select the MD5 function next to the textbox where you enter your plain password. Take note of the user id (uid) of your newly created user. After that, you need to find a role that has sufficient permissions in the role table. Find the role id (rid) and enter the uid and rid in a new row in the users\_roles table.

If there is no role that gives administrator access, because the client does everything with user 1, you need to perform a slightly dirtier trick. Save the password hash of user 1 somewhere and temporarily add a new password for user 1. Then log in with user 1, create a new account for yourself, a new role with sufficient permissions and add yourself to that role. After that, edit user 1 in the database and restore the password. I can recommend admin role to force a role to have all permissions at all times.
> 11 votes

# Answer
There's a much easier way.

1. Go into the DB and change the email address field of the user with id 1 and set it to your email address.
2. Go to `http://mysite/user` and click on the password recovery link.
3. Enter your email address and you'll get a password recovery link.

Of course this assumes that your dev systems allows drupal to send mails out of the box. This is true for most linux and osx boxes but not for Windows.
> 14 votes

# Answer
If you have access to the database, run the following query

```
UPDATE users
SET name='admin',
pass='$S$Drl0vgZ9yuU9uc4JyaTMHxMPriC7q/PsOUOx52fCrVQSTpI/Tu4x',
status=1
WHERE uid = 1;

```

---

the login details will be:

username = **admin**

password = **drupal**

---

REFERENCED HERE:

https://knackforge.com/blog/sivaji/different-ways-reset-drupal-admin-password
> 12 votes

# Answer
You can also create users and assign roles with Drush, as well as change passwords for existing users.

> Drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.
> 10 votes

# Answer
What you could do is to go into the database, save the old admin password, reset the admin password and then log in, create a new user, and then reset the admin password back to what it was before you started.

If you have access to drush, you could do this:

```
cd <drupal root directory>
php scripts/password-hash.sh 'drupal'

```

then take the MD5 hashed password generated above, and:

```
drush sql-cli
update users set name='admin', pass='pasted_big_hash_from_above' where uid=1;
quit

```

That should do the trick.

(source)
> 3 votes

# Answer
```
$user = array();
$user['status'] = 1; //for active user
$user['mail'] = 'test@test.com';
//profile field $user['profile_field_fname'] = 'Vikrant';
$user_account = array();
if($user_uid = module_name_get_uid_by_email($user['mail'])) { //It will use for update.
   $user_account = user_load(array(uid => $user_uid));
}

//save or update user information.
user_save($user_account, $user);

//Check existing record by email.
function module_name_get_uid_by_email($email){
   $query = db_query("SELECT uid FROM {users} WHERE mail = '%s'",$email);
   $result = db_fetch_object($query);
   return $result->uid;
}

```

Try the above code.
> 2 votes

# Answer
If you happen to use **drush** you can use `drush upwd [user] --password="[newpassword]"` which (re)sets the password for the user with the specified name. (`upwd` is the short command version for `user-password`)

Example from drush: `drush user-password someuser --password="correct horse battery staple"` which sets the specified password for username "someuser".
> 2 votes

---
Tags: 6, users, database
---


# Question
Title: dump(), kint() & print_r() are not working in .theme file
I've used drupal 8 with devel module. I want to change some values dynamically in views fields. So i tried to use theme\_preprocess\_views\_view\_fields(). When i tried to print variables using print\_r(), kint() & dump(), no one print values.

```
/**
 * Implement theme_preprocess_views_view_fields().
 */
function galip_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
  print_r($variables['fields']);exit;
}

```

I've enabled debug mode true in services.yml file. But i can't get any variables. How can i get variables?

# Answer
> 6 votes
You should pass the object into the `$variables` array, and then in one of the Twig templates issue `{{ dump(var) }}`. Drupal might be using output buffering there, which would explain why you don't see any output when issuing those calls from the preprocess function.

# Answer
> 7 votes
Just include Kint debugger in your theme file:

```
require_once('modules/devel/kint/kint/Kint.class.php');

```

and use Kint like so:

```
Kint::dump( $_SERVER );

```

---
Tags: 8, theming, debugging
---


# Question
Title: What determines what "view" gets displayed first on a page?
Lets say I have 2 views, that both need to be displayed on the same page and in the same content region. What determines which one gets displayed first over the other? I have looked around in the settings, but I can't seem to find them. I want to switch/flip my views around, but there doesn't seem to be a option to do this.

# Answer
> 1 votes
If you refer this Question on stackoverflow: How does Drupal Views decide between multiple displays with the same path, I think he has described both situations of views in his answer as separate paragraph and second paragraph is your answer.

I am pasting the entire answer here of @Andrew Aledge,

> If you're referring to the display within the views: each view display has a position and the displays are loaded according to that position in an ascending sort. So if you create a page display (which may get a position of 2 since the Default display typically has a position of 1) and then create another page display after that, the next page display may get a position of 3. The customer will be exposed to the position it reaches first (2, provided that they have met the criteria).
>
> If you're referring to the views themselves: views are loaded in order of their view id (vid). The customer will be exposed to the first one loaded.

If you see the LAST TWO Lines, he has mentioned on which basic the views decide which view will be displayed and which one not. He means that ***Provided all conditions same, the view will be shown as per the view id(vid)***

**Other situation:** Apart from above two situation, *Which view user will see if they have different Roles.* So in that can I think It will be decided based on which user has access to which view(I mean based on thier role access), and if same user has access to multiple views then in this case it will decided again based on `vid`.

I think, above three discussion have cover all the various situation of visibility of view.

---
Tags: 7
---


# Question
Title: Adding fields to entity (menu_link_content) form (menu_link_edit)
I have been diving into Drupal 8, it's plugin system and all the new stuff for some days now. I hope that I understood the basics and now I would like to start out with a new module.

The module should:

* Add a dropdown to the form `menu_link_edit`
* do the usual save/update/delete stuff for each menu link on submission of the form, so that the selected value can be accessed from the link entity.

Following the conventions I have created that structure:

```
+mymodule
 -mymodule.info.yml
 -mymodule.services.yml
 +src
  -MyModuleManager.php extends DefaultPluginManager
  -MyTypeInterface.php
  -MyTypeBase.php implements MyTypeInterface
  +Plugin
   +Mytypes
    -MyType1.php extends MyType
    -MyType2.php extends MyType

```

Until here the new whole Plugin stuff is clear to me, that is why I have not posted any code so far. With the above I declare the Items that should appear in the desired `dropdown`, but it does not attach the field to the form, and it does not care about the storage of the values.

I had a look at the module `menu_link_attributes` and there, in `menu_link_attributes.module` I found:

```
function menu_link_attributes_form_menu_link_content_form_alter(…){
    //code
    $form['actions']['submit']['#submit'][] = 'menu_link_attributes_menu_link_content_form_submit';
}

```

So the actual form is modified and another submit handler is added. **BUT** I do not get the part where the data (the values of the additional fields) is stored with the item (the menu link). **HOW DOES THAT WORK?**

On the other Hand, I had a look at the module `link_attributes`, therein (`link_attributes.module`) I found:

```
function link_attributes_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
    if ($entity_type->id() === 'menu_link_content') {
        $fields['link']->setDisplayOptions('form', [
            'type' => 'link_attributes',
            'weight' => -2,
        ]);
    }
}

```

And if I understood everything right, this piece of code does assign a different Field Widget to the Link, so that additional fields extend the original widget.

I think I understand the process, but also here, I do not understand how the data is stored/retrieve.

Since the overall question might be unclear, I hope I can figure out my objective like that:

From my understanding I would expect to alter the entity `menu_link_content` in some sort of `hook_entity_alter`, or if possible in the new D8 manner. But in non of the examples I could find any approach like that, why?

So by defining a new field (which renders the dropdown) and adding that field to the definition of `menu_link_content` the field should appear on the form all by itself, or do I get this totally wrong?

Thanks in advance!

**UPDATE**

I have implemented the following, but it does not do anything, so why is that not working?

```
function mymodule_entity_type_build(array &$entity_types) {
    $entity_types['menu_link_content']
        ->setFormClass('menu_link_content_form',
            'Drupal\mymodule\Form\MenuLinkContentForm');
}

```

I have intentionally implemented errors in 'Drupal\mymodule\Form\MenuLinkContentForm', just to check if it is used, but it isn't. So where's the catch here?

**UPDATE #2**

based on the accepted answer My resulting code looks like that:

```
//mymodule.module

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;

function mymodule_entity_base_field_info(EntityTypeInterface $entityType)
{
    if($entityType->id() == 'menu_link_content') {

        $manager = \Drupal::service('mymodule.pluginmanager');

        $labels = array_map(
            function(array $definition) use ($manager)
            {
                $instance = $manager->createInstance($definition['id']);
                return $instance->getName();
            },
            $manager->getDefinitions());

        $field = [
            'mymodulefield' => BaseFieldDefinition::create('list_string')
                ->setLabel(t('MYMODULE::FIELD::LABEL'))
                ->setSetting('allowed_values', $labels)
                ->setDisplayConfigurable('form', true)
                ->setDisplayConfigurable('view', true)
                ->setDisplayOptions('form', [
                    'type' => 'select',
                    'weight' => -10
                ])
        ];

        return $field;
    }
}

```

One thing made a lot of trouble: If during the installation of the module something went wrong, It resulted in MySql errors. Uninstalling was not possible anymore, since extra fields were attached to the entity.

# Answer
> 8 votes
The easy solution for this, is the add a new base field on the menu link entity, the Drupal the rest for you. You can do this with the `hook_base_field_info()` hook.

This code should work, but you might need to tweak it.

```
/**
 * Implements hook_entity_base_field_info().
 */
function MODULE_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['custom_field'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('LABEL'))
      ->setSetting('allowed_values_function', 'function_to_control_options')
      ->setDisplayOptions('form', array(
        // Default form display options
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }
}

```

The code above creates a list\_string field with an allowed values function and makes it configurable for both form and view mode.

The nice thing with the above approach is that the field gets added to the menu link field\_data table, so Drupal don't need to do extra joins etc. For form/display it uses fields like all of the other stuff menu links are built with, so you don't need to touch the Entity class, the form etc.

To get/set the field, you need to use the `::get` / `::set` method directly or access the field directly. Both is not considered best practice, but would work. To make the beautiful solution, you could create a custom entity class with getter and setter for the new base field.

---
Tags: forms, 8, plugins
---


# Question
Title: Is it possible to put Drupal.settings javascript in separate file
I am trying to place all javascript in external files, is it possible to place Drupal.settings javascript in an external file? It is displayed like:

```
jQuery.extend(Drupal.settings, { "basePath": "/", "fbconnect": { "user_pictures": "allow", "language_code": "en_US",...

```

# Answer
This is not possible without hacking the core. This javascript is assembled and injected into the page in includes/common.inc (check line 4312 in the api reference).
> 2 votes

# Answer
Yes - this won't make a difference to Drupal where the file is coming from. In Drupal, you can load this using drupal\_add\_js:

```
drupal_add_js('http://example.com/example.js', 'external');

```

Note that these files will not get aggregated when preprocessing is on.

The other thing to watch for with external javascript is to make sure you are testing for the existence of functions / variables if you are calling them in your file since you can't control the order / speed that they are loading in.
> 3 votes

# Answer
It is considered bad practice to have big inline javascripts. A lot of Drupal modules add settings to the Drupal.settings object. This means that we can end up with an enourmous inline script.

I think a solution should be found to allow Drupal.settings to be put in an external file rather than using inline
> 2 votes

---
Tags: 7, javascript
---


# Question
Title: Content not displaying for anyone other than Admin
I have a problem with Drupal 7. I recently set up Context module to display some blocks on given conditions and everything seemed to be fine. However, when I logged out every text in a block within a Mini panel disappeared on front page, and on every internal page content body (title still visible) is gone too.

I flushed the cache several times. In permissions anonymous and other users have "view published content"(this is a lazy translation from french) enabled. In didn't apply any kind of user role condition in Context, nor do I have any css/js error in console. Other than those which are only alerts:

> Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead\[En savoir plus\]jquery.min.js:1
>
> L’utilisation de « getPreventDefault() » est obsolète. Utiliser « defaultPrevented » à la place.

Please help me through these darks times...I'm running out of options

Thx in advance

# Answer
Ok, So...In fact I verified the permissions of a body field of a block within a mini panel (yeah right...) and there were no permissions for anonymous user to view. So I checked that for only one block and somehow it all went right without changing anything else. So there's that.

Thx anyway for your precious time.
> 1 votes

---
Tags: users
---


# Question
Title: Trying to pass id to the ajax callback function, keeps overwriting, how to solve this?
I created a form which have a lot of images and a delete button on every each one of them. I used ajax to create a callback function which would delete the image. Here is part of my form:

```
foreach($result as $key=>$some){
    $form['image-entry'][$some->id] = array(
      '#type' => 'fieldset'
    );

    $form['image-entry'][$some->id]['image_' . $some->id] = array(
      '#markup' => theme('image', $variables[$key]),
    );

    $form['image-entry'][$some->id]['description_' . $some->id] = array(
      '#type' => 'textarea',
      '#default_value' => $some->description,
      '#attributes' => array(
        'placeholder' => t('Describe this picture'),
       ),
    );
    $form['image-entry'][$some->id]['submit3' . $some->id] = array(
      '#type' => 'submit',
      '#value' => 'Delete',
      '#ajax' => array(
        'callback' => 'image_gallery_delete_photo_callback',
       ),
    );
   $form['#foo'] = array($some->id);
  }

```

As you can see I have 3rd submit button which is ajax callback and from example I found out that I need to create a new form element (foo) in this case, which stores some data that I can pass. Everything works like a charm, this is my callback function:

```
function image_gallery_delete_photo_callback($form, $form_state, $args){
  $arguments = $form['#foo'];
  dpm($arguments);

  /*$photo_delete = db_delete('image_gallery_photos')
                  ->condition('id', $arguments)
                  ->execute();*/
}

```

I am able to fetch the id of the photo from the form, but here I face a brick wall.

**Problem:** id is overwritten because it is in a foreach loop, taking it out, doesn't help. It only stores last value from the loop.

How can I get an id of the element selected?

# Answer
I'm sure you can pass some arguments to your callback by doing this:

```
$form['image-entry'][$some->id]['submit3' . $some->id] = array(
  '#type' => 'submit',
  '#value' => 'Delete',
  '#ajax' => array(
    'callback' => 'image_gallery_delete_photo_callback',
    'parameters'=> array('param1'=>$some->id)
   ),
);

```

Try to catch those parameters at your function `image_gallery_delete_photo_callback($form, $form_state, $args)`

The variable **$args** should contain 'param1'as your ID

Hope it helps !
> 0 votes

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


# Question
Title: How to implement the two categories of the same content type to automatically generate a new aggregation page?
example: there are two taxonomy fields of each article, a taxonomy is regional, another is the attribute，I want to achieve the "regional + attribute = regional attribute" automatically generated such a new aggregation page.

# Answer
> 1 votes
Create a new view, go to `admin/structure/views/add`

**Show:** Content **of type:** All

✅ Create a page

**Display Format:** Unformatted List **of:** Fields

`Save and Edit`

Now in your view, Click on Advanced (located in the right side).

**RELATIONSHIPS** click `add`

Select ✅ Taxonomy terms on node

For **Vocabularies** checkmark your vocabs and then checkmark ✅ require relationship.

Then in **FILTER CRITERIA** `add` Has taxonomy term

✅ Autocomplete, then type `regional, attribute`.

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


title: How to override existing plugin?

text:
# Question
Title: How to override existing plugin?
Considering `Drupal\search_api\Plugin\views\query\SearchApiQuery` class, I want to override `shouldAbort()` method there.

I have tried to create a new plugin class in my custom mod:

```
namespace Drupal\my_mod\Plugin\views\query;

use Drupal\search_api\Plugin\views\query\SearchApiQuery;

/**
 * Defines a Views query class for searching on Search API indexes.
 *
 * @ViewsQuery(
 *   id = "search_api_query",
 *   title = @Translation("Search API Query"),
 *   help = @Translation("The query will be generated and run using the Search API.")
 * )
 */
class MymodSearchApiQuery extends SearchApiQuery {

  /**
   * @inheritdoc
   */
  public function shouldAbort() {
    //do something fancy
  }
}

```

But it seems to not work. How can I do it properly?

# Answer
As per the suggestion by @googletorp, you should use hook\_views\_plugins\_query\_alter(). You simply update the plugin class with your own that overrides it.

```
function my_mod_views_plugins_query_alter(array &$plugins) {
  $plugins['search_api_query']['class'] = 'Drupal\my_mod\Plugin\views\query\MymodSearchApiQuery';
}

```
> 5 votes

# Answer
What you want to do, is to make views use your class instead of the the one solr module provides. Defining your own plugin wont help.

Instead you can use `hook_views_plugins_query_alter` to specify the plugin class.
> 5 votes

---
Tags: 8, plugins
---


# Question
Title: How to trigger rules action if cart is empty?
We have a field in our user profiles that is checkmarked when a user adds a product to their shopping cart (with Drupal Commerce). This is used to display a message reminding them to checkout if they have items in their cart. I have successfully set up rules to check the field when they add a product, and uncheck it when they make it through checkout.

However, I also need to uncheck the field if a user removes all products from their cart. I can't seem to figure out what conditions to add to check if the user's cart is empty after a product has been removed.

Any suggestions?

# Answer
> 1 votes
You could try adding a rule that looks at the total number of items in the cart. Just get the count of the line items list within rules.

# Answer
> 1 votes
May be "Commerce Cart Context" module will be usefull for you.

# Answer
> 0 votes
You can define a condition rule which can count products in your cart, for example:

```
/**
 * Implements hook_rules_condition_info().
 */
function foo_webstore_rules_condition_info() {
  return array(
    'foo_webstore_rules_condition_ordered_num_line_items' => array(
      'group' => t('Commerce'),
      'callbacks' => array(
        'execute' => 'foo_webstore_rules_condition_ordered_num_line_items',
      ),
      'label' => t('User ordered number of line items'),
      'parameter' => array(
        'count_type' => array(
          'type' => 'text',
          'label' => t('Products to compare'),
          'description' => t('Select which products should be taken into consideration.'),
          'optional' => TRUE,
          'default value' => '=',
          'options list' => 'foo_webstore_rules_condition_ordered_num_line_items_count_types',
          'restriction' => 'input',
        ),
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Product')
        ),
        'operator' => array(
          'type' => 'text',
          'label' => t('Operator'),
          'description' => t('The comparison operator.'),
          'optional' => TRUE,
          'default value' => '=',
          'options list' => 'commerce_numeric_comparison_operator_options_list',
          'restriction' => 'input',
        ),
        'value' => array(
          'type' => 'text',
          'label' => t('Value'),
          'description' => t('Integer representing a value.'),
          'default value' => '0',
        ),
      ),
      'module' => 'foo_webstore',
    ),
  );
}

/**
 * Rules condition's select box items for "Products to compare".
 */
function foo_webstore_rules_condition_ordered_num_line_items_count_types() {
  return array(
    'any' => t('Count products of any type'),
    'any|free' => t('Count free products of any type'),
    'exact' => t('Count products of the same type'),
    'exact|free' => t('Count free products of the same type'),
  );
}

/**
 * Rules action callback for "User ordered number of line items".
 */
function foo_webstore_rules_condition_ordered_num_line_items($count_type, $line_item, $operator, $value) {
  $count_types = explode('|', $count_type);

  $num_in_cart  = 0;
  $product_id   = $line_item->data['context']['entity']['entity_id'];
  $line_item_id = $line_item->line_item_id;
  $product_id   = reset($line_item->data['context']['product_ids']);

  // Checking total number of products in the cart.
  $cart_order = commerce_cart_order_load($GLOBALS['user']->uid);

  foreach ($cart_order->commerce_line_items[LANGUAGE_NONE] as $item) {
    $cart_line_item = commerce_line_item_load($item['line_item_id']);
    $cart_product_id = reset($cart_line_item->data['context']['product_ids']);
    $cart_product_price_free = $cart_line_item->commerce_total[LANGUAGE_NONE][0]['amount'] == 0;

    if (in_array('any', $count_types) || (in_array('exact', $count_types) && $cart_product_id === $product_id)) {
      if (!in_array('free', $count_types) || $cart_product_price_free) {
        ++$num_in_cart;
      }
    }
  }

  $num_bought = 0;

  // Checking how many products of this is user already bought.
  $data = db_query("
    SELECT LI.line_item_id AS lid, LI.quantity, LI.data
    FROM commerce_order O
    LEFT JOIN commerce_line_item LI ON LI.order_id = O.order_id
    WHERE O.`status` NOT IN ('selected', 'cart', 'canceled') AND O.uid = :uid
  ", array(
    ':uid' => $GLOBALS['user']->uid
  ))->fetchAll();

  foreach ($data as $row) {
    $commerce_data = unserialize ($row->data);
    $bought_product_id = reset($commerce_data['context']['product_ids']);

    // @TODO: Would be a good idea to check price in another way if we want code to be shareable.
    $bought_product = commerce_product_load($bought_product_id);

    $bought_product_price_free = $bought_product->commerce_price_eur[LANGUAGE_NONE][0]['amount'] == 0;

    if (in_array('any', $count_types) || (in_array('exact', $count_types) && $bought_product_id === $product_id)) {
      if (!in_array('free', $count_types) || $bought_product_price_free) {
        ++$num_bought;
      }
    }
  }

  // "1" is for current line item.
  $num_total = $num_in_cart + $num_bought + 1;

  switch ($operator) {
    case '<':  return $num_total <  $value;
    case '<=': return $num_total <= $value;
    case '=':  return $num_total == $value;
    case '>=': return $num_total >= $value;
    case '>':  return $num_total >  $value;
  }
}

```

Related: Add rule for counting/limiting the product line items

---
Tags: commerce, rules
---


# Question
Title: Limit total quantity of products across user's entire order history
I am trying to limit a user's total quantity of products across their entire order/purchase history based on a field on that product. For example, if **Can of Peanuts** has a limit of 3 per user, then the user should not be able to buy 3 then place another order for 3.

Does anyone have any recommendations for ways to accomplish this?

# Answer
> 2 votes
Use hook\_form\_commerce\_cart\_add\_to\_cart\_form\_alter()

```
<?php
mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id)
{
  /*code*/
}
?>

```

Then, inside the hook, use entityFieldQuery to get list of orders for this user

For locating the "currently selected product," you can use the form\_state variable:

```
<?php
$current_product = $form_state['default_product'];
?>

```

Finally, you'll want to iterate over each order and use entity meta data wrappers to wrap the orders so you can iterate over the line items, looking for matching products.

```
<?php
foreach ($orders as $order_id => $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
  }
}
?>

```

The final final round would include looking to see if the line item is attached to the product and then counting the number of products this person has purchased.

Unfortunately, while you might be able to construct an SQL statement that does most of the heavy lifting (instead of iterating over all the user's orders and line items), it would require much more intimate knowledge of your particular store architecture.

# Answer
> 0 votes
You can create a conditional rule to count the products in the cart, then create an action to remove *Commerce Line Item* from the cart if certain limit is reached.

Here is the example code:

```
/**
 * Implements hook_rules_condition_info().
 */
function foo_webstore_rules_condition_info() {
  return array(
    'foo_webstore_rules_condition_ordered_num_line_items' => array(
      'group' => t('Commerce'),
      'callbacks' => array(
        'execute' => 'foo_webstore_rules_condition_ordered_num_line_items',
      ),
      'label' => t('User ordered number of line items'),
      'parameter' => array(
        'count_type' => array(
          'type' => 'text',
          'label' => t('Products to compare'),
          'description' => t('Select which products should be taken into consideration.'),
          'optional' => TRUE,
          'default value' => '=',
          'options list' => 'foo_webstore_rules_condition_ordered_num_line_items_count_types',
          'restriction' => 'input',
        ),
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Product')
        ),
        'operator' => array(
          'type' => 'text',
          'label' => t('Operator'),
          'description' => t('The comparison operator.'),
          'optional' => TRUE,
          'default value' => '=',
          'options list' => 'commerce_numeric_comparison_operator_options_list',
          'restriction' => 'input',
        ),
        'value' => array(
          'type' => 'text',
          'label' => t('Value'),
          'description' => t('Integer representing a value.'),
          'default value' => '0',
        ),
      ),
      'module' => 'foo_webstore',
    ),
  );
}

/**
 * Rules condition's select box items for "Products to compare".
 */
function foo_webstore_rules_condition_ordered_num_line_items_count_types() {
  return array(
    'any' => t('Count products of any type'),
    'any|free' => t('Count free products of any type'),
    'exact' => t('Count products of the same type'),
    'exact|free' => t('Count free products of the same type'),
  );
}

/**
 * Rules action callback for "User ordered number of line items".
 */
function foo_webstore_rules_condition_ordered_num_line_items($count_type, $line_item, $operator, $value) {
  $count_types = explode('|', $count_type);

  $num_in_cart  = 0;
  $product_id   = $line_item->data['context']['entity']['entity_id'];
  $line_item_id = $line_item->line_item_id;
  $product_id   = reset($line_item->data['context']['product_ids']);

  // Checking total number of products in the cart.
  $cart_order = commerce_cart_order_load($GLOBALS['user']->uid);

  foreach ($cart_order->commerce_line_items[LANGUAGE_NONE] as $item) {
    $cart_line_item = commerce_line_item_load($item['line_item_id']);
    $cart_product_id = reset($cart_line_item->data['context']['product_ids']);
    $cart_product_price_free = $cart_line_item->commerce_total[LANGUAGE_NONE][0]['amount'] == 0;

    if (in_array('any', $count_types) || (in_array('exact', $count_types) && $cart_product_id === $product_id)) {
      if (!in_array('free', $count_types) || $cart_product_price_free) {
        ++$num_in_cart;
      }
    }
  }

  $num_bought = 0;

  // Checking how many products of this is user already bought.
  $data = db_query("
    SELECT LI.line_item_id AS lid, LI.quantity, LI.data
    FROM commerce_order O
    LEFT JOIN commerce_line_item LI ON LI.order_id = O.order_id
    WHERE O.`status` NOT IN ('selected', 'cart', 'canceled') AND O.uid = :uid
  ", array(
    ':uid' => $GLOBALS['user']->uid
  ))->fetchAll();

  foreach ($data as $row) {
    $commerce_data = unserialize ($row->data);
    $bought_product_id = reset($commerce_data['context']['product_ids']);

    // @TODO: Would be a good idea to check price in another way if we want code to be shareable.
    $bought_product = commerce_product_load($bought_product_id);

    $bought_product_price_free = $bought_product->commerce_price_eur[LANGUAGE_NONE][0]['amount'] == 0;

    if (in_array('any', $count_types) || (in_array('exact', $count_types) && $bought_product_id === $product_id)) {
      if (!in_array('free', $count_types) || $bought_product_price_free) {
        ++$num_bought;
      }
    }
  }

  // "1" is for current line item.
  $num_total = $num_in_cart + $num_bought + 1;

  switch ($operator) {
    case '<':  return $num_total <  $value;
    case '<=': return $num_total <= $value;
    case '=':  return $num_total == $value;
    case '>=': return $num_total >= $value;
    case '>':  return $num_total >  $value;
  }
}

function foo_webstore_rules_action_info() {
  return array(
    'foo_webstore_remove_line_item_from_cart_action' => array(
      'group' => t('Commerce'),
      'label' => t('Remove line item from the cart'),
      'parameter' => array(
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Commerce Line Item'),
        ),
      ),
    ),
  );
}

/**
 * Rules action. Removes Commerce Line Item from the cart.
 */
function foo_webstore_remove_line_item_from_cart_action($commerce_line_item) {
  commerce_line_item_delete($commerce_line_item->line_item_id);
}

```

Related Drupal posts: #2189247, #1267156.

See also: Limit Quantity When Adding a Product to Cart.

---
Tags: 7, commerce, rules
---


# Question
Title: entity_get_form_display setComponent throws "plugin does not exist" regardless of type
I'm trying to programmatically add a field to a custom bundle, and have it appear on the custom entity type. I'm using a `BaseForm` extended class, and have acquired an `entityManager` elsewhere using dependency injection.

Below is the `submitForm()` code I modelled, on how `FieldStorageAddForm::configureEntityFormDisplay()` etc. works:

```
$field_storage_values = [
  'field_name' => 'field_phone',
  'entity_type' => 'contact',
  'type' => 'string',
  'translatable' => false,
];
$field_values = [
  'field_name' => 'field_phone',
  'entity_type' => 'contact',
  'bundle' => 'organization',
  'label' => 'Phone',
  'translatable' => false,
];
$this->entityManager->getStorage('field_storage_config')
    ->create($field_storage_values)->save();
$this->entityManager->getStorage('field_config')
    ->create($field_values)->save();

entity_get_form_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string_textfield'])
  ->save();
entity_get_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string_textfield'])
  ->save();

```

This works fine for adding the field storage, and for associating the field instance with the bundle.

However, when it gets to the `entity_get_form_display()->setComponent()->save()`, the following exception is thrown:

```
Uncaught PHP Exception Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException: "The "string_string_textfield" plugin does not exist."
at /var/www/web/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 60

```

What's strange is that the same exception, quoting 'string', is seen for both `'type' => 'string_textfield'` and `'type' => 'text_text_with_summary'` (which doesn't even contain the word 'string'!) On the other hand, a nonsense value (e.g. 'string\_string\_textfield' or 'stringz\_textfield') yields the exception with the nonsense value in full, no parsing. So there's *some* kind of detection/lookup going on, but it still can't find the relevant plugin.

What am I missing? What should the value of `'type'` be? I'm aware of e.g. https://drupal.stackexchange.com/questions/177913/the-string-plugin-does-not-exist but as you can see the value suggested there doesn't seem to work in this situation.

# Answer
> 0 votes
OK, I've dug around and I think I've got a fix for this myself.

The first thing is to fix the code above; the two `'type'` entries SHOULD be different, and should match values available in the dropdowns in the admin UI:

```
entity_get_form_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'text_textfield'])
  ->save();
entity_get_display('contact', 'organization', 'default')
  ->setComponent('field_phone', ['type' => 'string'])
  ->save();

```

The second thing is that the entity's `baseFieldDefinitions()` were also defining a 'view' formatter type and a 'form' formatter type, but for an undeletable base field:

```
$fields['name']->setSettings([
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ])
  ->setDisplayOptions('view', ['label' => 'above', 'type' => 'string'])
  ->setDisplayOptions('form', ['type' => 'text_textfield'])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Originally, the form display here was also `'string'`. This is obviously nothing to do with the programmatic field adding itself, but when you run:

```
entity_get_*display(...)->setComponent(...)

```

the return value is `$this` i.e. the display object. So chaining `->save()` causes the ENTIRE display to be saved: including base fields. Only at this point did the broken configuration in the base fields suddenly cause a problem.

But, ensuring that:

* the `'type'` for form display ALWAYS matched a value available in the admin UI for content types
* and similar for view display
* and ensuring this across both the new field AND base fields

fixed the original problem. Phew.

---
Tags: entities, plugins
---


title: Search input in Drupal 8

text:
# Question
Title: Search input in Drupal 8
I have a website built in Drupal 8. In one of the basic page, I have to add a search box which searches only the contents in that specific page. Please suggest the best practice to implement this. Thanks.

# Answer
You need to create a view page, and in the FILTER CRITERIA you can add "for example" : content datasource:title and add the title of this specific page if it will not change But the best is to use : ID = nid that you will find in your database in the node\_field\_data table Search for the title and you will find your ID and use it to filter in your views and that's it !
> 1 votes

---
Tags: search
---


title: How to write a partial "setRebuild"?

text:
# Question
Title: How to write a partial "setRebuild"?
I created a custom module which contains a Class Form. When I submit my form, I redirect the user to the form page. During the submission, I need to save a `form_state` variable to re-use it after the user is redirected to the form.

So, from my submit method, I save my variable (with "`$form_state->set(...)`" ) and I add "`$form_state->setRebuild()`".

All works perfectly. Now, I want preserve my variable AND empty some field's form. I don't want to preserve values of all fields of my form after the user has been redirected.

I tried this :

```
// From my buildForm
// ...
$form['test'] = [
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

```

But I have this error when I use the setValueForElement method :

> The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Component\Utility\NestedArray::keyExists() must be of the type array, string given, called in /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in Drupal\Component\Utility\NestedArray::keyExists() (line 259 of core/lib/Drupal/Component/Utility/NestedArray.php).

I don't understand where my mistake is, use the setValueForElement maybe not the better way?

**Edit** (after Ismail Cherri's answer)

This is my new code : ("$form\['#parents'\] = array();" added)

```
// From my buildForm
// ...
$form['test'] = [
  '#parents' => [],
  '#type' => 'textfield',
  '#title' => "test",
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
];
//...
// I check if my var exist, if yes, that means the user has submited the form and has been redirected to the form
if($form_state->has('results') && $form_state->get('results')) {
  $form_state->setValueForElement($form['test'],"0");
}
return $form;

```

I keep the same error when I submit my form...

> The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Component\Utility\NestedArray::keyExists() must be of the type array, string given, called in /(...)/core/lib/Drupal/Core/Form/FormBuilder.php on line 1296 in Drupal\Component\Utility\NestedArray::keyExists() (line 259 of core/lib/Drupal/Component/Utility/NestedArray.php).

# Answer
Can you please try adding this to your buildForm() method:

```
$form['#parents'] = array();

```

According to documentation: FormStateInterface::setValueForElement You need to pass an array() and set the parents array for the form element.
Hope this helps.

**UPDATE**
After revisiting the documentation, can you try this code:

```
$form_state->setValueForElement($form_state->getValue('test'),"0");

```
> 2 votes

# Answer
The error you are getting, is because `$form['test']` doesn't have a `#parents` attribute. So to fix the error you have right now, you would need to do this:

```
$form['test'] = [
  '#parents' => [],
  ...
];

```

That said, going about it this way is very messy, and I would suggest you use some alternate solutions instead.

### Sneaky reset

Instead of trying to manipulate the form into thinking the user hasn't giving a value for `test`, you can simply rename it:

```
if ($form_state->has('results') && $form_state->get('results')) {
  // Copy form test to clear old submitted values.
  $form['test_1'] = $form['test'];
  // Assign the default value you want.
  $form['test_1']['#default_value'] = '';
  // Hide form test.
  $form['test']['#access'] = FALSE;
}

```

This is pretty simple/clever, but would require your validation/submit handler to take this into account.

### 2 forms / FULL reset.

Another solution would be to have multiple forms, or completely reset the form, and instead save the submitted data in cookies, sessions or something similar which is persistent. Then you could set default values you wanted to presave from the session or cookie. This could potentially be a bit messy, as you would need to clear the session as it otherwise would save the data for a long time, handle TTL etc.
> 1 votes

# Answer
No need to add parents, you can check if form has been submitted in a validate function:

In your form:

```
$form['test'] = [
  '#type' => 'textfield',
  '#title' => "test",
  '#element_validate' => array(array(get_class($this), 'validateTestField')),
];

```

then add the validate function:

```
  public static function validateTestField($element, FormStateInterface $form_state) {
    if($form_state->isSubmitted() && !empty($form_state->getValue('results'))) {
      $form_state->setValueForElement($element, "0");
      $element['#default_value'] = "0";
    }
  }

```
> 0 votes

---
Tags: forms, 8
---


title: Forms api validate float

text:
# Question
Title: Forms api validate float
when using the Drupal FAPI and needing a float number field you have to use type textfield. What's the best way to validate that this data is a float during hook\_form\_validate9)? Is there a built in function. or do you have to do is\_float()?

Thanks.

# Answer
> 1 votes
Because form input is always a string, is better to use is\_numeric().

See is\_float() note.

# Answer
> 0 votes
Drupal does not have an `is_float()` wrapper function. So yes, if you want to check to see if a string is a float, use PHP's native `is_float()`.

# Answer
> 0 votes
The FAPI provides the ability to define a validation callback on any element. Many of the validation callbacks you would like to use already exist.

See: https://api.drupal.org/api/drupal/includes!form.inc/function/element\_validate\_number/7.x

You would use it like this:

```
$form['my_numeric_field'] = array(
  '#type' => 'textfield',
  '#title' => t('My Numeric Field'),
  '#element_validate' => array('element_validate_number'),
);

```

---
Tags: forms
---


# Question
Title: Using HOOK_username_alter() to hide the real username
I'm using a pattern for the username creation using the contrib module: automatic\_usernames, this results in the following pattern for my use case: `[hotel_name][uid]`. Example: Hilton10

Here is the dilemma. This is fine for the business to see, but I do not want them to see their customer's actual username that they just created such as Hilton11 and instead I would like them to see the first name + last name of the customer.

How would I go about this using the following custom fields?

```
[#field_name] => field_customer_first_name

[#field_name] => field_customer_last_name

function MyCustomModule_username_alter(&$name, $account){
 global $user;
    if(in_array('venue admin', $user->roles)) {
    $name = ? //this is where im stuck
}

```

# Answer
The `$account` argument in `hook_username_alter()` provides the user entity object with all its field values. You can use its field values for your `$name` substitution. For example:

```
function MyCustomModule_username_alter(&$name, $account){
  global $user;

  // This example presumes a field_first_name as a user first name field.
  // It will vary based on your field & language environment.
  // use Devel's dpm() to find your actual value for user entity.
  if (isset($account->field_first_name[LANGUAGE_NONE][0]['value'])
      && in_array('venue admin', $user->roles)) {
    $name = $account->field_first_name[LANGUAGE_NONE][0]['value'];
  }
}

```
> 6 votes

---
Tags: 7, users, hooks
---


title: Webform ID not shown in debug output?

text:
# Question
Title: Webform ID not shown in debug output?
I created a new module to extend the webform module for custom submission hooks:

```
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'webform_client_form_213') {
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
    }
}

```

I have the webform module installed and I created a webform that has a node id of 213.

When I try to output the $form\_id variable, the value shown is nothing indicative of a webform and instead showing "search\_form\_block" as the form ID?

what is the error here? I pulled it straight from this example.

# Answer
> 1 votes
1. Install the Devel module.
2. Use the dpm() function, it will print out `$form_id` for *all forms* on any page you visit.

```
function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id);
}

```

---
Tags: 7, webforms, forms
---


# Question
Title: Regenerating images after new image style
I created a new image style. When I inspect my code, the image style has been applied but it doesn't find the image. The image and the new folder in `sites/default/files/styles` hasn't been created?

Whats wrong, how do I generate my new image(s)?

# Answer
Drupal creates derivatives images "on the fly" based on a defined image style. The act of creating a new style does not generate any images. Rather, the first time an image is requested using that style it will be generated and saved in `sites/default/files/styles/{stylename}/path/to/image.jpg`.

If you (for example) create a view that displays nodes with images using your newly defined image style, then as soon as you go to a page with that view the images will be generated.
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to list blogs by anonymous in blog module
I am able to list blogs by a specific user, e.g. /blog/123 - where 123 is the uid, but when I use /blog/0 I get access denied.

Can someone advise on a config setting to enable /blog/0 to list blogs by anonymous user (i.e. uid = 0), please?

I could implement a hook or override the View or something, just wanted to check if there isn't a config setting somewhere. I couldn't see one, looking so far.

# Answer
The blog route `blog/%user_uid_optional` route provided by the blog module performs a few checks in `blog_page_user_access()`:

```
  // The visitor must be able to access the site's content.
  // For a blog to 'exist' the user must either be able to
  // create new blog entries, or it must have existing posts.
  return $account->uid &&
         user_access('access content') &&
         (user_access('create blog content', $account) ||
          _blog_post_exists($account));

```

The `$account->uid` part of the conditional check will preclude access to **blog/0** even if anonymous users can create blogs posts.

A module evoking `hook_menu_alter()` you can override this route behavior by providing your own access callback that excludes the `$account->uid` check:

```
/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog/%user_uid_optional'])) {
    $items['blog/%user_uid_optional']['access callback'] = 'MYMODULE_blog_page_user_access';
  }
}

function MYMODULE_blog_page_user_access($account) {
  return user_access('access content') && (user_access('create blog content', $account) || _blog_post_exists($account));
}

```
> 2 votes

---
Tags: 7, users, nodes
---


# Question
Title: Use datefield year as condition in Entity Query
I'm performing an entity query that searches for nodes of my custom content type called 'news'. The content type has a date field called 'field\_date'. I want to be able to perform the query in a way that only produces the 'news' nodes that have a 'field\_date' that fits within a specified year. Here is an attempt I made below.

```
$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', [date('Y','field_date'), $year], '=')
  ->range(0, 10);

```

In the code above I'm attempting to only grab the year from the 'field\_date' datefield and compare that to $year, 2015 in this case. However I receive SQL errors like:

> Invalid parameter number: number of bound variables does not match number of tokens

I'm guessing part of it is date('Y','field\_date') doesn't know what 'field\_date' is but I'm not sure how to go about it.

How do I make a year comparison on a datefield in a entityquery condition?

# Answer
Assuming the data in the database looks like this: "2015-10-12T21:30:00", you can use a like query

```
->condition('field_date', $year . '%', 'like')

```

Your code revised with the change:

```
$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', $year . '%', 'like')
  ->range(0, 10);

```
> 4 votes

---
Tags: 8, database
---


# Question
Title: Is there a way to export the whole panelizer settings for a page?
With whole settings I mean: context, layout and content. I know how you can export the layout and context, but I do not know how to export the content.

We have several websites that share some pages in common which have widgets in the panels and we try to automate that so that our content managers do not have to do this with every setup.

# Answer
You can do this with Features:

* Enable Strongarm module
* Create new feature
* Export and Deploy Panelizer settings

Alternatively you can do this with a custom module. See https://www.phase2technology.com/blog/exporting-panelizer-defaults-to-code/
> 1 votes

---
Tags: panels, strongarm
---


# Question
Title: Clean URL regarding admin/* paths return 503 Service unavailable
I'm facing a weird problem in which all clean urls of admin pages such as admin/dashboard return 503 notice.

However, by changing url to non clean i.e. ?q=admin/dashboard it works.

All other content pages work normally with clean urls and just admin pages do not work.

I'm using shared host, apache, php7. I also have SSL enabled and therefore serving pages via HTTPS.

htaccess as follows:

```
#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  #RewriteRule ^ - [E=protossl]
  #RewriteCond %{HTTPS} on
  #RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>

```

# Answer
Well, this was a tough one.

There's a "node\_modules" folder under bootstrap theme which included a .info file (other than theme info).It is removed after a succesful "npm install --save-dev".

But of course Drupal goes nuts about it and boom you've got a 503 which tells you nothing about the problem.

After all day well spent - again.
> 1 votes

---
Tags: .htaccess
---


# Question
Title: How to place an Ubercart order on behalf of another user?
I would like to ask if it is possible to assign another UID, different from that of the currently logged in user, to an order under checkout process (e.g. via rules)?

Any idea how to do that? Thanks.

# Answer
> 0 votes
If you'd like to change ownership *during checkout*, probably not, or not without reworking some core UC code; there are likely to be permission problems if you switch the user owner before order completion.

Changing the ownership of a UC order is a trivial change.

```
$order = uc_order_load($order_id);
$order->uid = 1234;
uc_order_save($order);

```

But, the core Ubercart rules integration do not support a rules action that changes order ownership. So in order to use rules you'd need to build a custom action there. Also, because aforementioned permission problems, you'd likely need to use an event that occurs when the purchasing user no longer needs to own the order.

In summary, the above code is somewhat of a starting point, but you're looking at tripping over UC's order ownership enforcement if you go down this route.

# Answer
> 0 votes
fwiw I do something similar with the Masquerade module. I made the masquerade block show up for employees and this enables them to switch to a customer account to place an order. It works beautifully!

---
Tags: users, ubercart
---


# Question
Title: How to detect the newness of messages created with the Message module?
I have created messages to notify users that they have been tagged in a picture or that someone commented after them on a thread; pretty much like facebook-style notifications.

**How could I detect if a message targeting a user is new to him?**

I had two ideas:

* compare the timestamp of when the message has been created and the session timestamp. The session timestamp is refreshed every time a session requests a new page so I don't know if I can catch the previous value of this timestamp?
* catch the same event that triggers `drupal_set_message()`.

Would there be any other method to do that?

A recent post "This is a New Message/You have 4 New Messages" has been submitted in the issue queue of the Message module but apparently, it doesn't contain any built-in function to see if the message is new.

# Answer
> 1 votes
I ended up using a custom module with a table containing two columns: `uid` and `lastaccess` and two simple functions.

```
function notifmger_views_post_render(&$view, &$output, &$cache){
    if ($view->name == "notification" && $view->current_display == "page_1"){
        global $user;
        $check = db_query("SELECT * FROM notifmger WHERE uid = :uid",
            array(':uid' => $user->uid))->fetchCol(1);
        if (!empty($check)){
            $update = db_query("UPDATE notifmger SET lastaccess = :time WHERE uid = :uid", array(":time" => time(), ":uid" => $user->uid));
        }
        else {
            $insert = db_insert('notifmger')
            ->fields(array(
              'uid' => $user->uid,
              'lastaccess' => time()
            ))->execute();
        }
    }
}

function notifmger_counter() {
    global $user;
    $msgs = db_query("SELECT count(*) FROM message LEFT JOIN notifmger ON notifmger.uid = message.uid WHERE message.uid = :uid AND message.timestamp > notifmger.lastaccess AND message.type != :type", array(
        ":uid" => $user->uid,
        ":type" => "user_tagged_self"))->fetchCol();
    if ($msgs[0] != 0){
        return $msgs[0];
    }
    return NULL;
}

```

# Answer
> 1 votes
Have a look at my answer to "How to allow users to manage their own Message Stack messages?", which IMO is pretty close to the question here. It can be summarized like so:

1. Create a flag (using the the Flag module).
2. Create a view 'Messages by user'.
3. Use Rules to flag/unflag messages.
4. Trigger the Rules Component to mark messages (using the VBO module).
5. Create notifications about Unread Messages (using the "Menu Badges" module).

**Note**: no custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).

---
Tags: 7, notifications, message-subscribe
---


title: Aggregated entity reference translation

text:
# Question
Title: Aggregated entity reference translation
I'm having two customs content types in D7, one row (A) and another (B) that aggregates (via entity reference) the rows into bundles of rows (e.g. tables).

I can have up to 40 rows in a table. I'm translating manually each row in several languages. And then I'm creating one node (lets say node 100) in English of type B aggregating the 40 rows (let's say nodes 1-40) in English, and another node 101 in French (a translation of the English node 100) that aggregates the nodes 41-80 which are a direct translation of the 1-40 rows.

I would like while adding node 101 in French as a translation of node 100(English) to already pre-fill the node 101 to aggregate the nodes 41-80 which are in french and a one to one translation of the 1-40 English row nodes.

The translated entity reference module cannot help me in my case.

I tried to find a hook for the "add translation" to prepopulate the screen where the node 101 is being created as a translation of the node 100, and then just having to fill in 1-2 other extra fields in French and save...

Now I have to find the 41-80 references by hand, and since I'm having several languages (5 currently) the work involved is immense...

How could I achieve what I need? is there a module already written? otherwise which hook shall I use? I couldn't find an add translation hook in D7 (I believe there might be one in D8). I just need to know which hook to use for adding a new translation, I think I can manage the rest (finding for each row the translation in the target language).

I also do not need to do anything upon editing the node 101 after it has been saved, thus I only need the hook used the first time the node 101 is being created as a translation of node 100.

Many thanks

# Answer
The solution was to use the hook\_node\_prepare($node) and there to check if (!empty($node-\>translation\_source))

The above are the conditions that must be filled in to be in the "add translation" event.
> 0 votes

---
Tags: entities
---


# Question
Title: How can I move the modules that are dependencies for a module of mine in another directory?
I want to create a custom module with 2 dependencies. My module will be in sites/all/modules, and I need its dependencies to be in /modules/contrib.

How can I move the dependencies? I don't need any Drush command. It must be done using the browser only.

# Answer
> 1 votes
Drupal 7 doesn't look for modules on /modules. The list of directories looked for modules by `drupal_system_listing()` is the following one.

* profiles/$profile/modules and its sub-directories, where $profile is the short name of the profile currently installed
* sites/all/modules and its sub-directories
* $config/modules and its sub-directories, where $config is the directory containing the settings.php file used for the site

All those directories are relative to the directory containing Drupal, so a directory like /modules will never be checked for any module.

Actually, there isn't any need for a module to look for a specific directory for its dependencies. If the dependencies are modules that comes as *sub-modules* of the main module, they are normally put in the *modules* directory of the directory containing the main module, but the main module doesn't normally force Drupal to look in a specific directory for its own sub-modules.

Instead of /modules/contrib, you can use sites/all/modules/contrib, or sites/$site\_directory/modules/contrib. Those are directory where Drupal looks for modules.

There isn't any way to move a module from browser, and it is normally not necessary. You put the files with FTP or SSH, and you put the modules in the correct directory before installing the module using them.
If you already have your module installed, you disable it, disable its dependencies, move its dependencies in the correct directory (one that Drupal checks), enable them, and enable the module using them. If disabling/enabling doesn't work, you simply uninstall/install the modules.

---
Tags: 7
---


# Question
Title: How would we limit the drop down for the Date's Timzone field?
We are using the Date module that allows for enabling of Timezone during node edit (node/edit). We noticed that the dropdown is really long and we were wondering if there was a way to shorten the list to just say ETC, PST, UTC, GMT, etc.

We tried all the configuration setting, but could not shorten the drop down.

Current scenario:

Desired scenario:

Timezone (as an example) \- UTC \- PST/PDT \- MST/MDT \- EST/EDT \- GMT

# Answer
The Date module's field elements are supplied by the Date API module. The timezone component is supplied by its process callback `date_timezone_element_process()`.

It triggers `hook_date_timezone_process_alter()` which can be evoked by a custom module to alter the options within `$element['timezone']['#options']`.

For example:

```
/**
 * Implements hook_date_timezone_process_alter().
 */
function MYMODULE_date_timezone_process_alter(&$element, &$form_state, &$context) {

  if (isset($element['timezone']['#options'])) {
    // @TODO: Supply an array filter function that filters
    // IANA TZ names that don't correspond to
    // UTC - PST/PDT - MST/MDT - EST/EDT - GMT

    // Example: Filter TZ's that are only in the Americas
    $element['timezone']['#options'] = array_filter($element['timezone']['#options'], function($key) {
      return strpos($key, 'America/') !== FALSE;
    }, ARRAY_FILTER_USE_KEY);

  }
}

```
> 1 votes

---
Tags: 7, entities, i18n-l10n, datetime
---


# Question
Title: Where do I get a webhook url for a facebook messenger bot?
I want to check out and explore this interesting drupal module made by the white house: https://github.com/WhiteHouse/fb\_messenger\_bot

I've successfully installed drupal on my Mac thru MAMP. I've also enabled the said module. But I got stuck on this step of the installation instructions as stated in the README:

*"Complete steps 1-4 outlined in Facebook's quickstart documentation including the copying of the page access token in step 3 (note: this module sets up the webhook at /webhook/contact)"*

To be more specific, Facebook is asking for a callback url, but I can't find it. Whenever I type https://localhost:8888/webhook/contact as the callback url, Facebook gives me this error message:

*The URL couldn't be validated. Callback verification failed with the following errors: curl\_errno = 56; curl\_error = Received HTTP code 502 from proxy after CONNECT; HTTP Status Code = 502; HTTP Message = Private address*

I am completely new to drupal and MAMP. Any help that would point me towards the right direction would be greatly appreciated. Thank you very much!

# Answer
If you are working in a local development environment, you will need a publicly accessible IP address or domain name to route the FB request to your local server messenger bot webhooks.
> 0 votes

---
Tags: hooks, uri
---


# Question
Title: How can I access XMLSitemap links from external PHP script?
I have an external PHP script that does a lot of back end processing for a website. I need for this PHP script to query, insert, and delete various links from the XML Sitemap.

I want to use XMLSitemap's API instead of raw SQL so any additional functionality that needs to happen on inserts and deletes are called, like any alter hooks, etc.

I don't want to bog down the website for this processing, hence why I need to do this from a back-end script.

# Answer
> 2 votes
You'll need to bootstrap the Drupal environment in your PHP script to do this. There are many ways to do this, probably the easiest is Drush's php-script command:

```
drush php-script my_custom_script.php

```

This will let you execute any arbitrary PHP script in a bootstrapped Drupal environment.

Once you have your script running your Drupal environment, you can utilize the XMLSitemap API functions for all your CRUD operations.

---
Tags: 7, xml-sitemap
---


# Question
Title: How can I change the "page not found" message?
I want to change the *page not found* error message.

Recently, message shows like *The requested page could not be found.* I want to show *The requested page "/nvzmx,nvm,zxnv," could not be found.*

I don't want to create a custom page. I only want to change the error message given in the *page not found* page.

# Answer
You can do this by overwriting the route `system.404` with a custom controller:

**mymodule/src/Controller/MyHttp4xxController.php**

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyHttp4xxController extends ControllerBase {

  public function on404() {
    return [
      '#markup' => $this->t('Custom 404 message'),
    ];
  }

```

**mymodule.routing.yml**

```
system.404:
  path: '/system/404'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyHttp4xxController:on404'
    _title: 'Page not found'
  requirements:
    _access: 'TRUE'

```

**mymodule.install**

```
<?php

function mymodule_install() {
  module_set_weight('mymodule', 1);
}

```

You have to be sure, that your module runs after the system module, so that you can overwrite the route from the system module. This is why you need to set the module weight to 1. You need to reinstall the module, when you implement this.
> 3 votes

---
Tags: 8, status-messages
---


title: Internal server error on node save

text:
# Question
Title: Internal server error on node save
I'm getting internal server error on node save.

In `db log messages` there is no such error regarding this issue.

In apache error log I have these messages

```
mod_fcgid: read data timeout in 40 seconds, referer: http://test.com/node/add/photos
[error] Premature end of script headers: php-fcgi-wrapper, referer: http://test.com/node/add/photos

```

# Answer
> 0 votes
This was most likely caused by a rather long script that was timing out. The `IPCCommTimeout` on your virtual server is set to 40 seconds. If you encounter this problem again, you could edit the Apache directives that apply to this virtual server in `/etc/apache2/sites-available/test.com.conf` and set IPCCommTimeout, for example, to 300.

If you are using Virtualmin

* Chose the virtual server that you want to edit from the drop-down
menu
* Go to Services -\> Configure Website -\> Edit Directives
* Modify IPCCommTimeout from 40 to, for ex. 300 (seconds)

---
Tags: 7, nodes
---


# Question
Title: How to use Rules to assign user badges to users with sufficient User points?
I want users on my sites to have badges assigned to them. I have user points,user badges, and rules module. User points is working fine. I have created a badge. Now I want that whenever a user's total points is greater than, say 50, he or she is assigned a badge. So, I went about to create a rule. However, I was not able to find any event, condition, or action for this. Please advice

**Note**: I tried to assign badges directly to users by going to their profiles and assigning them badges...however when i try to do so i get the following error:"My\_Badge" is not a valid badge. Try using the autocomplete function (requires javascript). What is this?

# Answer
> 0 votes
This might not be an issue anymore, nevertheless, I think the problem should be solved now as the User Badges module has a production version out and most of the bugs have been taken care of. So, please upgrade to the latest 7.x-1.0 recommended release.

As for why you were not able to add a badge in your Rules action, well, the D7 version of User Badges was not integrated with Rules. We are actually working on it and it should be integrated very shortly.

# Answer
> 0 votes
Which version of User Badges are you using?

According to the module page "The 7.x version is NOT suitable for production yet." so if you want to use it you will probably need to do some manual debugging at the very least.

This user had the same issue you are seeing and they said uninstalling and reinstalling the latest 2.x dev worked for them.

# Answer
> 0 votes
Have a look at this Rules example (in Rules export format):

```
{ "rules_grant_a_new_badge" : {
    "LABEL" : "Grant a new badge",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "user_badges", "rules_conditional" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "50" } },
            "DO" : [
              { "add_badge_by_name" : { "badge" : "1", "user" : [ "userpoints-transaction:user" ] } }
            ]
          }
        ]
      }
    ]
  }
}

```

It does retrieve, as the very first Rules Action (not Rules Condition!) the current amount of user points of a user. If the amount is at least 50, it will grant the user badge.

In this example I'm using the Conditional Rules module. By using this module, you can consolidate the logic for various user badges in a single rule, e.g bronze for 50 points, silver for 500 points, gold for 5000 points. Though you could also rework the Rules Action to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".

The clue to make this rule work is the very first Rules Action "***Load user points of a user***". That's the alternative (work around?) for something like a missing Rules Condition to "check the current user points for a user".

---
Tags: 7, rules, userpoints, users
---


# Question
Title: What is the form ID of a submitted Webform to perform a custom redirect?
Once the webform is submitted, I need it to be redirected to edit form page where user can edit that form again.

I know is at `webform->components->form` settings and choose custom redirect. What is the value I should key in (since form ID is always different)?

# Answer
> 3 votes
There are number of ways to do this:

1. Use rules on event "After saving a node" -\> condition : "node is of type webform" -\> action : "add redirect" ; path : `node/[nid]/webform`. **Note:** `[nid]` might not be the exact token, but you'll get the exact token in the replacement patterns in the Rules UI.
2. Implement `hook_node_insert` in your custom module which triggers after every new node is created, check for the `$node->type` if it is of type `webform`, and use `drupal_goto` to redirect to the form components page. Path `node/{$node->id}/webform`.
3. Alter the `node_form` for webform to add a submit handler and use
`form_state['redirect'] = 'node' . $form_state['nid'] . '/webform';`

# Answer
> 1 votes
The easiest way to achieve this is to go to the `Webform settings configuration` page i.e `www.example.com/node/[nid]/webform/configure`.

There under the `Redirection location` settings, you can add the Custom URL with the required tokens i.e `node/[node:nid]/submission/[submission:sid]/edit`.

Please make sure that token module is installed and the permissions allow the user to edit the submission.

# Answer
> 0 votes
I use webform rule to solve my issue. Just need to install webform rule module.

---
Tags: 7, webforms
---


# Question
Title: Pass variables through AJAX callback and update MySQL database
I have a form where the users submit a text. Here is the code:

```
$form['reason'] = array(
            '#type' => 'textfield',
            '#title' => '',
            '#size' => '200',
            '#attributes' =>array('placeholder' => t('*Reason')),
            '#prefix' => '<div>'
          );

    $form['newsletter_unsubscribe_submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#attributes'=> array(
            'class' => ['btn', 'btn-primary']
        ),
        '#ajax' => array(
            'callback' => 'newsletter_unsubscribe_quiz_submit_driven_callback_share',
            'method' => 'replace',
            'effect' => 'fade',
        ),
        '#prefix' => '<div class="regular newsletter_unsubscribe_button">',
        '#suffix' => '</div></div>');

    return $form;

```

I managed to get the input of the user on a variable using `$_values = $form_state['values'];`
Also, I have some other variables to read from the current path and get some values.

```
    $_path = $_SERVER['HTTP_HOST'] . request_uri();

    preg_match('~id=(.*?)&~', $_path, $id);

    $first = $id[1];
    $second = substr($_path, -5);

```

where the first is the user id and the second is another variable that is unique per user.
My only problem is that I can't pass the $first and $second variables through the callback, and have them along with $reason `$_reason = filter_xss($_values['reason']);`
So, in my callback I want to be able to get the variables $first,$second with the $reason I already have. Now I have the $\_path variables above my form, in the same function.
Then I want to perform an update query on MySQL, something like

```
UPDATE users SET reason=$reason
WHERE first=$first AND second=$second

```

where the column users has only the columns first,second and reason . Is this possible? Thanks in advance!

**EDIT**
I actually managed to do the first part and get the variables. I created two form inputs and I give them default values, the two variables I want to get, and I will hide them afterwards.
I still haven't figured out how to update MySQL though, so all answers are welcome!

# Answer
I actually managed to do it! For anyone that may have a similar problem this is what I did.
First of all, I took the url parameters using `parse_url` and did the following

```
$parts =  parse_url($_path);
parse_str($parts['query'], $query);
$first = $query['first'];
$second = $query['second'];

```

,then put those variables as form default values, that I will hide using css:

```
$form['user_id'] = array (
         '#type' => 'textfield',
         '#title' => t('User id'),
         '#description' => t('user id'),
         '#default_value' => $first,
);

```

Then, on my callback function I take those variables, for example:

```
$_first = filter_xss($_values['first']);

```

and then I used `db_update`:

```
$num_updated = db_update('unsubscribed_users')
    ->fields(array(
        'reason' => $_reason,
      ))
    ->condition('first', $_first , '=')
    ->condition('second', $_second , '=')
    ->execute();

```
> 2 votes

---
Tags: 7, forms, database
---


# Question
Title: How to show a table depending on a drop down selection?
Initially there is only drop down menu in the form, when a selection is made I want to display a table in the same form.

```
$form['blood_group'] = array(
    '#type' => 'select',
    '#title' => t('Blood Group'),
    '#options' => array(
        'a+' => 'a +ve',
        'b+' => 'b +ve',
        'ab+' => 'ab +ve',
        'o+' => 'o +ve',
        ),
    '#required' => TRUE,
);

```

suppose if the user selects a+ i have to show the table containing names of all the people with the same blood group.

# Answer
> 2 votes
You can take a look at the #ajax property of the Drupal Form API.

Here is a good start :

```
$form['blood_group_wrapper']['tables'] = array(
  '#prefix' => '<div id="table-wrapper">',
  '#suffix' => '</div>',
);

$form['blood_group_wrapper']['blood_group'] = array(
  '#type' => 'select',
  '#title' => t('Blood Group'),
  '#options' => array(
      'a+' => 'a +ve',
      'b+' => 'b +ve',
      'ab+' => 'ab +ve',
      'o+' => 'o +ve',
      ),
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_show_table',
    'wrapper' => 'table-wrapper',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

function ajax_show_table($form, $form_state) {
  $table = '<table></table>';
  $form['blood_group_wrapper']['tables']['#markup'] = $table;

  return $form['blood_group_wrapper']['tables'];

}

```

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


title: Where are the facet blocks for search?

text:
# Question
Title: Where are the facet blocks for search?
In drupal 8, I have added couple of facets at this page /admin/config/search/facets

According to the documentation I should now have some blocks to put on the search page. But I do not see any blocks that represent those facets on the Admin block page(admin/structure/block)

the block for the faceted search does not show up when I look for it in place block modal dialog.

What step am I missing?

# Answer
The block is already created; you just need to place it following these steps:

1. Go to *Structure \> Block layout*
2. Click on \_Place block; you will get the list of available blocks
3. Search for the facet block and click on *Place block*
> 1 votes

---
Tags: 8, search
---


# Question
Title: How to override VBO redirect after performed action?
My problem is that I can't override the URL where VBO redirects me to after I performed a default action. When I write my own actions I simply put `$_GET['destination'] = 'my/target';` inside my custom form submit and that works. I tried to alter VBO's form submit to attach my own submit but that doesn't work:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_bulk_operations_form') {
    array_push($form['#submit'], 'MYMODULE_vbo_redirect');
  };
}

function MYMODULE_vbo_redirect() {
  $_GET['destination'] = 'my/target';
}

```

When I testhack the VBO module and inside `views_bulk_operations_form_submit($form, &$form_state)` replace the final redirect with my custom one, it works. How can I get inside there and get my custom redirect executed without hacking?

# Answer
I tried to alter the wrong form. VBO somehow merges its form stuff with the views form itself. So I had to look there to attach my custom submit. Then I had to pay attention to attach it in the same moment the `views_bulk_operations_form_submit` is attached. Then I set the cancel button to also bring me back where I want. And finally set `$form_state['redirect']` in my attached submit.

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}

```

Only problem left is that this redirect always gets triggered when performing any VBO action from this view. But I can live with that for now.
> 2 votes

# Answer
Has for VBO, there is a hook dedicated for form alter: `hook_views_bulk_operations_form_alter(&$form, &$form_state, $vbo)`

Example (modifying the email action):

```
function YOURMODULE_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
  $form_id = $form['#form_id'];
  if ($form_state['step'] == 'views_form_views_form') {
    // Alter the first step of the VBO form (the selection page).
  }
  elseif ($form_state['step'] == 'views_bulk_operations_config_form') {
    // Alter the configuration step of the VBO form.
    if( $form_id == 'views_form_YOURVIEWSMACHINENAME_YOURVIEWSDISPLAY' ) {
      if(isset($form['recipient'])) {
        $form['recipient']['#default_value'] = '[user:mail]';
      }
      $form['message']['#type'] = 'text_format'; //> sends an array...
      $form['message']['#default_value'] = variable_get('NAMEOFAVAR');
      //add token list
      $form['token'] = array(
          '#type' => 'fieldset',
          '#title' => t('Replacement tokens'),
          '#collapsible' => TRUE,
          '#collapsed' => TRUE,
      );
      $token_types = array('user');
      $form['token']['tokens'] = array(
          '#markup' => theme('token_tree', array('token_types' => $token_types))
      );
    }
  }
  elseif ($form_state['step'] == 'views_bulk_operations_confirm_form') {
    // Alter the confirmation step of the VBO form.
    array_unshift($form['actions']['submit']['#submit'], 'YOURMODULE_sendmail_vbo_submit');
    $form_state['operation']->formOptions['message'] = $form_state['operation']->formOptions['message']['value'];
  }
}

```

The only thing to notice is that in your custom submit function, you don't get the form\_state values has usual. I must dig more to find how to get them.

EDIT: To alter/save/do stuff with `$form_state['values']`, better to put your custom submit or validate function in the second "if":

```
elseif ($form_state['step'] == 'views_bulk_operations_config_form') {
      $form['actions']['submit']['#validate'][] = 'YOURMODULE_sendmail_vbo_validate';
}

```
> 1 votes

# Answer
In general you can use `hook_drupal_goto_alter`, for example:

```
/**
 * Implements hook_drupal_goto_alter().
 */
function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  if (CONDITION) {
    $path = 'my/target';
  }
}

```

Where in CONDITION you can check for the specific desired path which you want to override by checking the value of `current_path()` or `arg()`.

Not ideal, but it's simpler than implementing custom submit handler (e.g. in `$form['select']['action::views_bulk_operations_argument_selector_action']['#submit']`) using `hook_views_bulk_operations_form_alter` and finding the right place to override the path.
> 0 votes

# Answer
```
function MYMODULE_form_alter(&$form, &$form_state, $form_id)
{
 if ($form_id == 'views_bulk_operations_form') {
$form['#submit']='MYMODULE_vbo_redirect';
}
}
function MYMODULE_vbo_redirect() {
// Use die('here') and submit the form.if it dies then redirect it
drupal_goto('my/target');
}

```

Hope this will helps you
> -1 votes

---
Tags: 7, redirection, views
---


# Question
Title: How to add parameter to URL when passing ids as arguments to a page?
I have a view with an action *Pass ids as arguments to a page* where I need to add to the link. There is a parameter which I receive in the URL. I can print the parameter in the view, but I am not able to pass it as a token. It is not parsed.

Any ideas?

---

Basically I need to duplicate a node and assign to it a dynamic list of properties (other nodes). I created a view and added a VBO field. User select the ids and they get passed to my URL for elaboration. So far so good. My problem is that I need to pass, in addition to the ids, another field from the view. I tried to specify it in the URL `/admin/myurl/[my_field]`, but it doesn't parse the token.

# Answer
> 1 votes
Here is the workaround by implementing token support in `hook_drupal_goto_alter`:

```
/**
 * Implements hook_drupal_goto_alter().
 */
function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  if (module_exists('token') && user_access('administer nodes') && strpos($path, '[') !== FALSE) {
    // If token is found in path, replace it.
    // This feature is only available for admins for safety reasons.
    $path = token_replace($path);
  }
}

```

This will work for VBO select action, so you can use the path like: `/some/path/[current-page:arg:4]/csv` to pass the 4th parameter from the URL into another view.

# Answer
> 0 votes
As per suggestion from this post, you should write a custom action using `hook_action_info` similar as *Pass ids as arguments* VBO action, so consider duplicating it as a starting point.

See also the following feature request: Token support in "Pass ids as arguments to a page" URL field.

---
Tags: 7, views
---


# Question
Title: how to customize my views-view-table.tpl.php?
i have a view table for property list and i want to customize the view source code to make it print specific label that i add from inside of view in the administration

the view source code :

```
<thead>
  <tr>
    <?php foreach ($header as $field => $label): ?>
      <th <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?> scope="col">
        <?php print $label; ?>
      </th>
    <?php endforeach; ?>
  </tr>
</thead>

```

but this code print all fields labels even its empty!

output :

the output that i need like this :

any suggestion to update the code ?

# Answer
> 0 votes
The best way is to use field\_info\_instance($entity\_type, $field\_name, $bundle\_name)to get information about specific instance of a field. The label of the field is contained in the array returned from that function.

The general code :

`<?php
 $info = field_info_instance($entity_type, $field_name, $bundle_name);
 print $info['label'];
 ?> :`

in my situation :

`<?php
 $info = field_info_instance('node','property_photo','property');
 print $info['label'];
 ?> :`

OR

by Using this Code :

```
<?php print $header['$field_name']; ?> :

```

in my situation :

```
    <?php print $header['property_photo']; ?> :

```

that's it .

---
Tags: views
---


# Question
Title: Redirect on Custom page after one time login link
I created password reset link using `user_pass_reset_url` function. This is redirecting to `user/uid/edit` page after click login.

How to redirect on custom url?

# Answer
> 0 votes
Done using Custom code `drupal_goto`. I checked the current path and redirect it using `drupal_goto`. So whenever the user go to user/edit link he will be redirected.

# Answer
> 2 votes
Since the form builder for user/reset/%/%/% (user\_pass\_reset()) is using the following code to redirect the user, you can only replace the form builder with one that redirects the users where you want.

```
      $token = drupal_hash_base64(drupal_random_bytes(55));
      $_SESSION['pass_reset_' . $user->uid] = $token;
      drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));

```

If you do that (which means implementing `hook_menu_alter()`), be careful of how the workflow is modified. If you need to change that radically, and you want to be sure not to introduce security risks, I would rather:

* Alter the URL returned from `user_pass_reset_url()`, so that users are redirected to your page
* Implement a form builder for your page using the code used by `user_pass_reset()` as guideline

# Answer
> 0 votes
You can use `hook_drupal_goto_alter` to customize the current user password reset URL, e.g.

```
/**
 * Implements hook_drupal_goto_alter().
 */
function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  if (module_exists('token') && arg(0) == 'user' && arg(1) == 'reset') {
    $path = user_pass_reset_url();
  }
}

```

Where `user_pass_reset_url()` is your custom function providing new URL.

---
Tags: 7, users
---


# Question
Title: How can I theme individual fields in a row?
I'm having trouble doing something that I think should be relatively simple Drupal 8 views.

I have a content type called Countries. I would like to display the 3 latest country nodes on my homepage in a views block. Each country is displayed with the class "views-row" on the container div. I am using `views--view--unformatted--countries--block_1.html.twig` to theme the output.

I would like to output something like the following markup:

```
<a class="view-row-1" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-2" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-3" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

```

The problem I'm having is accessing individual fields in the template. If I use a view mode, I can access individual fields. If I select "show fields" in the view, I can add a field for "view result counter" and "path", which would allow me to add the "view-row-N" class and link the a tag to the node, but I can't get access to the fields individually. I have the `{{ row.content }}` variable, but any attempt to dig further into the variable (eg row.content.field\_name) gives me nothing and calling a `{{ dump(row.content) }}` crashes the website.

I can't output this as a view mode for 2 reasons. I don't have access to the "view result counter" or "path" fields in a view mode and, even if I had these variables, some fields would be nested inside others (The image and title are nested inside the )

I feel this should really be as simple as

```
<a class="view-row-{{ row.content.view_result_counter }}" href="{{ row.content.path }}">

```

etc but I've tried everything I can think of. Am I completely on the wrong path?

# Answer
You are on the wrong track. If you want to rewrite in twig how the fields are built to a row, you have to use the template `views-view-fields.html.twig`.

But the simplest method would be to rewrite the result of the fields in views ui. This is the option *"Override the output of this field with custom text"*. If you apply this on the last field and hide all previous fields with the option *"Exclude from display"*, you can see the twig variables for all fields in *"Replacement patterns"* and you are able to rewrite the complete row like the example you have shown in the question.
> 5 votes

---
Tags: views, theming, 8
---