# Question
Title: Unable to programmatically render webform with supplied default values
I have a block that is rendering a webform programmatically however I want to change a field based on the node that it's appearing on. I'm performing this like so.

```
    $webform_id = 'contact';
    $current_node = \Drupal::routeMatch()->getParameter('node');
    $contact_form = \Drupal\webform\Entity\Webform::load($webform_id);
    $values = ['data' => ['contact_email' => $current_node->field_email->value, 'message' => 'test']];
    $contact_form->getSubmissionForm($values);
    $contact_form_render = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($contact_form);
    return $contact_form_render;

```

It is able to render the webform just fine, however the supplied values for the contact\_email field and the message field do not appear, even though they were supplied as a parameter for getSubmissionForm. I've used https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform as an example but I don't seem to see any discrepancies between my code and theirs.

Is there something wrong with how I'm supplying the values to the programmatically rendered webform?

UPDATE: I tried doing things in a more manual manner

```
$form_storage = \Drupal::entityTypeManager()->getStorage('webform');
$webform_submission = $form_storage
      ->create(['webform_id'=>'contact', 'data' => ['contact_email' => $current_node->field_email->value],'message' => 'testing']);

$contact_form_render = \Drupal::entityManager()
      ->getViewBuilder('webform')
      ->view($webform_submission);

```

However I get the error

> Exception: Webform id (webform\_id) is required to create a webform submission. in Drupal\webform\Entity\WebformSubmission::preCreate() (line 586 of modules/contrib/webform/src/Entity/WebformSubmission.php).

Even though I'm explicitly setting the webform\_id.

# Answer
> 6 votes
Did you try using the Webform render element documented at the bottom of https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform.

```
return [
  '#type' => 'webform',
  '#webform' => 'your_form_id',
  '#default_data' => ['name' => 'Custom Name'],
];

```

---
Tags: 8, webforms
---


# Question
Title: How do I check by default a checkbox from a checkboxes control after an AJAX call
I have the next form which behavior is:

* When you select an option from select control, different checkbox are load on checkboxes control.
* When you check/uncheck checkbox a message is showed on the botton with info about select value and checkbox clicked.

Everything works fine, but is impossible check by default a checkbox from checkboxes control after ajax function.

Any idea?

```

namespace Drupal\drupal_miseries\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

class CheckboxesAjax extends FormBase {

    protected $values = [
        'select' => [
            '1' => 'Value1',
            '2' => 'Value2',
        ],
        // Options when select 1 is selected
        'checkboxes_v1' => [
            '1' => 'checkbox1',
            '2' => 'checkbox2',
        ],
        // Options when select 2 is selected
        'checkboxes_v2' => [
            '3' => 'checkbox3',
            '4' => 'checkbox4',
        ],
        // Default values for checkboxes
        'checkboxes_df' => [
            // Default value when checkboxes_v1 is showed
            '1' => ['1' => '1', '2' => '0'],
            // Default value when checkboxes_v2 is showed
            '2' => ['3' => '0', '4' => '1'],
        ],
    ];

    public function getFormId() {
        return 'drupal_miseries_checkboxesajax';
    }

    public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      return $form['container'];
    }

    public function checkboxesAjaxCallback(array &$form, FormStateInterface $form_state) {
      $checkbox = $form_state->getTriggeringElement();
      $select = $form_state->getValue('select');

      $form['status']['mensaje'] = [
          '#markup' => '

Select: '.$select.' '.$checkbox['#title'].' clicked.'.'

',
      ];

      return $form['status'];
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
      $form['select'] = [
        '#type' => 'select',
        '#title' => $this->t('Select form control'),
        '#options' => $this->values['select'],
        '#default_value' => key($this->values['select']),
        '#ajax' => [
            'callback' => [$this, 'selectAjaxCallback'],
            'wrapper' => 'checkboxes_wrapper',
        ],
      ];

      $form['container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'checkboxes_wrapper'],
      ];

      $form['container']['checkboxes'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Checkboxes form control from select @select',
          [ '@select' => empty($form_state->getValues()) ?
              $this->values['select'][key($this->values['select'])] : $form_state->getValue('select') ]),
        '#options' => empty($form_state->getValues()) ?
          $this->values['checkboxes_v1'] :
          $this->values['checkboxes_v'.$form_state->getValue('select')],
        '#default_value' => empty($form_state->getValues()) ?
          $this->values['checkboxes_df']['1'] :
          $this->values['checkboxes_df'][$form_state->getValue('select')],
        '#ajax' => [
            'callback' => [$this, 'checkboxesAjaxCallback'],
            'wrapper' => 'status',
        ],
      ];

      $form['status'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'status'],
      ];

      return $form;
    }

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

    }
}

```

# Answer
Thanks @IvanJaros, i have read it and i think i'm doing everything fine but i can't understand why is not working.

I have modify selectAjaxCallback to solve this problem:

```

public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      $select = $form_state->getValue('select');

      foreach ($this->values['checkboxes_df'][$select] as $key => $value) {
        $form['container']['checkboxes'][$key]['#checked'] = $value;
      }
      return $form['container'];
    }

```

This code works, but i'm not sure if it's the right way to solve this problem.

Thanks.
> 0 votes

---
Tags: 8, forms, ajax
---


# Question
Title: Which is the difference between the Full content and the Default mode?
The FieldUI uses the **default** as default value for entity form/view displays. But the EntityViewBuilderInterface uses the **full** as default value.

Also template\_preprocess\_taxonomy\_term() uses the **full** value to find out if the current page is taxonomy term.

So which one should I look for to know if "default" mode is being used? Should I be checking both values?

I think this applies to D7 too but I'm working with D8 so I'm looking for information within this context.

# Answer
> 2 votes
The argument for EntityViewBuilderInterface is $view\_mode.

View displays and view modes are *not* the same thing.

view\_mode can basically be anything you want, you can even make up them on the fly.

What the field formatter/widget system then does is look up if there is a form/view display with for that view mode. If that is the case, that is used. If not, then it falls back to `default`.

The view/form modes that you set up in the UI are basically only there to tell field UI that it can create form/view displays for them (the checkboxes at the bottom of the default display page). They are never used at runtime.

So, when you are going to node/1, there is by default no display for `full`, so it falls back to default. Whereas `teaser` does have one, so it uses different things. However, you can also enable a form display for `full` and then it will no longer use `default`.

# Answer
> 0 votes
There is no difference between default and full, they are essentially the same thing. "Full" is just a view mode and for some entities that is the "Default" view mode (not all though). Follows is more information like how to get the information that you are looking for in the correct way. I thought about removing the answer but I actually needed this information not too long ago and this may help someone else looking for a similar answer. With the question being a little vague it's hard to answer without making a guess at what is actually needed. If this is not what you are needing please let me know and I will update my answer accordingly.

Here is the view modes docs for explanation of different view modes in Drupal 8: https://www.drupal.org/node/2511722

In Drupal 7 you would use something like this (entity\_get\_info()):

```
$entity_info = entity_get_info('node');
dpm(array_keys($entity_info['view modes']));

```

That would return information like below:

```
array (
  0 => 'full',
  1 => 'teaser',
  2 => 'rss',
  3 => 'search_index',
  4 => 'search_result',
)

```

But Drupal 8 that function is deprecated (see here for more information.

So you would use code from the EntityManagerInterface:

```
/**
 * Gets the entity definition for an entity type.
 *
 * @param string|null $entity_type
 *   (optional) The entity type (e.g. 'node'). Leave NULL to retrieve
 *   information for all entity types.
 *
 * @return array
 *   An array containing the entity type's definition, as retrieved with
 *   \Drupal\Core\Entity\EntityManagerInterface. If $entity_type is NULL, an
 *   associative array of all entity type definitions keyed by entity type is
 *   returned.
 *
 * @see \Drupal\Core\Entity\EntityManagerInterface
 * @see hook_entity_info_alter()
 */

$allEntities = \Drupal::entityManager()->getDefinitions();

$nodeEntity = \Drupal::entityManager()->getDefinition('node');

dpm($nodeEntity);

```

You should be able to use devel to find out what the view mode is set to with the above code. These would ensure you are getting the correct view mode for whatever entity you are needing the information for at the time as the others that you have tried are returning information from different places and may not give you the correct results or results you need at the time.

# Answer
> 0 votes
There is a page named Display Modes, View Modes, and Form Modes that explain this a little.

***Display modes***

> Display modes (found at admin/structure/display-modes) exist to provide different presentations of Content Entities for either viewing or editing. The two types of display modes are "view modes" and "form modes."

***View modes and view displays***

> On this page (/admin/structure/types/manage/article/display) a site builder has the option to enable customized field display settings for the bundle (field order and field formatter usage) on a per view mode basis. It is not required that all view modes have specific customizations made for all bundles. In this example, only the view modes “RSS” and “Teaser” have their own specific settings. All other view modes fall back to the “default” configuration. The association between an entity type bundle and view mode is called a ***View Display***. @see EntityViewDisplayInterface

---
Tags: 8, forms
---


# Question
Title: Custom layout for a field in Drupal 7 with using a term id and term name
I have a content type that has term reference fields. One is a select one and one is a select many. What i'm trying to achieve is to overwrite the output for these fields.

I want the output of these 2 fields to be `<a href="../?selectedArtist={artistID}">{artistName}</a>` and `<a href="../?selectedLocation={locationID}">{locationName}</a>, <a href="../?selectedLocation={locationID}">{locationName}</a>`

These links will point to a page with an isotope grid layout on it, and will prepopulate the filters with what is in the querystring.

I have found how to update the output of the field, but I have no idea on how to get the terms ID and terms name.

```
function TEMPLATENAME_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'field_artist') {
      $variables['items']['0']['#markup'] = '<a href="../?selectedArtist=">View Map</a>';
    }
  }
}

```

Thanks.

# Answer
> 1 votes
After looking at https://www.digett.com/insights/change-output-single-field-drupal-7-node I realised that you can use `$variables['element']['#items']`

**term id** `$variables['element']['#items']['0']['tid']`

**term name** `$variables['element']['#items']['0']['taxonomy_term']->name`

---
Tags: theming, nodes
---


# Question
Title: Updating core from 8.2 to 8.3 via composer
I am trying to update Drupal core to 8.3 but am running into difficulties.

At the bottom of the page is the composer.json file I am starting with.

If i change "drupal/core": "~8.2" =\> "drupal/core": "~8.3" and then run `composer update drupal/core --with-dependencies` I get the following issues which i am not sure how to resolve this as they are not contained in the composer.json file i have included below.

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

   Problem 1
    - drupal/core 8.3.0 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.4.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - Conclusion: don't install symfony/psr-http-message-bridge 1.0.x-dev
    - Conclusion: don't install drupal/core 8.3.0-rc2
    - Conclusion: don't install drupal/core 8.3.0-rc1
    - Conclusion: don't install drupal/core 8.3.0-beta1
    - Installation request for symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2].
    - Conclusion: remove symfony/dom-crawler v3.2.6
    - Installation request for drupal/core ~8.3 -> satisfiable by drupal/core[8.3.0, 8.3.0-alpha1, 8.3.0-beta1, 8.3.0-rc1, 8.3.0-rc2, 8.3.x-dev, 8.4.x-dev].
    - Conclusion: don't install symfony/dom-crawler v3.2.6
    - drupal/core 8.3.0-alpha1 requires symfony/dom-crawler >=2.8.13 <3.0 -> satisfiable by symfony/dom-crawler[2.8.x-dev, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19].
    - Can only install one of: symfony/dom-crawler[2.8.x-dev, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.13, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.14, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.15, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.16, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.17, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.18, v3.2.6].
    - Can only install one of: symfony/dom-crawler[v2.8.19, v3.2.6].
    - Installation request for symfony/dom-crawler (locked at v3.2.6) -> satisfiable by symfony/dom-crawler[v3.2.6].

```

original composer.json

```
{
"name": "drupal/drupal",
"description": "Drupal is an open source content management platform powering millions of websites and applications.",
"type": "project",
"license": "GPL-2.0+",
"require": {
    "drupal/core": "~8.2",
    "drupal/backup_migrate": "4.x-dev",
    "composer/installers": "^1.0.21",
    "wikimedia/composer-merge-plugin": "~1.3",
    "drupal/console": "^1.0",
    "drupal/file_browser": "^1.0@alpha",
    "enyo/dropzone": "4.2.0",
    "desandro/masonry": "3.3.1",
    "desandro/imagesloaded": "3.1.8",
    "drupal/admin_toolbar": "^1.18",
    "drupal/ctools": "^3.0@alpha",
    "drupal/devel": "^1.0@beta",
    "drupal/migrate_tools": "^3.0",
    "drupal/migrate_plus": "^3.0",
    "drupal/media_entity": "^1.6",
    "drupal/media_entity_document": "^1.1",
    "drupal/media_entity_image": "^1.2",
    "drupal/inline_entity_form": "^1.0@beta",
    "drupal/entity_embed": "^1.0@beta",
    "drupal/entity_browser": "^1.0@beta",
    "paquettg/php-html-parser": "^1.7",
    "drupal/better_exposed_filters": "^3.0@alpha",
    "drupal/workbench_access": "^1.0@alpha",
    "drupal/webform": "^5.0@beta",
    "j7mbo/twitter-api-php": "^1.0",
    "nesbot/carbon": "^1.22",
    "Drupal/userprotect": "^1.0",
    "drupal/config_ignore": "^1.2",
    "Drupal/permissions_by_term": "^1.16",
    "Drupal/views_menu_children_filter": "^1.0@alpha",
    "drupal/sitemap": "^1.2",
    "drupal/xmlsitemap": "^1.0@alpha",
    "drupal/simple_sitemap": "^2.8",
    "drupal/redirect": "^1.0@alpha",
    "drupal/metatag": "^1.0",
    "drupal/acl": "^1.0@alpha",
    "drupal/examples": "1.x-dev",
    "drupal/honeypot": "^1.23",
    "drupal/field_collection": "^1.0@alpha",
    "drupal/dropzonejs": "^1.0@alpha",
    "drupal/embed": "^1.0@RC",
    "drupal/pathauto": "^1.0@RC",
    "drupal/rabbit_hole": "^1.0@beta",
    "drupal/entity_reference_display": "^1.0",
    "drupal/field_group": "^1.0@RC",
    "drupal/layouter": "^1.0",
    "drupal/mailsystem": "^4.1",
    "drupal/mimemail": "^1.0@alpha",
    "drupal/permissions_by_term": "^1.17",
    "drupal/content_access": "1.x-dev",
    "drupal/rules": "^3.0@alpha",
    "drupal/smart_trim": "^1.0",
    "drupal/taxonomy_menu": "^3.3",
    "drupal/token": "^1.0@RC",
    "drupal/typed_data": "^1.0@alpha",
    "drupal/video_embed_field": "^1.4",
    "drupal/views_infinite_scroll": "^1.3",
    "drupal/noreferrer": "^1.1",
    "drupal/system_status": "^2.4",
    "drupal/google_analytics": "^2.1"
},
"replace": {

},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
    "preferred-install": "dist",
    "autoloader-suffix": "Drupal8"
},
"extra": {
    "_readme": [
        "By default Drupal loads the autoloader from ./vendor/autoload.php.",
        "To change the autoloader you can edit ./autoload.php."
    ],
    "merge-plugin": {
        "include": [
            "core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "libraries/{$name}": [
            "type:drupal-library"
        ],
        "profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ]
    }
},
"autoload": {
    "psr-4": {
        "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
    }
},
"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},
"dependencies": {
    "backupmigrate/core": "dev-master",
    "psr/log": "dev-master"
},
"repositories": [
    {
        "type": "composer",
        "url":  "https://packages.drupal.org/8"
    },
    {
        "type": "package",
        "package": {
            "name": "desandro/masonry",
            "version": "3.3.1",
            "type": "drupal-library",
            "dist": {
                "url": "https://github.com/desandro/masonry/archive/v3.3.1.zip",
                "type": "zip"
            }
        }
    },
    {
        "type": "package",
        "package": {
            "name": "desandro/imagesloaded",
            "version": "3.1.8",
            "type": "drupal-library",
            "dist": {
                "url": "https://github.com/desandro/imagesloaded/archive/v3.1.8.zip",
                "type": "zip"
            }
        }
    },
    {
        "type": "package",
        "package": {
            "name": "enyo/dropzone",
            "version": "4.2.0",
            "type": "drupal-library",
            "source": {
                "url": "https://github.com/enyo/dropzone",
                "type": "git",
                "reference": "origin/master"
            }
        }
    },
    {
        "type": "vcs",
        "url": "https://github.com/backupmigrate/backup_migrate_core"
    }
]

```

}

# Answer
Similar to @rreiss I had to delete .lock. This is what worked for me:

```
rm -rf vendor && rm -rf docroot/core && rm -rf docroot/modules/contrib && rm -f composer.lock

composer require drupal/core:8.3.1 --update-with-dependencies

```

line one could be unique to your project, confirm by looking up installer-paths in your composer.json.
> 3 votes

# Answer
Just ran into this same thing. To fix I backed-up/deleted the /vendor directory and ran 'composer update' again so Composer would re-download all dependencies. I think installed dependencies vs. required get out of sync.
> 1 votes

# Answer
I had a very similar issue when attempting to upgrade from 8.3.7 to 8.4.0. I think I found the culprit.

In the DOCROOT composer.json file, I see the following lines:

```
"merge-plugin": {
    "include": [
        "core/composer.json"
    ],
    "recurse": false,
    "replace": false,
    "merge-extra": false
},

```

So this directs the DOCROOT composer.json file to refer to the `core/composer.json`file and also require those dependencies. The problem is that it is looking at the dependencies from your *currently installed version* of Drupal, whereas the upgraded version has new dependencies. This creates the conflict we're seeing.

Here is the solution I found which works. It does *not* require deleting any files or modules.

1)Download a copy of the `core/composer.json` file from *the tarball of the version of Drupal you are upgrading to*.

2)In your current installation, *replace* the `core/composer.json` file with the new version you just downloaded.

3)Update your DOCROOT composer.json file with "drupal/core:~8.x.x"(whatever you're upgrading to).

4)Run `composer update --with-dependencies` as usual. This time, the update should proceed. Then apply database/entity updates, rebuild the cache, etc. etc.

I'm a Windows user and definitely more of a site builder, so I won't even try to post command-line prompts to do these things in Linux. And I'm not sure if this is a "proper" solution, or even why that above code blocks the upgrade, but this is what worked for me!
> 1 votes

# Answer
Just noting that this seemed to work for me for core update from 8.2.3 \> 8.3.7. Note my Drupal 8 install used this: https://github.com/drupal-composer/drupal-scaffold which has this directory structure:

.git
.gitignore
composer.json
composer.lock
config
scripts
vendor
web

* Put site into maintenance mode: /admin/config/development/maintenance
* Run this command in the root of the site: `rm -rf vendor && rm -rf web/core && rm -f composer.lock`
* Run this command in the root of the site: `composer require drupal/core:8.3.7 --update-with-dependencies`
* Go to /update.php (or `drush updb`) and run the updates. It will say there are 17 to run. It will probably return errors, if so, go to /update.php and run updates again (this time it will say there are less to run). Go to home page when it is done.
* Check over the site.
* Take site out of maintenance mode: /admin/config/development/maintenance
> 0 votes

---
Tags: 8, updating, composer
---


# Question
Title: List of User's Comments - show one latest comment on node only
I have a views block that lists a user's comments on the site.

For example user JohnA has posted 5 comments total on the site like so:

* Node 1: 2 comments
* Node 2: 1 comment
* Node 3: 2 comments

In my view, I want to create a list of nodes that JohnA has commented on with the following Format:

```
<h1>Node Title</h1>
<p>By Node Author</p>
<p>You commented on this 2 months ago</p>

```

However, when a create a view and add the field Comment: Post Date, Node 1 and Node 3, which JohnA has commented on twice, show up twice (because JohnA has two values for that field in this context).

The view works fine until adding any comment specific field, such as comment post date, comment body, etc...

I'm thinking about using the Views View Field module as a potential solution. I feel like there is a simple solution that I am missing.

Any help would be greatly appreciated.

# Answer
I would use the Views Field View or a similar module for this.

The reasons is that you are trying to filter on two things: * Most recent comment * Unique node

I would create a "parent" view that shows all nodes the user has commented on and then a "child" view that filters the comments on each node to show the most recent one.

See my detailed answer here to a question about getting the latest node per user.

An alternative is to play around with Views aggregation settings.
> 1 votes

---
Tags: 7, views, comments
---


# Question
Title: Druapl 7 Update displayed price of product when quantity changes
I'm new to drupal. What I want is the price to be updated for an ubercart product when I change the quantity the same way it happens with the attributes on the product page.

So far I have a custom module to edit the type of the edit quantity form when I add a product in my cart. I turned it to a select box and tried to append the class ajax-processed but nothing happens.

# Answer
> 0 votes
Well after some tail chasing I managed to do it. It probably is a bad solution since I had to modify **uc\_product\_module** itself. Here's what I did:

1) Created a custom module that adds two buttons in **hook\_form\_alter**\- and + that will modify the quantity:

```
    $form['decrease'] = array(
        '#name' => 'decrease',
        '#id' => 'decrease-product-qty',
        '#type' => 'button',
        '#value' => t('-'),
        '#prefix' => '<div class="form-item form-item-qty-btn form-type-uc-quantity form-group">',
        '#ajax' => array(
            'wrapper' => 'wrapper',
            'callback' => 'decreaseProductQuantity_form_ajax_callback'
        )
    );

/**
 * AJAX callback function for addToCartFormEditQuantity_form().
 */
function decreaseProductQuantity_form_ajax_callback($form, $form_state)
{
    $nid = $form_state['values']['nid'];
    $node = node_load($nid);

//Get current quantity
$quantity = (int)$form['qty']['#value'];
// Adjust
if ($quantity > 1) {
    $quantity--;
}

$form_state['storage']['quantity'] = $quantity;

// Calculate updated price to be displayed
$displayPrice = uc_currency_format($node->price*$quantity);
// Price textfield id and class
$fieldId = "#total-price-uc-product-" . $nid;
$fieldClass = '.uc-price';

// Update field via command
$commands = array();
$commands[] = ajax_command_invoke('#edit-qty', 'val', array($quantity));
$commands[] = ajax_command_html($fieldClass, $displayPrice);

// Send the command to the page.
$page = array(
    '#type' => 'ajax',
    '#commands' => $commands,
);
return $page;
}

```

2) Saved quantity in **$form\_state\['storage'\]\['quantity'\]** = $quantity; as seen above. In order to keep the value form being erased add use **$form\['after\_build'\]**:

```
//Inside hook_form_alter
$form['#after_build'][] = 'addToCartFormEditQuantity_after_build';

function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    $form_state['storage']['quantity'] = (int)$element['qty']['#value'];
    return $element;
}

```

3) Final step modified **ubercart/uc\_product/uc\_product.module** function **uc\_product\_view\_ajax\_commands**:

```
 * @return
 *   An array of Ajax commands.
 */
function uc_product_view_ajax_commands($form_state, $keys) {
  $commands = array();
  if (variable_get('uc_product_update_node_view', FALSE) && !empty($form_state['storage']['variant'])) {
    $node_div = '.uc-product-' . $form_state['storage']['variant']->nid;
    $build = node_view($form_state['storage']['variant']);
    foreach ($keys as $key) {
      if (isset($build[$key])) {
         //Modify display price to take qantity into consideration
        if ($key === "display_price") {
          $quantity = (int)$form_state['storage']['quantity'];
          $totalPrice = (float)$build[$key]['#value'];
          $totalPrice *= $quantity;

          $build[$key]['#value'] = $totalPrice;
        }
        $id = $node_div . '.' . str_replace('_', '-', $key);
        $commands[] = ajax_command_replace($id, drupal_render($build[$key]));
      }
    }
  }
  return $commands;
}

```

---
Tags: ajax, ubercart
---


title: How to use feeds with entity reference?

text:
# Question
Title: How to use feeds with entity reference?
I have a simple example the uses an entity reference field that references taxonomy terms (e.g. "Arranger"). On import I need feeds to see if the term exists, reference it. If it doesn't exist, create and then reference it:

My CSV:

My Feed Mapping:

It imports everything else but not the entity reference field. It doesn't create the term either.

What do my feed mapping need to look like to allow entity reference to check for and if the term doesn't exist, create it (and then reference it)?

# Answer
Perhaps the Feeds Tamper: String to ID module might in this situation?

> A Feeds \+ Feeds Tamper plugin that resolves strings pulled in from feeds importers and maps them to Drupal entity IDs, so they can be used as entity references.
>
> Adds support for freeform Entityreference linking when using Feeds.
> 5 votes

# Answer
What version of feeds are you using? You mention in one place it's an entity reference and another that it's a taxonomy term.

If it's taxonomy feeds 2.x alpha8 will work, you need to use tax term.

To get entity references working you need to use Entity reference feeds module.

> Provides feeds integration for entityreference for mapping directly to properties of referenced entities.
>
> * Utilizes Entity API to provide mapping targets for entity properties.
> * Will automatically create new referenced entities and update existing ones using a GUID mapping to separate between the two.
> * Set default values for required entity properties and avoid being forced to map them in Feeds
> 0 votes

# Answer
I had a similar problem passing values from a feeds source to Entity reference fields on a node.

I solved my problem by using Views Bulk Operations to manually set the the values for the entity reference fields *after* the feed had created/updated the node.

I appreciate that this isn't an elegant solution but if you only have 3-5 entities that are referenced it will work quickly and it is simple to set up...
> 0 votes

# Answer
Kinda late but you can use **hook\_feeds\_after\_parse** and alter the results from your csv file before importing. In your case, convert the csv-field which I guess is the name of the taxonomy term (the one that you want to map to the entity (taxonomy) reference) into its tid and select **Entity reference by Entity ID** in the Feeds UI **target** list.
> 0 votes

---
Tags: feeds, entities
---


# Question
Title: How can I redirect a form to the home page?
I have below code

```
global $base_url;
$form['submit'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this->t('Submit'),
        '#attributes' => [
            'onclick' => "window.location='" . $base_url . "'",
        ],
    ];

```

But it's not working. It's not redirecting to home page. How can I redirect a form to the home page upon submission?

# Answer
If it's a custom form please include submitForm which is an implementation of FormInterface for processing of submitted data.:

```
use Drupal\Core\Form\FormStateInterface;
...
public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRedirect('<front>'); //This will redirect you to the front page
}

```
> 3 votes

---
Tags: 8, forms
---


title: Webform comfirmation page token

text:
# Question
Title: Webform comfirmation page token
Example I have webform at http://www.example.com/webform. Once I submit the form it will redirect to confirmation page which is http://www.example.com/node/8/done?sid=18&**token**=ggffdgdf7g8df7g89d7fg98df77

May I how to get this token value from database? I had tried md5() for submitted time, but the value is not the same.

# Answer
> 0 votes
I found the answer in the `webform.module` file:

```
/**
 * Return the access token for a submission.
 *
 * @param object $submission
 *   The submission object.
 *
 * @return string
 *   The access token for the submission.
 */
function webform_get_submission_access_token($submission) {
  return md5($submission->submitted . $submission->sid . drupal_get_private_key());
}

```

So it's an MD5 hash of a concatenation of the submission date, submission ID and a random private key, set by the webform module.

---
Tags: 7, webforms
---


title: Where is my stylesheet located?

text:
# Question
Title: Where is my stylesheet located?
I would like to make small css changes such as h1 and various font, background colors and divs etc. I am using Newsflash theme on Drupal 7 and I have searched and searched my folders thus: sites\> all\> themes\> newsflash\> css\> **local.css**

I can probably override things here but I would prefer to go to the source stylesheet if it exists. Does it exist? If not, is **local.css** the right place to write my changes?

# Answer
Go to **/admin/config/development/performance**

Uncheck Aggregate and compress css files

Now with your browser right click and inspect element, hover mouse over the .css file and it will tell you where it is at.

If it's coming from a contrib module, you should add your css on your theme's CSS file (in your case being local.css), as when you update that contrib module, it will lose the changes.

As you can see in my screenshot, that is coming from my theme's homepage.css file.

**PS:** After you're done, remember to turn back on (check-mark) Aggregate and compress css files in Performance.
> 1 votes

---
Tags: theming
---


# Question
Title: What's your trick to document (in the UI?) variables overridden in settings.php?
If you define variable overrides in `settings.php`, there is no visible change to the admin UI. It's easy when overtired (or just inexperienced) to overlook this when changing some config through the UI, and getting an unexpected result.

Have people come up with a trick to document `settings.php` overrides right in the related admin form? I guess I could write a `form_alter` every time I define a settings.php override, but is there an alternative clever that devs are using? (I'm using D7, BTW.)

# Answer
You could implement a hook\_help that displays a message on the page where you would set the variable. Would still need to do it manually per variable though.
> 2 votes

# Answer
As per @Patrick comment, you can apply the patch from #2408549 Drupal issue which will display a message on the top if there are overridden values.

> Each configuration form knows about the configuration keys edited and centralizes an accessor (`$this->config()`) to access them. Thanks to this, we can track if there were any configuration details loaded that may have overrides applied (by loading the editable version as well and comparing the data). That way, we can detect if there are overridden values at least under the same conditions as the admin form was displayed (eg. *static global overrides*). Using that information, we can display a message on top of the form if there is overridden configuration and editing is pointless.

However the patch is for Drupal 8, so either you need upgrade your site to 8.5.x or wait to be ported to Drupal 7.
> 0 votes

---
Tags: configuration
---


title: How to secure session cookies

text:
# Question
Title: How to secure session cookies
I am facing a session cookie hijacking vulnerability please refer the attached

> image. When i put these cookie in another browser which i simply type the domain like http://example.com and add the copy cookie using the extension then simply i change the url to example.com/dashboard then user dashboard automatically open just because of copy cookie all have the same label only value is different.

# Answer
The value of the cookie needs to be kept a secret, otherwise as you point out, someone can 'hijack' the session and perform actions as the original user.

Under normal circumstances an attacker wouldn't be able to get the value of this cookie from your browser, if they can, then they're into your machine, and can probably do what they like. Game over.

That leaves man-in-the-middle attacks as a way to get the value of this cookie, and you avoid those by running the site over HTTPS, so that the value of the cookies is encrypted in transit, and only readable by the client and the server.
> 1 votes

---
Tags: 7, sessions
---


title: Code for module weight does not work

text:
# Question
Title: Code for module weight does not work
I have two modules about login forms. Want to give weight to them , but my code does not work. I put this in template.php, maybe I missed something. I restart mysql, but it does not help.

```
$weight = db_select('system', 's')
      ->fields('s', array('weight'))
      ->condition('name', '[commerce_checkout_redirect]', '=')
      ->execute()
      ->fetchField();

  // Set our module to a weight 1 heavier, so ours moves lower in execution order
 db_update('system')
    ->fields(array('weight' => $weight + 1))
    ->condition('name', '[redirect_after_login]', '=')
    ->execute();

```

# Answer
> 0 votes
Eliminate the square brackets from the query and it should work:

```
$weight = db_select('system', 's')
  ->fields('s', array('weight'))
  ->condition('name', 'commerce_checkout_redirect', '=')
  ->execute()
  ->fetchField();

```

// Set our module to a weight 1 heavier, so ours moves lower in execution order

```
 db_update('system')
    ->fields(array('weight' => $weight + 1))
    ->condition('name', 'redirect_after_login', '=')
    ->execute();

```

---
Tags: 7, forms, commerce
---


title: Previewing updates to published content

text:
# Question
Title: Previewing updates to published content
Is it possible to preview changes made to published content before the content goes live? Or do you always have to unpublish content before editing and then save and preview before publishing?

# Answer
Yes you can Preview your content before Publish the changes to go live and you do not need to unpublish it to see the preview. Do the follwoing steps:

1. Navigate to Admin \> Structure \> Content Type and click Edit in front of your content type.
2. In the submission form settings tab.
3. Locate Preview before submitting and check Required.
4. Save the content type.
5. Navigate to Admin \> Add Content \> \[Your Content Type\].
6. You can see the Preview button listed next to Save node button.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to use last parameter (term) as a filter in a view
I'm using Drupal 7 as a document management system and I've got a taxonomy vocabulary called "Document Tags" with the following structure:

```
Accounting
  Best Practices
  Client 1
  Client 2
HR
  Forms
  Policies
IT
Office Management
   Photos
   Org Charts

```

I created a block view using Views Tree and set up the tree structure that works well so that the categories are nested and expand properly, and are each linked like so:

```
mysite.com/docs/accounting
mysite.com/docs/accounting/best-practices
mysite.com/docs/accounting/client-1
mysite.com/docs/hr
mysite.com/docs/hr/forms

```

My document view uses the contextual filter "Content: Has taxonomy term ID" and then in the filter as shown. When I click on a first level category (Accounting, HR, IT, Office Management, etc.) it works great but anything underneath only displays the documents tagged with the top level, so it's evidently only using the first parameter in the display.

Is there a way to have the filter always pull the last URL parameter (e.g. "forms" in the URL mysite.com/docs/hr/forms)?

UPDATED - here are screenshots of the two pages and their results: http://tentenstudios.com/storage/page\_1\_filter.png http://tentenstudios.com/storage/page\_1\_results.png http://tentenstudios.com/storage/page\_2\_filter.png http://tentenstudios.com/storage/page\_2\_results.png

# Answer
> 0 votes
Yes, you can add a separate block with the same settings and in the contextual filter get form from the url.

Add the blocks in the same region and in the visibility settings select Only the listed pages and add docs/\*/\* for child terms and to the other block add docs/\* for the parent terms.

**UPDATED:**

If you have a Taxonomy type page view then you can do the following thing.

Create tow pages with path as docs/\* for parent terms and docs/*/* for child terms i.e. form.

In the contextual filter add term id and select This Page override. and check Provide default value. In the Type drop-down select Raw value from URL and then from Path select 3 for docs/%/% path and 2 for docs/% path.

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


# Question
Title: Drupal 7 commerce stripe stripe-php library refuse to load
I'm trying to implement commerce on my D7 site and after installing packs of modules I've installed commerce\_stripe module to use Stripe payments.

After I created all necessary things(stripe account, products, stripe api keys, latest stripe-php library in sites/all/libraries/) I'm trying to proceed payment and see an error:

Error making the payment. Please contact shop admin to proceed.

Went to reports -\> recent log messages and see:

Failure to load Stripe API PHP Client Library.

Hours of googling and I found few ways how to handle it. Updated Libraries module to the latest version, instead of 7.x-3.0-alpha installed 7.x-3.x-dev, clear cache, run cron. Unfortunately, nothing happens.

trying to locate an error I've found function that trying to load stripe php library. It's `commerce_stripe_load_library()` in commerce\_stripe.module file. Error throws in the beginning of this function:

```
$library = libraries_load('stripe-php');
  if (!$library || empty($library['loaded'])) {
    watchdog('commerce_stripe', 'Failure to load Stripe API PHP Client Library.', array(), WATCHDOG_CRITICAL);
    return FALSE;
  }

```

Trying to dpm result of `libraries_load()` function. and first condition `!$library` is passed successfully. But `$library['loaded']` is `FALSE`.

Any ideas why? Any help appreciated.

# Answer
> 1 votes
Finally found the solution.

There is wrong information about installing library on drupal dot org.

It says

> ## Installation
>
> Install and activate Commerce Stripe and Libraries modules.
>
> Download the latest Stripe PHP release from GitHub.
>
> Extract the contents of the archive into the directory /sites/all/libraries/stripe-php
>
> Create an account at Stripe.com, and insert your API keys from the Stripe
>
> Dashboard into the Commerce Stripe payment method settings at admin/commerce/config/payment-methods.

So the thing is that this is the wrong information. If you go to `commerce_stripe.module` and find hook `commerce_stripe_libraries_info()` in `'version arguments'` you will see that it tries to locate in file VERSION this pattern:

`'pattern' => '/(3.\d+(\.\d+)?)/',`

It means that you need version 3 of stripe-php library(depends on your commerce\_stripe module version). So fix for this is to use correct version of stripe-php library

# UPDATE

You can check necessary library's status by executing `drush library-list`

you will see something like this:

```
Name                   Status        Version  Variants          Dependencies  Provider
stripe-php             Not detected           -                 -             Commerce Stripe

```

if stripe-php library's status is not detected, then you user wrong version or place the library to the wrong place.

---
Tags: 7, commerce
---


# Question
Title: How to see if there is a hidden admin role with an account that has no admin access?
I'm completely new to Drupal. A friend has asked me to help out with his Drupal 7 site. He created an account for me - but I'm thinking that the role given to my user account isn't really an admin account. When logging in, I don't see any way to administer modules, user permissions, etc.

I'm thinking that the admin role is hidden. For a person who is just now learning Drupal, what would be the easiest way to see if there is a hidden admin role?

# Answer
> ... For a person who is just now learning Drupal, what would be the easiest way to see if their is a hidden admin role?

***`Talk to your friend`***, and perform these steps:

* **Step 1**: ask for a screenprint (created by your friend, while your friend is logged in) of the list of roles shown via relative path `admin/people/permissions/roles` ... That will show you all "roles" defined in your site. Typically you'll have at least these 3 hardcoded (= delivered with Drupal) roles:

+ anonymous user (in the Drupal database this corresponds to `role id = 1`).
    + authenticated user (in the Drupal database this corresponds to `role id = 2`).
    + administrator (in the Drupal database this corresponds to `role id = 3`).
* **Step 2**: find out what the "user id" is for the user that you received, which you'll typically see (as part of the relative path) when you try to edit your own profile.
* **Step 3**: ask for a screenprint (created by your friend, while your friend is logged in) of the granted roles shown via relative path `user/uid/edit` (whereas `uid` in it corresponds to your own user id) ... That will show you all "roles" you have been granted. Probably the role "administrator" will not have been granted.
> 1 votes

# Answer
There are no hidden roles. You should have your user account login, and you should also have the user 1 (root user) login. That is the god user account.
> 0 votes

---
Tags: users
---


# Question
Title: PHP Fatal error: Class 'Drupal\Core\DrupalKernel' not found
I have installed the EntityPrint module in drupal 8 for the pdf conversion.

Followed below procedure:

> `curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer composer config repositories.drupal composer https://packages.drupal.org/8`
>
> Run: `composer require "drupal/entity_print 2.x"` in the site `docroot/`.

1. https://packagist.org/packages/mikehaertl/phpwkhtmltopdf
2. https://packagist.org/packages/dompdf/dompdf
3. https://packagist.org/packages/tecnickcom/tcpdf

I have installed the above packages using, as the entity print module insisted to install it in drupal page.

Once the installation was done, drupal site was crashed, while checking the error log, I got the following:

> \[error\] FastCGI sent in stderr: "PHP message: PHP Fatal error: Class 'Drupal\Core\DrupalKernel' not found in /var/www/html/drupal/index.php on line 16" while reading response header from upstream

I have uninstalled the packages but unable to disable entity print. Since my `drush` command results in error.

Can anyone please help me to find out?

# Answer
> 5 votes
Try the following:

* Check if `autoload.php` file exists and it includes the right path to your `vendor/` folder.
* Clear any external cache services if in use (e.g. *Memcached* or *Redis*).
* If you're using PHP 5.x, you should use PHP 7.x instead.

---

To rebuild your site from scratch based on your `composer.json` file, try the following steps:

1. Backup and delete the `/core` and `/vendor` directories completely.
2. Delete the `composer.lock` file.
3. Run: `composer install`.
4. Run: `composer update`.

Source: D8 conflict resolution.

# Answer
> 3 votes
I am not sure if you installed your site using composer but I suspect Symphony is missing or your vendor directory is missing. Check if you have drupal inside composer.json file. If you do see Drupal I would recommend the following:

1. Make a backup of your entire code just in case you need to go back. (Hopefull you are using Git so you don't need to do this)
2. In the root of your project remove the vendor directory
3. run `composer install`
4. run `drush cr`

It should download Drupal and all the symphony components.

---
Tags: 8, installation, composer
---


# Question
Title: How to get drush to work with xdebug -- may have recently broken
I've been using drush with xdebug for years. It looks like it broke in the last two weeks, possibly due to modifications made to the core "drush" script (Split 'drush' script into finder, wrapper and launcher stages.). It now dispatches via "pcntl\_exec" on Ubuntu, and xdebug never gets control back thereafter.

I've tried reverting drush to the previous commit ("8ab7ad9... Make uli test more resiliant vis-a-vis html tags that may be injected into log messages."), which fixes the xdebug problem, but does not appear to be compatible with RC1 :-(. So I strongly suspect the addition of pcntl\_exec.

Anyone know how to get around this, or do I need to log an issue against drush on their github site?

# Answer
The former drush script is still available as `drush.launcher`. I would recommend making this your entrypoint when using Drush with xdebug, and omit the drush "finder" script (called simply "drush") altogether.

If this does not work for you, you should make a report in the Drush issue queue on GitHub.
> 7 votes

# Answer
Another option here is to allow a higher number of concurrent debug sessions. Using PHPStorm, where I encountered this same problem, the default is to only allow one connection. If you check in **Settings -\> Languages & Frameworks -\> PHP -\> Debug** you will find a **Max. simultaneous connections setting**. Bumping this to 2 or higher will allow the spawned processes to connect with XDebug back to PHPStorm and continue on.
> 1 votes

# Answer
I use xdebug with vim using a plugin called vdebug. When debugging drush commands, it would break prematurely in `~/.composer/vendor/drush/drush/drush`. To allow xdebug to continue processing when drush executes another script try hitting `F7` then `F5` in *very* quick succession.

For more details see the discussion here: https://github.com/joonty/vdebug/issues/97#issuecomment-334481429
> 0 votes

---
Tags: drush, 8, debugging
---


# Question
Title: Content Moderation: how to make a button to move between states?
I want to allow authenticated users to fill out a node (**Draft**) and then, when they are ready, submit the node (to give it the **Submitted** state). An admin will later decide whether or not to publish the node.

I'm experimenting with the improvements to the Content Moderation module on Drupal 8.4-rc2 (new UI is in the 8.4 series, so 8.3 and before will look different).

I have the following workflow states defined:

* Draft
* Submitted
* Published

There is a *transition* called **Submit** to move from the **Draft** state to the **Submitted** state. Authenticated users have permission to use this transition.

The problem is that the core UI for this looks very complicated.

This is a node edit page:

And this is a node view page:

**I want to hide this moderation UI and instead provide users with a single button, "Submit for approval."**

I hid the moderation and revision UI from auth users (only admin have permission to edit workflows) like this:

```
function mymodule_form_content_moderation_entity_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['#access'] = FALSE;
  }
}

function mymodule_form_node_mycontenttype_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['revision_information']['#access'] = FALSE;
    $form['moderation_state']['#access'] = FALSE;
  }
}

function mymodule_form_node_mycontenttype_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['revision_information']['#access'] = FALSE;
    $form['moderation_state']['#access'] = FALSE;
  }
}

```

So this cleans up the UI and hides all the Content Moderation options.

But how do I create a button to move from one state to another? Specifically, I want the bottom of the form to look like this:

* Save button (saves the node in the same (**Draft**) workflow state)
* New button that saves the node and activates the transition to the **Submitted** state

This is basically the same thing as what core does when it provides an option to **Save as published** and a second option to **Save as unpublished**-- I just want to do this with my workflow states.

# Answer
> 1 votes
I think you should be able to do something like this. (But I did not test).

The first code block adds an additional submit button and gives it a custom submit handler. (Button specific submit callbacks should run before form submit callbacks.)

```
function mymodule_form_TYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Add second submit button (Also check if user can see this).
  $form['actions']['submit_publish'] = [
    '#type' => 'submit',
    '#value' => t('Submit for approval'),
    '#submit' => ['mymodule_submit_callback'],
  ];
}

```

And the submit callback, which simply sets the new value for the moderation state.

```
/**
 * Submit callback to submit for approval
 */
function mymodule_submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'MODERATION STATE ID');
}

```

# Answer
> 1 votes
Based on the code from Neograph734, this is the code I actually used (tested and working):

```
function MYMODULE_form_node_CONTENTTYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array_merge($form['actions']['submit']['#submit'], array('MYMODULE_draft2submit_callback')),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}

```

For more info, see this issue.

---
Tags: 8, workflows
---


title: Render a form from an existing module

text:
# Question
Title: Render a form from an existing module
We are just trying to gain a deeper understanding of Drupal forms and how to manipulate and render them as needed.

We have a module installed which allows uses to edit and create content through a form. The module renders the form on its own edit/create page. We would like to render the edit/create forms on a different page with other content.

Below are a few functions which we believe render the forms. (if not which function should we be looking for??)

```
/**
 * Page callback for creating a customer profile of a given type.
 */
function commerce_addressbook_profile_create($account, $profile_type) {
  // Add the breadcrumb for the form's location.
  commerce_addressbook_set_breadcrumb($account, $profile_type);

  $profile = commerce_customer_profile_new($profile_type, $account->uid);
  // The submit handler needs an indication that the profile was just added.
  // The regular is_new property gets unset after save is complete.
  $profile->_is_new = TRUE;
  module_load_include('inc', 'commerce_customer', 'includes/commerce_customer_profile.forms');
  return drupal_get_form('commerce_addressbook_customer_profile_form', $profile);
}

/**
 * Page callback for editing a customer profile.
 */
function commerce_addressbook_profile_options_edit($account, $customer_profile) {
  // Add the breadcrumb for the form's location.
  commerce_addressbook_set_breadcrumb($account, $customer_profile->type);

  // If the profile is referenced by an order, make sure it gets duplicated.
  $profile = clone($customer_profile);
  if (!commerce_customer_profile_can_delete($customer_profile)) {
    $profile->previous_id = $profile->profile_id;
    unset($profile->profile_id);
    unset($profile->revision_id);
    $profile->is_new = TRUE;
  }
  module_load_include('inc', 'commerce_customer', 'includes/commerce_customer_profile.forms');
  return drupal_get_form('commerce_addressbook_customer_profile_form', $profile);
}

```

What is the process for calling these functions (if they are the ones we are looking for) into a TPL page?

---

---

---

**EASY TO READ COMMENTS:** I have added the follow to template.php within my theme directory

```
function THEME_preprocess_page(&$variables){
    module_load_include('inc', 'commerce_addressbook', 'includes/commerce_addressbook.user');
    $variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);
}

```

I have also included the following with a page tpl file.

```
<?php print render($profile_form); ?>

```

This results in the page returning a 500 error. (commenting out the variables line allows the page to load.)

# Answer
You don't want to be putting that much PHP code into a tpl template file. Your menu item should have two parameters (user account, and profile type) and the page callback is specified as the desired function.

If you are doing this another way, you still need the user object and customer profile. In a preprocess function or in a custom page callback, you can create the form as a variable:

### template.php:

```
// you can load a user account in various ways, ill assume this is behind a user path
$account = menu_get_object('user');
// you will need to verify this is the right function to use.
$customer_profile = commerce_customer_profile_load(profile_id_here);

$variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);

```

### in your tpl file:

```
<?php print render($profile_form); ?>

```

I am not familiar with the commerce\_addressbook module, but there is a chance you'll need to include the file that defines those functions too, especially if they do not live in a .module file but live in a .inc file.

In which case, you'd need:

```
module_load_include('inc', 'commerce_addressbook', 'filepath/filename');
$variables['profile_form'] = commerce_addressbook_profile_options_edit($account, $customer_profile);

```
> 1 votes

---
Tags: 7, theming, forms
---


# Question
Title: arrange view to show 3 x 3 grid of nodes
How would i get Drupal to show a 3x3 grid of nodes of a certain content type.

I've tried using both Format:Grid and Format:Table. Also I used Show: Fields and Show: Teasers but it doesn't work out the way I want.

I am wondering if it's best to use 2 separate blocks of 3 nodes with an offset for the second block so that the 1st block shows nodes 1,2,3 and the 2nd block shows 4,5,6.

This is all related to 1 single content type with fields which include. 1 Image, and 1 URL.

# Answer
> 3 votes
Using format and pager settings this should be possible.

**Add Format type of Grid**

**Set the number of columns under the Format settings to "3"**

**Set page to only show 9 items**

Set the filter to only show nodes of a specific content type:

Now all you need to do is set the view fields, filter, sort, and other options to your liking. Hope this helps!

---
Tags: views, nodes, entities, blocks, theming
---


# Question
Title: Drupal 7 Get field value by machine name and pass to javascript
I have tried to do this a couple of different ways, but I will just include the latest.

My task is to build a module that will get the STRING value of a taxonomy term by the machine name of the field when the page is rendered, and pass that STRING value to a javascript function to output data in a block.

Most recently, I have tried adding the code to the template.php file in the preprocess\_html, page, node and process\_html:

\*The field is called 'field\_test'

```
global $nid;
$node = node_load('12');
$test = $node->field_test['und'][0]['value'];
drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');

```

Error in processes was a call to undefined index. Error in page.tpl was a call to non object.

I also tried field\_get\_items:

```
$items = field_get_items('node', $node, 'field_test');
$first_item = array_shift($items);
$test = $first_item['value'];

```

In the node.tpl file, I tried adding this code:

```
<?php
  $test = $node->field_test['und'][0]['value'];
  drupal_add_js(array('mymodule' => array('test' => $test)), 'setting');
?>

```

No errors, but Drupal.settings.test returns undefined in the browser console.

I'll admit I am still new to the Drupal API. In addition to the **correct code,** I may also lack an understanding of the order in which Drupal components are loaded, and specifically **where the code should be placed**.

I would really appreciate any help you can provide.

# Answer
It should be `Drupal.settings.mymodule.test` not `Drupal.settings.test`. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try `$node = menu_get_object('node');`.

Example:

```
if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

```

In your console (like Google Chrome) you can type `Drupal.settings` to see the entire object, and you should see `mymodule` as a part of it. Within that you will find test with the term name as a value.
> 2 votes

---
Tags: nodes, entities, javascript, hooks
---


# Question
Title: How to loop through a dynamic taxonomy vocabulary and if term is chosen, do an action?
My problem is as follows:

* I have a taxonomy vocabulary with terms, which are changing from time to time.
* I have two node types --\> **type 1** and **type 2**
* **Type 1** has a taxonomy term reference field
* **Type 2** has an entity reference field which can be prepopulated with the module "entity reference prepopulate"

If I create a new node of node type *type 1* then a rule should check which terms are selected and create a new node of *type 2* for each selected term automatically.

The entity reference field of the new *type 2* node should be prepopulated with a reference back to the original *type 1* node.

Because the terms of the vocabulary are changing, the check up by the rule should be IMHO dynamic.

*Dummy-Code:*

**If** a new node of node *type 1* is saved,**then** check which taxonomy terms are selected.

**for each** selected term:

* create a new node of *type 2*
* and prepopulate the entity reference field of node *type 2* with the value of node *type 1*.

I tried it with the Conditional Rules module, but there seems no for..each control loop available.

How can I solve my problem?

# Answer
> **If** a new node of node *type 1* is saved,

= Rules Event: After saving content, of type "type 1".

> **then** check which taxonomy terms are selected.

= Rules Action: Create a Rules loop, which iterates over each of the selected taxonomy terms, assume you use a name for each list item like "`selected_term`".

> **for each** selected term:

= Rules Action (which is part of the loop), in which you perform a "Rules Component", and which uses as parameter the "`selected_term`".

> * create a new node of *type 2*

= 1st Rules Action performed as part of the Rules Component, which is to "Create an entity" (a node of "type 2").

> * and prepopulate the entity reference field of node *type 2* with the value of node *type 1*.

= 2nd Rules Action performed as part of the Rules Component, which is to "set a data value", for the entity reference field, as part of the entity (node) that got created in the previous Rules Action, and followed by a Rules Action to "save the entity".

Refer to the List and loops video for more details about processing lists and loops via Rules.

**Note**: no need for the Conditional Rules module ...
> 1 votes

---
Tags: 7, nodes, taxonomy-terms, rules
---


# Question
Title: overide default text lenth when field is defined
I can set the size of a text field using the manage filed forms. But I want to do this when the module creats the field. I need the correct setting name and so far I cant google up ant thing that works. Below is the code i'm using to create my fields. I would appreciate any help.

```
function _bigimage_installed_instances() {
$t = get_t();
return array(

        'bigimage_image' => array(
        'field_name' => 'bigimage_image',
        'label' => $t('Small Image Overview of the Big Image'),
        'settings' => array('file_directory' => 'bigimage/[current-user:url:path]'),
        'widget' => array(
            'type' => 'image'
        ),
        'display' => array(
            'example_node_list' => array(
                'label' => $t('Small Image overview of the bigimage'),
                'type' => 'image'
            )
        )
    ),
        'bigimage_zif' => array(
        'field_name' => 'bigimage_zif',
        'type' => 'file',
        'label' => $t('bigimage ZIF data'),
        'settings' => array('file_extensions' => 'zif zpp', 'file_directory' => 'bigimage/[current-user:url:path]'),
        'widget' => array(
            'type' => 'file'

        ),
        'display' => array(
            'example_node_list' => array(
                'label' => $t('ZIF Data of the bigimage'),
                'type' => 'file'
            )
        )
    ),
     'bigimage_vars' => array(
        'field_name' => 'bigimage_vars',
        'label' => $t('Zoomify Viewer Commands'),
        'settings' => array ('#maxlength' => '125' ),
        'widget' => array(
            'type' => 'text'
        ),
        'display' => array(
            'example_node_list' => array(
                'label' => $t('Zoomify viewer Commands'),
                'type' => 'text'
            )
        )
    )

);

```

}

# Answer
I finally deduced the answer. The size setting only seems to work in the widget. the max\_length setting only in the field definition. Yep I'm that dense.
> 0 votes

---
Tags: entities
---


# Question
Title: How to set default value for textfield programmatically in drupal 7?
I need a form\_alter code or something that I could use to set my field value. I'm getting the value from the parameter and I've tried a lot of ways but nothing works for me. This is the list of codes I've tried on my custom module:

```
function custommodule_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom_package') {
      $default = $_GET['field_product_add_ons'];
      $form["field_add_on_nids"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE]['#default_value'] = $default;

  }

  if($form_id == 'custom_package') {
      $default = $_GET['field_product_add_ons'];
      $form["field_add_on_nids"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['value']['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE][0]['#default_value'] = $default;
      $form['field_add_on_nids'][LANGUAGE_NONE]['#default_value'] = $default;

  }
}

```

I think the code will be simple but the field is still blank. My field is just a single text field.

Thank you in advance for your help!

# Answer
Is your custom module called `custommodule_node` or just `custommodule`? Assuming it's `custommodule`, your function should look like below. You use `->` because node is an object.

```
function custommodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'custom_package') {
      $default = $_GET['field_product_add_ons'];
      $form->field_add_on_nids[LANGUAGE_NONE][0]['value'] = $default;
  }
}

```

also, there is no `if ($form['#node']->type == 'custom_package')`

Use `if ($form_id == 'custom_package')` to match $form\_id.
> 0 votes

# Answer
Try

```
 $form['field_add_on_nids']['und']['#default_value'] = $default;

```

Thanks
> 0 votes

# Answer
You can try either of these way any one will work

**Option 1:**

```
$form['field_name']['und']['#default_value'][0] = $default_value;

```

**Option 2:**

```
$form['field_name']['und']['#default_value'] = $default_value;

```

**option 3 :**

```
$form['field_name']['und'][0]['value']['#default_value']= $default_value;

```
> 0 votes

# Answer
I would try the following, as it works for me:

```
$form['field_myfield'][LANGUAGE_NONE]['#default_value'] = "value";

```

I believe that using LANGUAGE\_NONE is considered a better practice than 'und'.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Search API: Custom processor not hitting addFieldValues
I'm creating a custom module for adding a processor that adds relative entities. Here's my code for **getPropertyDefinition**.

```
public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
$properties = [];
if ($datasource) {
  $entity_type = \Drupal::service('entity_type.manager')->getStorage('group_type')->load(key($datasource->getBundles()));
  $entity_type_ids = [];
  $plugin_manager = \Drupal::service('plugin.manager.group_content_enabler')->getInstalled();
  foreach($plugin_manager->getInstanceIds() as $instance_id) {
    array_push($entity_type_ids, $plugin_manager->get($instance_id)->getPluginDefinition()['entity_type_id']);
  }
  foreach($entity_type_ids as $entity_type_id) {
    $definition = [
      'label' => $this->t(ucwords($entity_type_id)),
      'description' => $this->t('Entity reference of ' . $entity_type_id),
      'type' => 'entity:' . $entity_type_id,
      'processor_id' => $this->getPluginId(),
    ];
    $properties[$entity_type_id] = new EntityProcessorProperty($definition);
    $properties[$entity_type_id]->setEntityTypeId($entity_type_id);
  }
}
return $properties;
}

```

And, after adding relative fields to index, I think it should hit **addFieldValues** method but it doesn't. For test purpose, I only put die in the method.

```
public function addFieldValues(ItemInterface $item) {die;}

```

But, when I copied code from addURI's **getPropertyDefinition** into my **getPropertyDefinition**, it hits **addFieldValues** when indexing. Is there anything wrong in my **getPropertyDefinition**?

# Answer
> 2 votes
**EDIT** I created an issue on the search API issue queue Custom Entity Reference processor does not trigger addFieldValues()\* and the maintainer has pointed to an existing issue that it was duplicating. So there is an existing issue that is being worked on here - #2910638: Entity reference via processor sample code not working Jump on there and help test :)

* I couldn't post the first link because of a lack of reputation and I figured the link to the issue where work is being carried out is more useful :D

I'm encountering the same behaviour and have an idea why this occurs but not an answer on how to fix it (I can't post a comment so needed to add this as an answer).

`\Drupal\search_api\Item\Item::getFields` is responsible for calling the instances' implementation of `addFieldValues`. Within that function there is this code block:

```
   foreach ($this->index->getFieldsByDatasource($datasource_id) as $field_id => $field) {
      // Don't overwrite fields that were previously set.
      if (empty($this->fields[$field_id])) {
        $this->fields[$field_id] = clone $field;

        $field_data_type = $this->fields[$field_id]->getType();
        // If the field data type is in the fallback mapping list, then use
        // the fallback type as field type.
        if (isset($data_type_fallback_mapping[$field_data_type])) {
          $this->fields[$field_id]->setType($data_type_fallback_mapping[$field_data_type]);
        }

        $property = $field->getDataDefinition();
        if ($property instanceof ProcessorPropertyInterface) {
          $processors_with_fields[$property->getProcessorId()] = TRUE;
        }
        elseif ($datasource_id) {
          $fields_by_property_path[$field->getPropertyPath()][] = $this->fields[$field_id];
        }
      }
    }
    try {
      if ($fields_by_property_path) {
        \Drupal::getContainer()
          ->get('search_api.fields_helper')
          ->extractFields($this->getOriginalObject(), $fields_by_property_path, $this->getLanguage());
      }
      if ($processors_with_fields) {
        $processors = $this->index->getProcessorsByStage(ProcessorInterface::STAGE_ADD_PROPERTIES);
        foreach ($processors as $processor_id => $processor) {
          if (isset($processors_with_fields[$processor_id])) {
            $processor->addFieldValues($this);
          }
        }
      }
    }

```

If the value of `$property` is not an instanceof `ProcessorPropertyInterface` then `addFieldValues()` is never called.

What I'm not sure of is what is the best path to take to begin solving this.

* Should I add a new custom processor that only acts on this custom field and use `addFieldValues()` there? (I've yet to test this) OR
* Is it an issue that `addFieldValues()` is never called and the Search API module needs to be updated so that it is?

I've tried implementing the other functions from the parent class (`\Drupal\search_api\Processor\ProcessorPluginBase`) ie `alterIndexedItems` but none of those are triggered.

I came across the same approach that you're using here on d.o - Adding an entity reference via a processor so it may be the docs need to be updated.

---
Tags: search
---


title: Render JavaScript in a block

text:
# Question
Title: Render JavaScript in a block
The relevant items of the directory structure are the following:

* /template.php
* /js/custom.js

The following code is located in `template.php`. On page render, this function gets the value of a taxonomy term field with machine name `field_test` and passes it to a JavaScript function.

```
function bartikCustom_process_page(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
     _color_page_alter($variables);
  }
  if ($node = menu_get_object('node')) {
    $tid = $node->field_test['und'][0]['tid'];
    $term = taxonomy_term_load($tid);
    drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
  }

```

In `custom.js`, the JavaScript function manipulates the variable to obtain further data.

```
(function ($) {
Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
        var testMe = Drupal.settings.mymodule.test;
        // Append the 'test' var to a Google Charts Service query string as a SELECT statement to call back a chart with controller
    }
});

```

How can I print out the resultant Google Chart into a block? Do I need to use the `#attach` function?

I'm still new to Drupal APIs so any help is much appreciated.

# Answer
For this instead of rendering it to a js you can create a custom block. If you are using views create a block view with type content. Add views conditional module for filteration. Follow these steps.

1. Create a block from view with Show content.
2. Add field\_test in the Fields.
3. Adds Views condition field.
4. From If this field dropdown select the field you want to check.
5. Enter the value in This value field i.e. (Term id for Cheese or Apple).
6. And then in Then Output this textarea add "Your favorite food is Cheese which is a Dairy".
7. And then in Otherwise, Output this textarea add "Your favorite food is Apple which is a Fruit".
8. Save the view and your place the created block in any region.
> 0 votes

---
Tags: theming, nodes, javascript, blocks, hooks
---


# Question
Title: How to send a push notification with Rules to specified user by grabbing UID from content field?
I want to send a push notification to a single Drupal, which, seems simple given the below screen shot.

This works great when the user is always the same (I simply type in the UID). However, in my case, the UID is always different. Is it possible for me to grab the UID from a content field (e.g. from Content Type 'Friends', I have a field named `field_target_user`) using a token, and have it populate in my Rules' User Identifier field?

# Answer
Use the button that says ***`Switch to direct input mode`***. And verify if you can use any of the tokens shown there as the *identifier* you're looking for.

If no appropriate token is shown, then try to add an appropriate Rules Condition with `Entity has field`, to make the field you need available for further processing in the rule. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "*The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')*". For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

However, as per your "... content field ... from Content Type 'friends'\*" (as in your question), the above may not be sufficient yet (= the appropriate token is still not shown). I.e from the label(s) it sounds that this could well be a multi value field (of type entity reference?). In that case you first need to add a "Rules loop" to iterate of the list of friends, so that inside that loop you can use a token related to the `uid` of the current list item being processed.

The above are just 3 of the typical/possible approaches to get access in a custom rule to some token you're looking for. There are others though, such as:

* using Rules Action to "Fetch entity by ID", or
* getting the Views Rules module involved,
* etc.

**Note**: In case you're using the Push Notifications module, you may want to have a look at its community documentation related to Rules integration, especially this screenprint on that page seems pretty similar to what you're looking for (if you can reference the `node:author` token, it should also be possible to reference some other field of a node).
> 0 votes

---
Tags: 7, rules, notifications
---


# Question
Title: Render parent paragraph depending on dynamic data from child paragraph (e.g. db query)
Here's my problem (D8):

There's a content type concert. In a paragraph type concerts\_list a list of upcoming concerts (concert nodes) is displayed. This concerts\_list paragraph is referenced in field\_right\_column of another paragraph of type 2\_columns.

What I want to do is: Hide the right column if there are no upcoming concerts in the concerts paragraph.

My issue is that the outer (parent) paragraph is rendered and preprocessed before the child paragraph and the resulting render array only includes #theme, #paragraph and #cache but not the actual render array used to render the paragraph.

How can I access a child paragraph's render array from the parent? I don't want/need to access the child paragraph's fields since the concerts are no field because the data is simply added to the build array in hook\_entity\_type view.

When rendering the 2\_columns paragraph I need to know whether or not there are any upcoming concerts and if not I'd like to hide the right column.

Is there a better approach to achieving a similar result?

I'd appreciate any hints/tips/...!

Here's the relevant code:

```
function MODULE_paragraph_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $bundle = $entity->bundle();
  if ($bundle === 'concerts_list') {
    // Get the max number of concerts we want to display.
    $max_concerts = (int)$entity->get('field_count')->value;
    $build['concerts'] = MODULE_get_upcoming_concersts($max_concerts, 'teaser');
  }
  elseif ($bundle === '2_columns') {
    // Determine whether to show one or 2 columns depending on the number of
    // upcoming concerts in 'concerts_list'.
    // It would also be ok to do that in twig but I'd need to get the data
    // somewhere.
  }
}

function MODULE_get_upcoming_concerts($limit = 0, $view_mode = 'default') {
  $entity_type_manager = \Drupal::entityTypeManager();
  $query = $entity_type_manager
    ->getStorage('node')
    ->getQuery()
    ->condition('type', 'concert')
    ->condition('field_date', strtotime('midnight'), '>')
    ->sort('field_date', 'ASC');

  if ($limit) {
    $query->range(0, $limit);
  }

  $nids = $query->execute();
  if (count($nids) < 1) {
    return [];
  }
  $nodes = $entity_type_manager->getStorage('node')->loadMultiple($nids);
  return $entity_type_manager->getViewBuilder('node')->viewMultiple($nodes, $view_mode);
}

```

# Answer
> 0 votes
I don't understand the code and what you are trying to do, so I answer the question in the title and the last part of the question:

> How can i access a child paragraph's render array from the parent? Or is there a better approach to achieving a similar result?

Don't use the render array, use the parent paragraph entity to get the child paragraphs and their field values:

```
use Drupal\Core\Cache\Cache;

/**
 * Implements hook_ENTITY_TYPE_view() for paragraph entities.
 */
function MODULE_paragraph_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $bundle = $entity->bundle();
  // check if this is the parent paragraph
  if ($bundle === 'gigs_teaser') {
    foreach ($entity->field_child_paragraphs->referencedEntities() as $paragraph) {
      // get a field value from a child paragraph
      $field_value = $paragraph->field_example->value;
      $build['#cache']['tags'] = Cache::mergeTags($build['#cache']['tags'], $paragraph->getCacheTags());
      ...
    }
  }
}

```

---

**Node query**

I think I understand now the issue more. You ask probably the wrong question, because the "dynamic data from the child paragraph" is in reality not data from this paragraph, but from a node entity query. If you want to access this query data from two places in code, then put the code in a function and store the result in a static variable so that it is not calculated twice.

---
Tags: theming, 8, hooks, paragraphs
---


# Question
Title: Flags: flagging unflagging rules, how to check if an user has already flagged a node?
I'm using Drupal 7 and I created 3 flags for article content type; these flags are global flags: `bad`, `nice` and `cool`. Now, I want create a rule in order to check if an user has already flagged an article.

For example: a user flags article as `bad`. Now the user wants to flag the same article as `nice`. Theoretically, the user must unflag `bad` and flag `nice`.

I want a rule that check if the user has already flagged a node; if yes, the previous flag must unflagged.

In Rules there are Rules Conditions that can execute php code, but flag api, has a `$flag-is_flagged` function that checks if an user flagged a node only if the flag is non-global flag.

Any idea?

# Answer
> 1 votes
What you're trying to achieve (= allow users to flag nodes by one out of 3 flags), is by design NOT something you can implement by using a **global** flag. Because global flags cannot be used by individual users. So I suggest you rethink/rework the design of those flags, so that they are NOT defined as global anymore. After you do so, you should be able to implement what you're trying to do, by using the Rules module, and with no need for PHP code. Read on for more details on how to do so.

Have a look at this rule (in Rules export format):

```
{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "IF" : [
      { "flag_flagged_node" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ]
        }
      }
    ],
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "this_is_bad",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

```

Some details about the above rule:

* Rules Event: A node has been flagged, under "Nice".
* Rules Condition: The flagged node is flagged with flag "Bad", by the flagging user.
* Rules Action: Unflag the flagged node, for flag "Bad", by the flagging user.

You should be able to import the above rule in your own site, provided you first adapt the machine names of both flags (`this_is_nice` and `this_is_bad`) to fit your own machine names.

### If nice is not sufficient (and it should be cool also ...)

If you want to implement similar logic for the "cool" flag, you can rework the Rules Condition and Rules Action in the sample rule above towards a Rules Component (say you name it "*Disallow BAD flag*"), and remove them from the rule shown above. Then clone this Rules Component towards a similar one for the "Cool" flag (say you name it "*Disallow COOL flag*"), in which you change all "bad" to "cool". And finally invoke both Rules Components via an extra Rules Action (1 for each) in the sample rule above.

Or you can use the Conditional Rules module to consolidate both rules in a single rule. Here is a variation of the above rule (using flags with machine names `this_is_nice`, `this_is_bad` and `this_is_cool`), to illustrate how such rule would look like:

```
{ "rules_unflag_related_flags" : {
    "LABEL" : "Unflag related flags",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "flag" ],
    "ON" : { "flag_flagged_this_is_nice" : [] },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "flag_flagged_node" : {
                "flag" : "this_is_bad",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_bad",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          },
          {
            "ELSE IF" : { "flag_flagged_node" : {
                "flag" : "this_is_cool",
                "node" : [ "flagged-node" ],
                "flagging_user" : [ "flagging_user" ]
              }
            },
            "DO" : [
              { "flag_unflagnode" : {
                  "flag" : "this_is_cool",
                  "node" : [ "flagged-node" ],
                  "flagging_user" : [ "flagging_user" ],
                  "permission_check" : "1"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

```

***Easy, no?***

---
Tags: rules, flags
---


# Question
Title: How to add back to top using drupal behaviors?
I have added the following Drupal behaviors below to my main.js file which is already included in my theme and renders on the page with the correct main.js file. The purpose of this behavior is to scroll the user to the top of the page and it is not working. I cannot even get it to log an alert('clicked'). Need help figure out what i am missing.

main.js

```
Drupal.behaviors.scrollToTop = {
  attach: function (context, setting) {
    $('#back-to-top', context).on('click', function(){
        alert('clicked'); //does not work
        $('body,html').animate({scrollTop : 0}, 500); //does not work
    });
  }
};

```

html

```
<body>
  <!-- assume this is at the bottom and there is more in the body -->
  <a id="back-to-top" href="javascript:void(0)";><div>div is used to insert up arrow</div></a>
</body>

```

# Answer
Try wrapping it:

```
(function ($) {
    Drupal.behaviors.scrollToTop = {
      attach: function (context, setting) {
        $('#back-to-top', context).on('click', function(){
            $('body,html').animate({scrollTop : 0}, 500);
        });
      }
    };
}(jQuery));

```

Had the same issue, AFAIK the wrapper is necessary to actually fire the behavior.
> 1 votes

---
Tags: theming, 8, nodes, javascript
---


# Question
Title: Different front page depending on previous selection for anonymous users
I have a D8 project where the client wants users to select a route they will follow depending on who they are (let's call the two groups Students and Employers), and then the next time they visit show the home page for the appropriate group.

So for example if they click mydomain.com/students, the next time they visit mydomain.com/ it will redirect them to /students

The users will always be anonymous, so not logged in.

I have seen various solutions to this (e.g. the Front module), but they all seem to be dependent either on user role (no use for anon users), a subdomain or browser locale, none of which help us.

What I have in mind is that when visiting one of the target landing pages (e.g. /students) with a Referrer header of the home page, we set a cookie or session variable. Then when the root URL is requested with no or an external Referrer header (so you can still go to the proper homepage via navigation), we check for this and send a redirect if appropriate. The actual paths used could be saved in config.

I'm sure there is a hook I can use somewhere in core to do this, haven't looked into it in much detail yet, but my biggest concern is caching. If the homepage is cached, the hook would never fire and we wouldn't get the redirect, but at the same time I don't want to disable caching on the homepage.

Any experiences/ideas here would be very much appreciated.

# Answer
So... I think I have solved this, although cache testing has not yet been done (any thoughts on how to do this welcome!).

Credit to this post for the outline solution, and also to this one for D8 redirects.

First, I create a custom module called mysite\_homepage\_redirect - it needs the following `mysite_homepage_redirect.services.yml` file (apparently a priority \> 200 means it gets fired before the cache):

```
services:
  http_middleware.mysite_homepage_redirect:
    class: Drupal\mysite_homepage_redirect\StackMiddleware\MysiteHomepageRedirect
    tags:
      - { name: http_middleware, priority: 250, responder: true }

```

Then we need the following in `src/mysite_homepage_redirect/StackMiddleware/MysiteHomepageRedirect.php`:

```
<?php

namespace Drupal\mysite_homepage_redirect\StackMiddleware;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * Provides a HTTP middleware.
 */
class MysiteHomepageRedirect implements HttpKernelInterface {

  /**
   * Map of pages that should be redirected to from home
   * this coulde ultimately be put into config with an admin screen
   */
  private $navigation_map = array(
    '/employers',
    '/students',
  );

  /**
   * The wrapped HTTP kernel.
   *
   * @var \Symfony\Component\HttpKernel\HttpKernelInterface
   */
  protected $httpKernel;

  /**
   * Constructs a MyModule object.
   *
   * @param \Symfony\Component\HttpKernel\HttpKernelInterface $kernel
   *   The decorated kernel.
   * @param mixed $optional_argument
   *   (optional) An optional argument.
   */
  public function __construct(HttpKernelInterface $http_kernel) {
    $this->httpKernel = $http_kernel;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {

    $current = $request->server->get('REQUEST_URI');
    $source = $request->server->get('HTTP_REFERER');
    $host = $request->server->get('HTTP_HOST');

    //cut the host string out of the referer
    $x = strpos($source, $host);
    if($x) {
      $source = substr($source, $x + strlen($host));
    }

    $redir = isset($_COOKIE['mysite_homepage_redirect']) ? $_COOKIE['mysite_homepage_redirect'] : false;

    if($current == '/' && strpos($source, $host) === false && $redir) {
      $response = new RedirectResponse($redir, 302);
      $response->send();
      return;
    }
    elseif(in_array($current, $this->navigation_map) && $source == '/') {
      //need to use native setcookie() because user_cookie_save relies on the user module which is not yet loaded
      //expires in 30 days
      setcookie('mysite_homepage_redirect', $current, time() + 86400 * 30);
      \Drupal::logger('mysite_homepage_redirect')->notice("saved redirect cookie: " . $current);
    }

    return $this->httpKernel->handle($request, $type, $catch);
  }
}

```

That seems to work as expected. The cookie seemed the simplest way to save the redirect. Any further thoughts welcome!
> 4 votes

---
Tags: caching, redirection
---


# Question
Title: Are edited files in core modules overwritten on updating Drupal?
I have searched related questions but could't really find a decisive YES or NO.

I changed a few files in core/modules/user/ ... to alter the display of the form used on my site. For example:

```
 $form['account']['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => $this->t(''),
      '#required' => TRUE,
      '#attributes' => [
        'class' => ['username'],
        'placeholder' => $this->t('Username'),   // ADDED THIS
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
      ],
      '#default_value' => (!$register ? $account->getAccountName() : ''),
      '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
    ];

```

> Do these edited core files revert back to their original state thus deleting my changes when I update Drupal in the future?

# Answer
> 1 votes
YES, for sure. Clear enough ....?

PS: that's also why one should never hack core ...

---
Tags: 8, users
---


# Question
Title: Wrong date field format on mobile iOS / Android
I created a form with Drupal's FAPI. The form includes two date fields. It works fine on desktop browser.

But on mobile (iOS and Android), the datepicker doesn’t show up. It is the native date selector which shows up.

The issue is that the native date selector doesn’t seem to apply the date format (in my case : `'#date_date_format' => 'd/m/Y'`)

I see 2 possible solutions :

1. With JS, force the date format
2. Force the date picker to show up (i’ve seen this on other website i’ve made but in wasn’t Drupal FAPI.

How do you handle this problem ?

Here is my code and a screen shot of the issue :

```
    $form['date_debut'] = array(
        '#type' => 'date',
        '#title' => $this->t('Date de début'),
        '#type' => 'date_popup',
        '#date_date_format' => 'd/m/Y',
        '#description' => t('Cliquez dans le champ et sélectionnez une date de début de congé dans le calendrier'),
        '#required' => TRUE
    );

```

# Answer
The solution is not to use :

```
<input type="date">

```

but

```
<input type="text">

```

With Form API, replace :

```
$form['my_date'] = array(
    '#type' => 'date',
);

```

with

```
$form['my_date'] = array(
    '#type' => 'textfield',
);

```

And attach a date picker like the jQuery Datepicker available in Drupal 8 or other library like Bootstrap Datepicker

In safari, i need to test in private mode because sometines the Safari cache prevents me to see update in my JS.
> 1 votes

---
Tags: 8, forms, datetime
---


title: Provide access among the users

text:
# Question
Title: Provide access among the users
I need a requirement like this. In my site, there will be 2 types of user role.

1) Role A 2) Role B

Role A users can able to create the new users and assign them a Role B. I want to provide the access among the Role A users.

Let say **User 1** of **Role A** created **3** users of Role B and **User 2** of **Role A** created another **2** users of Role B.

I need to provide access to **Role A** users like the users who have been created by **User 1** of **Role A** cannot be accessible or editable for **User 2** of **Role A** and vice versa.

Is there any custom module to achieve this or we need to go for custom implementation?

# Answer
I don't follow exactly what you're asking, but if you want to give lower level users the ability to assign roles without needing the 'administer permissions' permission or other high level permissions, you can add the module RoleAssign.

> RoleAssign specifically allows site administrators to further delegate the task of managing user's roles while withholding the Administer permissions permission.
>
> RoleAssign introduces a new permission called Assign roles. Users with this permission are able to assign selected roles to still other users. Only users with the Administer permissions permission may select which roles are available for assignment through this module.
>
> RoleAssign is ideal for smaller sites with a system administrator and one assistant administrator role that should be reasonably restricted in what it allows. For larger sites with multiple levels of administrators or whenever you need finer-grained control over which role can assign which other role, check out Role Delegation.
> 0 votes

---
Tags: 7, users
---