# Question
Title: Cron stopped running; logs say: "Attempting to re-run cron while it is already running."
What are the steps to troubleshoot and resolve this issue as per title?

When I try to run manually, I get a page immediately, and the error message "Attempting to re-run cron while it is already running."

# Answer
> 12 votes
The cron semaphore is probably locked. You could try calling drupal\_cron\_cleanup() from anywhere in your code (that doesn't happen to be invoked by cron) and that should unlock your cron semaphore variable.

If you have drush configured in Drupal 6 you could also try:

```
$ drush vdel -y cron_semaphore

```

# Answer
> 19 votes
# Summary

The error message you are seeing would happen if the following two conditions are met:

* You cron jobs do not finish (error) or take more than 4 minutes to finish ;
* You invoke cron more often than every 4 minutes (According to your crontab setting, not the setting in Drupal)

This error message is therefore a symptom of a cron tasks that is either failing or taking too long to run. (Note: I realise you have already found the culprit, but I wanted to add an answer for people who find this page via searches, as I did)

# Background

The first thing to understand is how Drupal cron tasks are run. The Drupal cron is *invoked* at regular intervals - either through a cron job on your server, or after every page load if you use the poor man's cron which is Drupal's default.

The cron tasks are not necessarily run every time cron is invoked however - there is a setting in Drupal (default is 3 hours) which says how often cron tasks should be run. But this delay of 3 hours only applies if the cron tasks have finished successfully.

In Drupal 7, cron uses Drupal's locking mechanisms, which provides a cooperative, advisory lock system. One of the features of this lock system is that locks expire after a certain time. In the case of cron, it expires after 4 minutes - so if your cron is invoked every 3 minutes and the previous cron job hadn't finished by that time (either it crashed or was very slow), you would indeed get this error message.

The fact you set the cron to be every 12 hours does not make a difference - because the Drupal cron task is failing/taking too long, Drupal assumes it hasn't been run so tries to run it again as soon as cron is invoked. The twelve hour delay only applies to successful cron runs.

The cron semaphore variable does not exist any more in Drupal 7 - this was for an older version of Drupal. In Drupal 7 there is no reliable way to manually release a lock, because the locking backend might change - however if you are using the core locking mechanism then you can release cron locks by editing the database:

```
DELETE FROM semaphore WHERE name = 'cron';

```

But by doing this you would only be fixing the symptoms - the problem that needs addressing is why is cron failing / taking so long to run.

# Answer
> 4 votes
The `cron_semaphore` variable did exist in Drupal 6, but you're using Drupal 7, so the semaphore locks moved into separate table called `semaphore`.

So solution to unlock the cron semaphore would be:

**Drupal 7**

```
drush sqlq "TRUNCATE semaphore"

```

**Drupal 6**

```
drush -y vdel cron_semaphore

```

# Answer
> 2 votes
You can debug the cron by using Cron Debug module.

> Cron Debug will help you find cron processes which
>
> * fail due to programming or runtime errors
> * time out (PHP, server, database)
> * are very slow
>
> Cron Debug will also allow you to test run specific cron functions while not running others. This can be nice for developing cron functions where you don't want to run a full cron.php with all maintenance, alerts and other tasks every time you test your own function.

# Answer
> 1 votes
This is how I solved the cron issue:

1. Via PhpMyAdmin, I looked in the semaphore table and deleted row where `name = cron`
2. I ran "drush cron" via command line
3. I seen an error message that gave me a clue of the issue; this may be different for you, but for me a recently uninstalled module that was sharing a PHP library with an installed module was causing an error

# Answer
> 0 votes
For Drupal 8 : drush sqlq "DELETE FROM semaphore WHERE name = 'cron';"

# Answer
> 0 votes
On Drupal 7, as even another option,

Via `drush cron` I was getting,

```
WD cron: Attempting to re-run cron while it is already running.       [warning]
Cron run failed.                                                      [error]

```

This was on development environment and happened because a previous cron was running and got interrupted.

On `includes/common.inc`, at line 5413, or around, you'll find this block, https://cgit.drupalcode.org/drupal/tree/includes/common.inc?h=7.x#n5413

```
  // Try to acquire cron lock.
  if (!lock_acquire('cron', 240.0)) {
    // Cron is still running normally.
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  }

```

Modify the `if` with an `&& FALSE`,

```
  // Try to acquire cron lock.
  if (!lock_acquire('cron', 240.0) && FALSE) {
    // Cron is still running normally.
    watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
  }

```

And rerun cron. That will allow it to run.

Please don't deploy this and revert it back after it finishes. It also helps with debugging.

# Answer
> -1 votes
I've come up against this a few times. In Drupal 6 If you don't use drush you can fix it like this:

1 Remove the cron\_% variables from the variables table.

```
SELECT * FROM variable WHERE name like "cron%";

DELETE FROM variable WHERE name like "cron%";

```

2 clear Drupal cache at: /admin/settings/performance

by pressing the 'clear cached data' button at the bottom of the page.

3 run cron from admin panel /admin/reports/status/run-cron don't run it from comand line as this can cause problems.

4 Check that the next automatic cron run completes as normal.

# Answer
> -2 votes
You can debug by using xdebug , run cron from admin interface Admin \> Configuration \> system \> cron.

---
Tags: 7, cron
---


# Question
Title: How do I enable title and target to link?
Using Drupal 8, with the link icon in the wysiwyg editor, currently in the modal popup, it only allows URL. I have to switch to source to add title and target attributes (outside website). Is there a way to add those fields in the interface specifically that modal popup? It looks like it's CKEditor. My client is not as html savvy.

Let me know + steps to enable... thanks, any help would be appreciated.

# Answer
> 1 votes
You can use D8 Editor Advanced link module.

Enhances the link Dialog in D8 CKEditor. Allows to define the following attributes:

* title
* class
* id
* target
* rel

---
Tags: wysiwyg
---


# Question
Title: how to get content type field name as drop down for filter in view
In Drupal 7.10, I have created new content type with 15 fields and file upload for collecting input from end user(named inputdata). I need to create a search page with content field of "inputdata" (content type) . In views I select the "inputdata" using exposed filter 15 field is difficult, its not fair. So I need these 15 fields as drop down (instead of equal to , contains, greater than ...in exposed filter). So How do I get the names of fields as drop down for search ? Which modules I need to configure ?

# Answer
I can only give you an example of querying the users table and displaying the people in the users table as an option but this might help:

```
  function example_page_builder() {

  $form = array();

 //getting the list of users
  $query = "select * from users where name!='';";

  $result = db_query($query);
  foreach ($result as $user) {
    $users[$user->uid] = $user->name;
  }

  $form['example_field_set']['users'] = array(
    '#type' => 'select',
    '#weight' => -6,
    '#title' => t('Select User:'),
    '#options' => $users,
  );

  return $form;
}

```
> 0 votes

# Answer
Well there are many ways for this, but we have to know if the user input widget, if they are term references or just input boxes.

There is a module that could help you here, that is Hierarchical Select

another one that could help is custom search
> 0 votes

# Answer
You can use views or module, if you are creating website in drupal 6.

As per statement in project page of the module:

> Views Or adds the ability to combine blocks of filters with OR. If one of the filters in the block is true, the combined block will be true.
> 0 votes

# Answer
You can use Better Jump Menu. In case you want to redirect it to a specific page and on the basis of getting the filtered Result.
> 0 votes

# Answer
As content represented by default in Drupal's views and its type as a filter you need to

* Edit your view
* In Filter Criteria section hit Add button
* Start typing **type** (it will bring the type that you want)
* **Expose this filter to visitors, to allow them to change it** have this checkbox checked
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to print an image in a paragraph that references a node with an image field
I have the following scenario:

I have a paragraph called **Timeslot** that contains an entity reference field to a content type called **Class**.

That content type has an image field called **Class Badge**.

I would like to print the Class Badge image inside this paragraph using a twig template.

# Answer
I went in circles for hours before I found the solution. There are many posts with partial or theoretical solutions, but none of them worked for me.

My solution consists of a twig file, paragraph--timeslot.html.twig, which prints all of the fields from the Timeslot paragraph. The line which prints the Class Badge image looks like this:

```
<img src={{ file_url(paragraph.field_class.entity.field_class_badge.entity.uri.value) }} />

```

Working from right to left:

`entity.uri.value` is the uri value for the image field in the referenced node, which is the url prefaced by public:// or private://

`entity.field_class_badge` is the field in the referenced node that contains the image.

`paragraph.field_class` is the field in the paragraph that references the node.

`file_url` strips public:// or private:// from the uri that is retrieved so it can be used as the src in the image tag.

It is worth noting that uri is one of the database fields in the file\_managed table. An alternative approach above could have been to use the filename field instead, and construct the URL manually within my code. Other fields that may prove useful would be filesize, created, and status.

Hopefully this helps someone. I doubt it's the definitive solution, but it worked for me.

UPDATE: I have since extended the solution above to display a specific image style, rather than the original image. Simply change the tag in the code to look like this, where class\_badge is the machine name of the image style.

**Essential** \- you'll need to install the Twig Tweaks module to get this version of the solution to work.

```
<img src={{ file_url(paragraph.field_monday_class.entity.field_class_badge.entity.uri.value | image_style('class_badge')) }}>

```
> 1 votes

# Answer
I ran into similar kind of problem, thought of posting my code here. My code is from the paragraph twig file

```
{% for item in paragraph.field_node_reference %}
<a href=" {{ path('entity.node.canonical', {'node': item.entity.id}) }} ">
<img src={{ file_url(item.entity.entity.field_class_badge.entity.uri.value) }} />
</a>

{% endfor %}

```
> 0 votes

# Answer
In my opinion you need to at first get

1. `target_id` from referenced field (`$entity_id = $node->get('field_class')->getValue()['target_id'];`)
2. Load the entity (`$entity = Node::load($entity_id)->toArray();`)
3. Then from that loaded entity extract your image field and pass to twig

No additional modules required.
> 0 votes

---
Tags: theming, paragraphs
---


title: How can I create a custom service?

text:
# Question
Title: How can I create a custom service?
I've been following instructions on the web on creating a new service, but I can't seem to get it to work.

In my controller:

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyController extends ControllerBase {
  public function myroute() {
      $db = \Drupal::service('mymodule.db');
      return array('DEBUG');
  }
}

```

In my mymodule.services.yml:

```
services:
  mymodule.db:
    class: Drupal\mymodule\mymoduleDB

```

In my service class:

```
namespace Drupal\mymodule;

class mymoduleDB {
  public function dosomething() {
    return 'data...';
  }
}

```

In my controller, when I comment out the line that calls \Drupal::service, then the controller works, so it's an issue with calling the service.

I'm getting a HTTP 500 error.

# Answer
Create mymodule.services.yml

```
services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []

```

Now create **Services** folder under your **mymodule/src**. After that create **CustomService.php** in Service folder.

In CustomService.php

```
<?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}

```

And for accessing service in your module file

```
$service = \Drupal::service('mymodule.custom_services');
$service->getServiceData();

```
> 11 votes

# Answer
Use dependency injection

```
namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
class MyController extends ControllerBase implements ContainerInjectionInterface{
  protected $moduleDB;

  /**
   * Constructs a MyController object
   *
   *   The module handler service.
   */
  public function __construct($moduleDB) {
    $this->moduleDB = $moduleDB;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('mymodule.db')
    );
  }

  public function myroute() {
    $db = $this->moduleDB;
    return array('DEBUG');
  }
}

```
> 2 votes

# Answer
The answer from A Reddy was pretty much what I had set up, so I stripped the code further. I had a line where I was calling:

```
$resp = new stdClass();

```

I removed it and it works. I need to research why this doesn't work, but my original setup was correct.
> 0 votes

---
Tags: 8
---


title: Create link to email all views results

text:
# Question
Title: Create link to email all views results
I have a view that outputs a list of email addresses.

I'd like to find a way to set up a mailto: link that contains all of those as one comma-separated list.

Could anyone advise?

# Answer
> 0 votes
In the views under fields add "Custom Text" field. Wherein text field you can Replacement patterns from exisiting fields. There you can give link

```
<a href="mailto:{{field_name}}">{{field_name}}</a>.

```

After that edit email field and check "Exclude from display".

---
Tags: 7, views
---


# Question
Title: Why entity_metadata_wrapper->save() doesn't update node's revision?
I'm developing a module to update nodes(enable revision). It looks like this.

```
 $nodes = node_load_multiple(array(), array('type' => $bundleType));
 foreach ($ndoes as $node){
    $w = entity_metadata_wrapper('node',$node);
    $w->MyFields->set($someValue);
    $w->save();
 }

```

It set fields correctly but node's revision-id didn't change after `$w->save()`.

How can I update the revision ID?

# Answer
> 7 votes
Is the create new revision flag set on the node for the content type? Have you tried like $w-\>revision-\>set(1); before saving? ....

**EDIT:**

Author says setting `$w->revision->set(1)` solves his issue.

# Answer
> 10 votes
When you edit a node via the UI, it is done via `node_form()`. This has a call near the top to `node_object_prepare()`, which sets up default values for that node. This includes setting the default value of `$node->revision`, which is used by `node_save()` to determine whether a new revision is needed or not.

The Entity API is revision aware, but `node_object_prepare()` is a node-specific thing. This means that you need to manage the values yourself, including setting the revision property to mimic what the node edit form will do.

# Answer
> 7 votes
None of these answers are actually correct, doing `->set(1)` makes it sound like your actually changing the revision number and therefore should increment it.

This is actually just a boolean flag so the correct answer is `$node->revision->set(true);`

As zhuchun says: he doesn't understand why its needed, when explained as a boolean flag it makes perfect sense rather than the number.

# Answer
> 0 votes
If the node type doesn't have revisions enabled by default, the most succinct way to request a new revision is:

`$w->revision = TRUE;`

which is exactly the same as using:

`$w->revision->set(TRUE);`

but with less typing required.

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


title: Pass argument to custom access callback

text:
# Question
Title: Pass argument to custom access callback
Is there a way to specify an argument to pass to a custom access callback, specifically an argument that isn't part of the path? Like in Drupal 7 you could do this:

```
function mymodule_menu() {
  $items['abc/$val'] = array(
    'page callback' => 'mymodule_abc_view',
    'access callback' => 'mymodule_abcdef_access',
    'access arguments' => array(1, 'test1'),
  );
  $items['def/$val'] = array(
    'page callback' => 'mymodule_def_view',
    'access callback' => 'mymodule_abcdef_access',
    'access arguments' => array(1, 'test2'),
  );
  return $items;
}

function mymodule_abc_access($val, $type) {
  return ($val['some_prop'] == $type);
}

```

So in Drupal 8 I would have this in mymodule.routing.yml:

```
mymodule.abc:
  path: 'abc/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::abc'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

mymodule.def:
  path: 'def/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::def'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

```

And in MyModuleController:

```
public function abcDefAccess($val, $type) {
  return AccessResult::allowedIf($val->someProp == $type);
}

```

But is there any way to pass 'test1' or 'test2' as $type? Otherwise I guess I would just have to make a separate access function for each type.

# Answer
> 2 votes
In D8 you can use custom route arguments:

> Passing arguments to controllers
>
> All keys under the defaults section which do not start with an underscore will be passed in as arguments to the controller. Name your arguments appropriately for the arguments of the controller. For example a routing.yml file with the following:
>
> ```
> example.content:
>   path: '/example'
>   defaults:
>     _controller: '\Drupal\example\Controller\ExampleController::content'
>     custom_arg: 12
>   requirements:
>     _permission: 'access content'
>
> ```
>
> Will pass on $custom\_arg to the controller, so your content method can take $custom\_arg:
>
> ```
>   public function content(Request $request, $custom_arg) {
>     // Now can use $custom_arg (which will get 12 here) and $request.
>   }
>
> ```

Source: https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

While the documentation is for a controller, the same applies to other route callbacks, like in your case an access callback:

```
public function abcDefAccess($val, $custom_arg) {
  return AccessResult::allowedIf($val->someProp == $custom_arg);
}

```

# Answer
> 3 votes
Your route:

```
regportal_user.orders:
  path: '/user/{user}/orders'
  defaults:
    _entity_view: 'user.orders'
    _title: 'Управление заказами'
  requirements:
    _custom_access: '\Drupal\regportal_user\Controller\RegportalUserController::accessOwnOrders'

```

Your controller:

```
  /**
   * Checks access for a regportal_user.orders route.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResult
   */
  public function accessOwnOrders(AccountInterface $account, $user) {
    if ($account->id() == $user) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }

```

# Answer
> 2 votes
As @4k4 said, adding a non-underscored default to the route entry will send that exact string as a parameter to the custom access controller, as long as the parameter names match up. Since your `abcDefAccess` method wants `$type`, just add `type` to your routing definitions. So mymodule.routing.yml becomes:

```
mymodule.abc:
  path: 'abc/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::abc'
    type: 'abc'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

mymodule.def:
  path: 'def/{val}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::def'
    type: 'def'
  requirements:
    _custom_access: '\Drupal\mymodule\Controller\MyModuleController::abcDefAccess'

```

---
Tags: routes, 8
---


title: Drupal db select IN, group by count

text:
# Question
Title: Drupal db select IN, group by count
need a bit of help please, when i write my query like this it works fine

```
    $query = db_query('select * from form_submissions where address in (select address from form_submissions group by address having count(address) > 1 ');
    $submissions = $query->execute();

```

but when i write it with drupal it should work like this? but it dont

```
    $query = db_select('form_submissions', 'sfs')->fields('sfs', array());
    $subquery = db_select('form_submissions', '')->fields('address', array())->groupBy('address')->having('count(address) > 1');
    $query->condition('address', $subquery, 'in');

    $submissions = $query->execute();

```

can someone see what im doing wrong?

# Answer
> 0 votes
```
    $query = db_select('form_submissions', 'sfs')->fields('sfs', array());
    $subquery = db_select('form_submissions', 'sfs')->fields('sfs', array('address'))->groupBy('address')->having('count(address) > 1');
    $query->condition('address', $subquery, 'in');

    $submissions = $query->execute();

```

# Answer
> 0 votes
Please try following code:

```
$query = db_select('form_submissions', 'sfs')
    ->fields('sfs');
$subquery = db_select('form_submissions', 'subsfs')
    ->fields('subsfs', array('address'))
    ->groupBy('subsfs.address')
    ->addExpression('COUNT(subsfs.address)', 'countAddress')
    ->havingCondition('countAddress', 1, '>');

$query->condition('sfs.address', $subquery, 'IN');

    $submissions = $query->execute();

```

---
Tags: 7, database
---


# Question
Title: `composer require` fails because "Source directory docroot/core has uncommitted changes"
**Symptom:** You have a script that fails while executing a `composer require` command, resulting in output like the following:

```
$ ./example.sh
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)

In VcsDownloader.php line 242:

  Source directory docroot/core has uncommitted changes.

```

Attempting to execute the offending `composer require` command manually results in output like the following:

```
$ composer require drupal/examples
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
    The package has modified files:
    M core.services.yml
    M includes/install.core.inc
    M includes/install.inc
    M lib/Drupal/Core/Config/ConfigInstaller.php
    M lib/Drupal/Core/Config/ExtensionInstallStorage.php
    M lib/Drupal/Core/Config/InstallStorage.php
    M lib/Drupal/Core/Entity/EntityViewBuilder.php
    M lib/Drupal/Core/EventSubscriber/ConfigImportSubscriber.php
    M lib/Drupal/Core/Extension/ExtensionDiscovery.php
    M lib/Drupal/Core/Extension/ModuleExtensionList.php
    19 more files modified, choose "v" to view the full list
    Discard changes [y,n,v,d,?]?

```

**Conditions:** You are using Composer to manage your Drupal site dependencies and applying patches with `cweagans/composer-patches`. You may be using Acquia BLT.

# Answer
**Explanation:** The problem is that `cweagans/composer-patches` is applying patches to Drupal Core after cloning it, leading Composer to believe you've modified the affected files and therefore to prompt you to overwrite them lest you unwittingly lose work in progress.

**Solution:** Configure Composer to `discard-changes` which "\[sets\] the default style of handling dirty updates when in non-interactive mode... \[to\] always discard changes in vendors", then modify your script to pass the `--no-interaction` (or `-n`) flag. E.g.:

```
$ composer config discard-changes true
$ composer require -n drupal/examples
Using version 1.x-dev for drupal/examples
./composer.json has been updated
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
Deleting docroot/core - deleted
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/core (8.6.x-dev 8dbf42a): Cloning 8dbf42a90c from cache
  - Applying patches for drupal/core
    https://www.drupal.org/files/issues/2869592-remove-update-warning-7.patch (2869592 - Disabled update module shouldn't produce a status report warning)
    https://www.drupal.org/files/issues/2885441-2.patch (2885441 - EntityReferenceAutocompleteWidget should define its size setting as an integer)
    https://www.drupal.org/files/issues/2018-09-24/2815221-109.patch (2815221 - Add quickedit to the latest-revision route)
    https://www.drupal.org/files/issues/2018-10-12/1356276-531.patch (1356276 - Allow profiles to define a base/parent profile and load them in the correct order)
    https://www.drupal.org/files/issues/2018-07-09/2914389-8-do-not-test.patch (2914389 - Allow profiles to exclude dependencies of their parent)

Writing lock file
Generating autoload files

```
> 12 votes

---
Tags: 8, composer, version-control
---


# Question
Title: Get form values into hook_node_insert / hook_node_update
I need to get in `hook_node_insert` and `hook_node_update` the value of a field I manually added to a form.

```
function hook_form_FORMID_alter(&$form, FormStateInterface $formState, $form_id) {

  $form['newfield'] = [
    '#title' => 'New field',
    '#type' => 'checkbox',
  ];
}

```

In Drupal 7 every form field is copied to the entity and it's easy to access it as explained here Get data form into hook\_node\_insert / hook\_node\_update

Is there a way in Drupal 8 too?

# Answer
Use an entity builder callback on the form, for example:

```
function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_node_builder';
}

/**
 * Entity form builder to add the menu information to the node.
 */
function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->menu = $form_state->getValue('menu');
}

```
> 3 votes

---
Tags: 8, nodes, forms
---


# Question
Title: How we can have layout options at time of node creation just like we select in panels and display suite
How we can add layout selection option of display suite or panel during node creation. Any solution available. The layout selection should be at the time of node selection.

# Answer
It sounds like what you really want is something like the Paragraphs module:

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

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/

**EDIT:** It's not a video, but here's a good place to start with Paragraphs for Drupal 7:

https://www.drupal.org/node/2605424

And since you are familiar with Display Suite, you might find this to be helpful:

https://stackoverflow.com/a/40479965
> 0 votes

---
Tags: panels, display-suite
---


# Question
Title: Get programmatically value of sub field collection item of a field collection
I have a field collection

field library

and a sub field collection

field book

which has a field collection item field title.

to get the first field collection I use a wrapper:

```
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_library->value() as $key =>
$field_collection_wrapper) {
$ffp = $field_collection_wrapper->field_title[LANGUAGE_NONE][0]['value'];
}

```

but I need another for each inside the first foreach to get the item of the sub collection. How should I do it?

# Answer
I *think* this should be structured properly. It should give you access to each book on each library item.

```
$node_wrapper = entity_metadata_wrapper('node', $node);
$libraries = $node_wrapper->field_library->value();
foreach($libraries as $library){
  $library_wrapper = entity_metadata_wrapper('field_collection_item', $library);
  $books = $library_wrapper->field_book->value();
  foreach($books as $book){
    $book_wrapper = entity_metadata_wrapper('field_collection_item', $book);
    $title = $book_wrapper->field_title->value();
  }
}

```
> 0 votes

---
Tags: stream-wrappers
---


# Question
Title: Rule to create an identical entity to the node created then delete node
I have a content type called "article" and an entity type called "article 2", they both have identical fields.

When I create an article node and save it I want a rule to fire that then basically creates an exact copy of this as an entity, article 2. then deleted the original node after that. So I am left with a copy of the node as an entity - all fields etc, and no node.

I can get rules to create an entity quite easily by using "Create a new entity" but I can't seem to map the fields from node to entity?

# Answer
> 0 votes
Wonders never cease, managed to figure this out. For anyone else:

* Created a Rule

**EVENTS:**

After saving new content of type Article

**CONDITIONS:**

1. Entity has a field:

Data selector: node

Field: added ONE field from my source node (one seems to be enough) This was called "discipline" in my case. node:field:discipline

2. Entity is of bundle:

Data selector: node

ENTITY BUNDLE: Article

(so this is my source node again, my original node I am copying from)

**ACTIONS:** (this is where we create the entity using the information from the node)

1. Create a new entity:

ENTITY TYPE:

Article CLONE (this is my entity "content type" name, to make it simple)

2. Set a data value:

Selected data: entity-created:field-discipline (this is the identical field on my newly created entity that I want to add data to.

Data selector: node:field:discipline (this is the field from the node I want to copy to my entity identical field)

3. Delete entity:node

3rd step deletes the original node that was created. You can add more "set data values" as you'll need one for each field you are copying over.

This works fine. There could be better ways to do this, of course. Hope this helps someone else.

---
Tags: entities, rules
---


# Question
Title: Inject variables from Controller to Blocks?
I have a Product module that implement's an entity, a Repository, a Controller and 2 Blocks

The problem is, in the product page, I'm querying the entity in every block and also in the Controller. I'm trying to find a way to query ONLY ONE TIME, and then pass the result to the 3 parts (Blocks and Controller).

So for example, I have:

```
class SidebarProductBlock extends BlockBase {

  $repository = new ProductRepository();

  $product_id = $route_match->getParameter('id');
  $productObject = $repository->getProductByProductId($product_id);

  // Some more processing and return
}

class StoresGridProductBlock extends BlockBase {

// Here I query AGAIN

  $repository = new ProductRepository();

  $product_id = $route_match->getParameter('id');
  $productObject = $repository->getProductByProductId($product_id);

  // Some more processing and return
}

// And in the Controller I query AGAIN.

```

How can I manage to query the database just one time and use pass the result in all 3 parts?

The Blocks are always rendered in the same page

# Answer
> 0 votes
You can't inject variables from a controller to a block.

Generally it would help to put the repository in a service, so that you don't have to instantiate it multiple times and are able to cache product objects queried before.

In this case you don't even need to call the repository in each controller/block, because Drupal upcasts entities to objects in routes and you can get the object directly from the route match, as long as the product entity is using the standard way to generate entity routes with param converter.

---
Tags: blocks, page-controller
---


title: File widget custom upload location

text:
# Question
Title: File widget custom upload location
I am working on a custom module (based on Model project) with a file field attached to my custom entities, now I would like to save files in certain directories according to entity id eg:

```
public://files/my_custom_entity_ID/filename

```

I've tried with `hook_file_insert` but can't get the entity id in order to use it later in `file_move`.

Which hook (if any) should I use? Or I am missing the whole approach?

# Answer
Assuming D8

If this is part of a "BaseFieldDefinition" of your own entity, you may set a lot of options like so:

```
// create photo
$fields['photo'] = BaseFieldDefinition::create('image')
    ->setLabel("Photo")
    ->setDescription('Ein Photo')
    ->setSettings(array(
        "file_directory" => 'profilbilder/[date:custom:Y]-[date:custom:m]',
        "file_extensions" => 'png gif jpg jpeg',
        "max_filesize" => '600 KB',
        "max_resolution" => '600x800',
        "min_resolution" => '30x40',
        "alt_field" => false,
        "alt_field_required" => false,
        "title_field" => false,
        "title_field_required" => false,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'image_image',
        'weight' => 5,
    ))
    ->setDisplayOptions('view', array(
        'type' => 'image',
        'weight' => 1,
        'label' => 'hidden',
        'settings' => array(
            'image_style' => 'thumbnail',
        ),
    ));

```

As you see, you can use tags in the file\_directory setting. If you craft your fields using the Drupal 8 field UI, you can also use tags in the UI field.

If it's D7, you should change to D8 :-)
> 0 votes

---
Tags: entities, hooks, files
---


# Question
Title: define a template file for a field item in my modules
I wish to register a template file for use with a filed item, but I can't wrap my head around it.

here is what I am trying to achieve. In my field widget Formatter

```
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];

foreach ($items as $delta => $item) {
  $elements[$delta] = [
    '#markup' => $this->viewValue($item),
    '#theme' => 'my-field-item-template',
  ];
}

return $elements;

```

}

Then in my .module file

```
function mymodule_theme($existing, $type, $theme, $path){
return array('myplugin' =>
    array(
        'variables' => array(
            'other elements' => 'other elements',
            ),
            'template' => 'my-field-item-template'
        )
    );

```

}

I wish to print my 'variables' in my twig file, I believe my template file is not registered for use with my field item this way. What's the right way?

# Answer
> 0 votes
In hook\_theme you define and register your templates.

In your code your template will be "myplugin". To use that template you need to specify "#theme" =\> "myplugin" in your render array (not my-field-item-template). Then twig tries to render your content with the file called "myplugin.html.twig". This twig file should be stored in the templates directory of your module.

You may read this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates to learn more about debugging theming.

---
Tags: theming, entities, plugins
---


# Question
Title: How to display my array values in nested array of type stdClass Object
i am having trouble figuring out how to render my array fields values for specific fields. So far i've managed to query my db and collect the node values and save it to my cart of items. However, i am unsure how to echo these into a table for users to view in the most efficient way for fields related only to itemname, quantity and field\_id.

1. The following is my code to load entities into an array:

> ```
> if (isset($result['node'])) {
>   $scart_items_nids = array_keys($result['node']);
>   $scart_items = entity_load('node', $scart_items_nids);
>   }
>
> ```

2. I run the following output to view the array:

> ```
>  echo "<pre>";
>   print_r($scart_items);
>   echo "</pre>";
>
> ```

3. This is the output i get:

```
Array
(
    [145] => stdClass Object
(
    [vid] => 264
    [uid] => 1
    [title] => Rxk
    [log] =>
    [status] => 1
    [comment] => 0
    [promote] => 0
    [sticky] => 0
    [nid] => 145
    [type] => shopping_cart
    [language] => und
    [created] => 1544177045
    [changed] => 1544177045
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1544177045
    [revision_uid] => 1
    [field_id] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 21
                            [format] =>
                            [safe_value] => 21
                        )

                )

        )

    [field_itemid] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 11
                            [format] =>
                            [safe_value] => 11
                        )

                )

        )

    [field_itemname] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Example Tour
                            [format] =>
                            [safe_value] => Example Tour
                        )

                )

        )

    [field_quantity] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1
                            [format] =>
                            [safe_value] => 1
                        )

                )

        )

    [cid] => 0
    [last_comment_timestamp] => 1544177045
    [last_comment_name] =>
    [last_comment_uid] => 1
    [comment_count] => 0
    [name] => administrator
    [picture] => 8
    [data] => a:6:{s:16:"ckeditor_default";s:1:"t";s:20:"ckeditor_show_toggle";s:1:"t";s:14:"ckeditor_width";s:4:"100%";s:13:"ckeditor_lang";s:2:"en";s:18:"ckeditor_auto_lang";s:1:"t";s:7:"contact";i:0;}
)

    [146] => stdClass Object
        (
    [vid] => 265
    [uid] => 1
    [title] => Test
    [log] =>
    [status] => 1
    [comment] => 0
    [promote] => 0
    [sticky] => 0
    [nid] => 146
    [type] => shopping_cart
    [language] => und
    [created] => 1544177049
    [changed] => 1544177049
    [tnid] => 0
    [translate] => 0
    [revision_timestamp] => 1544177049
    [revision_uid] => 1
    [field_id] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 12
                            [format] =>
                            [safe_value] => 12
                        )

                )

        )

    [field_itemid] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 11
                            [format] =>
                            [safe_value] => 11
                        )

                )

        )

    [field_itemname] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => Sample Tour
                            [format] =>
                            [safe_value] => Sample Tour
                        )

                )

        )

    [field_quantity] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => 1
                            [format] =>
                            [safe_value] => 1
                        )

                )

        )

    [cid] => 0
    [last_comment_timestamp] => 1544177049
    [last_comment_name] =>
    [last_comment_uid] => 1
    [comment_count] => 0
    [name] => administrator
    [picture] => 8
    [data] => a:6:{s:16:"ckeditor_default";s:1:"t";s:20:"ckeditor_show_toggle";s:1:"t";s:14:"ckeditor_width";s:4:"100%";s:13:"ckeditor_lang";s:2:"en";s:18:"ckeditor_auto_lang";s:1:"t";s:7:"contact";i:0;}
)

```

# Answer
Here `$scart_items` contains loaded nodes as object.

```
$item_details =array();
foreach($scart_items as $item){
  $temp = array();
  $temp['itemname'] = $scart_items->field_itemname['und'][0]['value'];
  $temp['feild_id'] = $scart_items->field_id['und'][0]['value'];
  $temp['quantity'] = $scart_items->field_quantity['und'][0]['value'];
  $item_details[] = $temp;
 }

```

`$item_details` return the required array.
> 0 votes

---
Tags: database
---


title: Configuration form confirmation

text:
# Question
Title: Configuration form confirmation
I have a configuration form which extends `ConfigFormBase`.

How can I add a confirmation popup/page to give a message to the user that some field has certain value and do you wish to continue form submission?

I know there also is the `ConfirmFormBase` class but I don't have a clue how to implement this in my configuration form.

# Answer
I'm not sure you could easily implement ConfirmFormBase with the config form. It might be easier to turn your form into a multistep form and have step 2 with a simple submit button/message for confirmation rather than trying to implement ConfirmFormBase

That should achieve essentially the same thing
> 0 votes

---
Tags: 8, forms
---


# Question
Title: Custom Ajax forms with managed_file form element
We have a form with three fields - where depending on the value of the first select field, we will show the other two form elements - one select field (the options depends on the value of the first select field) and one file upload field.

The issue is that when I upload a file the second select list value is resetting. Because managed\_file form element is again calling an ajax function which overrides the value of my first ajax call

Code is below:

```
public function buildForm(array $form, FormStateInterface $form_state) {
    $texts = array();
    $text_values = db_query("SELECT text_id, title FROM `heritage_text_structure`")->fetchAll();
    foreach($text_values AS $key => $value){
        $texts[$value->text_id] = $value->title;
    }
    $form['text'] = array(
        '#type' => 'select',
        '#title' => $this->t('Select the heritage text'),
        '#required' => TRUE,
        '#options' => $texts,
        '#default_value' => isset($form['text']['#default_value'])?$form['text']['#default_value']:null,
        '#ajax' => array(
            'event' => 'change',
            'wrapper' => 'text-info',
            'callback' => '::_ajax_text_callback',
        ),
    );
    if(!empty($form_state->getTriggeringElement())) {
        $description = '';
        $text_id = $form_state->getTriggeringElement()['#value'];
        $labels = db_query("SELECT level_labels FROM `heritage_text_structure` WHERE text_id = :text_id", array(':text_id' => $text_id))->fetchField();
        $labels_array = explode(',', $labels);
        $label_count = count($labels_array);
        for($i=0; $i<count($labels_array); $i++){
            if($i < $label_count-1)
                $description = $description.$labels_array[$i].', ';
            else $description = $description.$labels_array[$i];
        }
        $description = $description.', Content, Language';
        $csvCount = $label_count + 2;
    }
    $form['text_info'] = array(
        '#type' => 'container',
        '#prefix' => '<div id="text-info">',
        '#suffix' => '</div>'
    );
    if(isset($text_id) && $text_id > 0){
        $validators = array(
            'file_validate_extensions' => array('csv '),
        );
        $form['text_info']['fieldset'] = array(
            '#type' => 'fieldset',
            '#title' => $this->t('Select the Target Source'),
            '#description' => $this->t('Choose the source into which you are importing content'),
        );
        $sources = array();
        $source_values = db_query("SELECT id, title FROM `heritage_source_nodes` WHERE text_id = :text_id", array('text_id' => $text_id))->fetchAll();
        foreach($source_values AS $key => $value){
            $sources[$value->id] = $value->title;
        }
        $form['text_info']['fieldset']['sources'] = array(
            '#type' => 'select',
            '#title' => $this->t('Select the Source to which content is imported'),
            '#required' => TRUE,
            '#options' => $sources,
            '#default_value' => isset($form['text_info']['fieldset']['sources']['widget']['#default_value'])?$form['text_info']['fieldset']['sources']['widget']['#default_value']:null,
        );
        $form['text_info']['fieldset']['file'] = array(
            '#type' => 'managed_file',
            '#title' => t('Upload the Content in CSV format'),
            '#size' => 20,
            '#description' => t('CSV file (eg: '.$description.'). Please maintain the order of the fields.'),
            '#upload_location' => 'public://file_uploads/',
            '#upload_validators' => $validators,
        );
        $form['text_info']['fieldset']['csv_count'] = array(
            '#type' => 'hidden',
            '#value' => $csvCount,
        );
    }
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Import Content'),
    );
    return $form;
}
/**
* {@inheritdoc} Map content to the corresponding fields.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
    $text = $form_state->getValue('text');
    print("<pre>");print_r($form_state->getValue());exit;
}

/**
* Ajax callback function
*/
public function _ajax_text_callback(array $form, FormStateInterface $form_state) {
    return $form['text_info'];
}

```

# Answer
This is how we solved it:

During ajax callback, instead of getting the triggered element value, we got the value from $form\_state-\>getUserInput()

ie, in the above code replaced

`$text_id = $form_state->getTriggeringElement()['#value'];`

with

`$text_id = $form_state->getUserInput()['text'];`

Since the managed\_field will also do an ajax request the text\_id was getting replaced in the above code.
> 0 votes

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


# Question
Title: Update programmatically value of field collection item
I want to update a field collection

I have the following:

```
function pdf_app_node_presave($node) {
    if (!$node->is_new) {
        global $base_url;
        if($node->type == 'article') {
            $node_wrapper = entity_metadata_wrapper('node', $node);

            foreach ($node_wrapper->field_chapitres->value() as $library) {
                $library_wrapper = entity_metadata_wrapper('field_collection_item', $library);

                  $books = $library_wrapper->field_subchapters->value();
                  foreach($books as $book){
                    $book_wrapper = entity_metadata_wrapper('field_collection_item', $book);
                    $title ='sfsdfsd';
                    $book_wrapper->field_pdf_title2->set($title);
                    $book_wrapper->save();

                  }
            }

            field_attach_update('node', $node);

        }

    }

}

```

But i get an error i think i should use something like

```
    $values[0]['field_title'][LANGUAGE_NONE][0] = $title;

```

but it is also not working.

# Answer
> 0 votes
If you want to Update value of field collection item use `Set` Something like:

```
$book_wrapper->field_title->set($title);

```

For more info See Entity metadata wrappers Docs ***Example using field collections*** Section.

---
Tags: stream-wrappers
---


title: How to display fivestar average infos?

text:
# Question
Title: How to display fivestar average infos?
I am building a view with fivestar infos under the voting widget which look like this with the views preview:

But it is rendered without the infos in the page:
In both cases I'm an admin user identified.
I notice that a whole div with the description class available in the views and including the average/total votes infos is not rendered in the final display.

Is there some configuration to do ? Permission don't seem to be the problem.

**EDIT: So the main issue comes from the theme which is hardcoded from scratch and nothing is displayed unless it is willingly preprocessed or regenerated in a view. I found my way out (see below)**

# Answer
> 1 votes
My way out:
For the node rendering: I used `render($vars['content']['field_fivestar']['#items'][0]['count'])` and `render($vars['content']['field_fivestar']['#items'][0]['average'])` in the template of the node. And then wrap it all in custom html and some if conditions.

For the views list rendering: I recreated the field using one field Fivestar with Rated format + Vote Results : Value based on a relationship 'Content : Vote Results' filtered on Number of votes on the Aggregation Function. Then I completed it with views conditional fields for the different plural / singular / empty alternatives

# Answer
> 2 votes
Have you gone to Display Manager /admin/structure/types/manage//display and played with those settings by the gear?

I normally setup display types like "default", "teaser", "teaser- icon side", etc. Then when I create a view, instead of outputting "fields", I output one of these pre-setup display types. I use Display Suite to help get more control of them.

I'm using this votingapi widget in D8 in this way and had no issues.

---
Tags: 7, views, rating
---


# Question
Title: How to properly filter a form's data against XSS?
Drupal 7.

I've got an (ECK module) entity form. The form's only field is a multi-value field of the field\_collection (Field Collection module) type. The field collection contains two fields: a textarea, and a set of radio buttons. The user submits the form (AHAH), the entity is saved and the form is presented back to the user with the submitted values. For this project that is the intended (and necessary) behavior.

My (stripped down) validation handler is as follows:

```
/**
 * My custom validation handler.
 */
function my_module_eck_entity_form_validate($form, &$form_state) {
  $values = &$form_state['values'];
  $lang = $values['entity']->language;

  $fields = array('field_my_text', 'field_my_radios');
  foreach ($fields as $field_name) {
    // the values which get saved to the entity object
    foreach ($values['field_my_field_collection'][$lang] as &$item) {
      foreach ($item['entity']->{$field_name}[$lang] as &$child) {
        $child['value'] = filter_xss($child['value']);
      }
    }

    // the values which get output as part of the form on page-reload
    foreach ($form_state['complete form']['field_my_field_collection'][$lang] as &$item) {
      if (is_array($item) && isset($item[$field_name][$lang])) {
        foreach ($item[$field_name][$lang] as &$child) {
          if (is_array($child)) {
            $child['value']['#value'] = filter_xss($child['value']['#value']);
          }
        }
      }
    }
  }
}

```

It works and does what I want, but it is an ugly monstrosity that'll keep me up at night. There has got to be a nicer, cleaner way of doing this.

For the intents and purposes of this question, let's not discuss the pros & cons of Drupal's `filter_xss()` vs other tools - plenty of existing questions about that.

# Answer
Ended up with a different solution than what I originally posted. The following code adds a "Perform XSS validation" checkbox on the edit-field pages for all text fields, and then performs validation on those fields. If there are validation issues, an error is thrown and the form doesn't submit.

```
  /**
   * Extends hook_form_alter().
   */
  function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'field_ui_field_edit_form' && in_array($form['#field']['type'], array('text', 'text_with_summary', 'text_long'))) {
      $form['instance']['xss'] = array(
        '#type' => 'checkbox',
        '#default_value' => isset($form['#instance']['xss']) ? $form['#instance']['xss'] : 0,
        '#title' => t('Perform XSS validation'),
      );
    }
  }

  /**
   * Extends hook_field_attach_validate().
   */
  function hook_field_attach_validate($entity_type, $entity, &$errors) {
    $info = entity_get_info($entity_type);

    if (!isset($info['entity keys']['bundle']) || !$info['entity keys']['bundle']) {
      return;
    }

    $bundle_key = $info['entity keys']['bundle'];

    $lang = isset($entity->language) ? $entity->language : LANGUAGE_NONE;
    $fields_list = field_info_instances($entity_type, $entity->{$bundle_key});

    foreach ($fields_list as $field_name => $field_settings) {
      if (isset($field_settings['xss']) && $field_settings['xss']) {
        $field_items = field_get_items($entity_type, $entity, $field_name, $lang);

        foreach ($field_items as $delta => $item) {
          if (isset($item['value']) && $item['value'] != filter_xss($item['value'])) {
            $errors[$field_name][$lang][$delta][] = array(
              'error' => $field_name,
              'message' => t('Field contains invalid content.'),
            );
          }
        }
      }
    }
  }

```
> 1 votes

# Answer
There's a huge issue with your implementation: it's destructive. Let's say a user writes about HTML, uses common comparison symbols or just uses the evil emoticon for despair: `<o>`. Changing data will make it harder for the user to later edit his post, it might even remove parts of it. Let's respect the user effort of typing into a textarea and hitting 'Save'.

So, what to do about XSS? Well, XSS is not dangerous in your database, it is only dangerous when displayed in a browser. So relax about saving it and worry about displaying it. Default formatters for text fields will use the text format settings to apply filters. Make sure the text formats available for your user are safe. And if you're writing your own formatter, don't forget to filter the output (preferrably by respecting the text format settings).

See https://drupal.org/node/28984 and https://drupal.org/documentation/modules/filter for more on this topic.
> 3 votes

# Answer
I'm in favour of Yuriy's solution, since it prevents insertion of vulnerable code in the backend + proper user feedback in case something would have been pasted "accidently".

The embedded code sample is not completely working though for all entity types. For example "user" entity does not have a bundle entity key defined which makes it impossible to XSS check custom defined user fields.

Also, the applied method to expose proper errors to the user is not working when validation is done on node/%/edit form submissions, therefore replaced with more common form\_set\_error() function.

Here's a slightly adapted version of the snippet, working for both node entities as others :

```
function hook_field_attach_validate($entity_type, $entity, &$errors) {

  $info = entity_get_info($entity_type);
  if (isset($info['entity keys']['bundle']) && $info['entity keys']['bundle']) {
    $bundle_key = $info['entity keys']['bundle'];
    $bundle = $entity->{$bundle_key};
  }
  else {
    $bundle = $entity_type;
  }

  $lang = isset($entity->language) ? $entity->language : LANGUAGE_NONE;
  $fields_list = field_info_instances($entity_type, $bundle);
  foreach ($fields_list as $field_name => $field_settings) {
    if (isset($field_settings['xss']) && $field_settings['xss']) {
      $field_items = field_get_items($entity_type, $entity, $field_name, $lang);
      foreach ($field_items as $delta => $item) {
        if (isset($item['value']) && $item['value'] != filter_xss($item['value'])) {
          form_set_error($field_name, t('Field "@label" contains unallowed text elements.', ['@label' => t($field_settings['label'])]));
        }
      }
    }
  }
}

```
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How to compare before and after state in whatever_submit($form, &$form_state)
In a custom module, I have a form allowing some Create/Update/Delete data in a specific table of the database.
In the submit part of the code, I'd like to compare 'before' state (what was displayed to the user) to 'after' state (what he has actually entered) in order to properly update the database: create what has been added, update what has been changed and delete what has been removed. How can I do that?
By the way, the site is running Drupal 6.37.

# Answer
First of all: **You should migrate to Drupal 7 or 8. Drupal 6 is no longer supported as of Feb 24th, 2016.** If migration is not possible, perform security updates. The latest version of Drupal 6 is 6.38 released on 24 February 2016. Have you also heard about the Drupal 6 LTS initiative? I highly recommend reading the details https://www.drupal.org/project/d6lts, https://github.com/d6lts/drupal.

Answering your question, the simplest thing would be to pass the object with the data in the form:

```
$form['my_object'] = array(
  '#value' => $my_object,
  '#type' => 'value',
);

$form['some_field'] = array(
  '#default_value' => $my_object->some_field,
  '#type' => 'textfield',
);

```

Then in the submit handler you can compare values:

```
if ($form_state['values']['my_object']->some_field != $form_state['values']['some_field']) {
  // Value of some_field has changed!
}

```
> 0 votes

---
Tags: forms, 6
---


title: Slide effect with JQuery

text:
# Question
Title: Slide effect with JQuery
I'm not very good with Javascript/Jquery, and I don't understand something.

I display a full size image when the user arrives for the first time on the homepage. If the user scrolls, the image disappears slowly and the homepage appears.

To hide the image, I use the jquery function .hide(). It works correctly, but I want another animation because the default isn't very elegant.

To do that, it seems I need to include core/jquery.ui, but even if I include it in my dependencies for my library, I get the following error:

> TypeError: r.easing\[this.easing\] is not a function

And if I include core/jquery.ui.effects.slide, I get this error:

> TypeError: g\[i\] is undefined

Here my code:

my\_module.libraries.yml

```
home:
  js:
    js/home.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
    - core/jquery.cookie
    - core/jquery.ui.effects.slide

```

js/home.js

```
(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.pre_home = {
    attach: function (context, settings) {
    $(window).scroll(function () {
      var popup = $('#pre-home');
      console.log("Hide"); // Display correctly when I scroll
      popup.hide("slide", {direction: "top"}, 1000); // Doesn't work in this case, work I remove all parameters but not with the effect I want.
        });
    },
  };
})(jQuery, Drupal, drupalSettings);

```

I don't know what I'm doing wrong.

# Answer
> 1 votes
A big thank to @No Sssweat for the answer. My methodology was good, I done an error in the definition of the direction.

So, you need to include the `core/jquery.ui.effects.slide` in your libraries.yml file and follow this documentation http://api.jqueryui.com/slide-effect/.

---
Tags: 8, javascript
---


# Question
Title: Access the value of a disabled field in a twig template
I'm using the Paragraphs module to create components, i then make a content type and add the Paragraph as a reference field.

The form of the Paragraph has a field (a list) where a content creator can select a color name for a background color for the div. Each Paragraph has 3 values (pacific\_blue, smokey\_white, white).

However, i'm trying to get the selected value without displaying it on the site.

As long as the field is not disabled i can get the value using this code and add the class to style the div with the right background color:

```
<div class="c14a {{ content.group_wrap.field_color_backgroud.0["#markup"] }}">
  <div{{ attributes.addClass(classes) }}>
      {{ content }}
  </div>
</div>

```

So how do i get the value of a field that is disabled in 'manage display'?

Thx...

# Answer
> 0 votes
Ok, i going to answer my own question because i think it's the most elegant option for my current situation.

The solution is to **'not' disable any field**. Then in your template you just output the fields that you want. That way, you do have the value but you are not outputting it to the visitor.

```
<div class="c14a {{ content.field_background.0["#markup"] }}">
  <div{{ attributes.addClass(classes) }}>

    {{ content.field_title }}

  </div>
</div>

```

# Answer
> 0 votes
Try to add it on you hook\_preproccess\_node to variables.

something like following snippet could help you.

**on your THEMENAME.theme**

```
function THEMENAME_preprocess_node(&$vars) {
    $node = $vars['node'];
    if(isset($vars['node']) && $vars['node']->getType()=='YOUR_CONTENT_TYPE_MACHINE_NAME') {
        $values = $node->field_color_backgroud->entity->getValue();
        $vars['myvar'] = $values[0];
    }

}

```

Then on your TWIG file `{{ myvar }}` will be available.

# Answer
> 0 votes
Expanding on your self-answered question, if you're using Display Suite and Paragraphs together and want to keep your formatting and any special token fields you've created, the `without` twig filter works great for excluding any fields you don't want to show. Here's my custom template that uses a couple of fields as CSS classes, then hides them from display:

```
<{{ ds_content_wrapper }}{{ attributes.addClass('ds-1col', 'clearfix') }}>
  {{ title_suffix.contextual_links }}
  {% set bgcolor = content.field_background_color.0['#markup'] %}
  {% set angles = content.field_skew.0['#markup'] %}
  <div class="wrapper {{ bgcolor | lower }} {{ angles | lower | replace({' ':'_'}) }}">
     {{ ds_content | without('field_background_color', 'field_skew') }}
  </div>
</{{ ds_content_wrapper }}>

```

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


# Question
Title: Decryption failed because the HMAC could not be validated
I am using the Encrypt module to encrypt some of user object data.

I can encrypt data, but while decrypt it, I get the following error:

> Decryption failed because the HMAC could not be validated

```
encrypt('name') // It works.
decrypt('some encrypted data') // It throws the above error.

```

How can I decrypt data using that module?

# Answer
***I have found below solution.*** I have un-serialized encrypted data. Found below details.

Used above input to decrypt function.

```
$options = array();
$method = 'mcrypt_aes_cbc';
$key_provider = 'drupal_variable';
$config = array('provider_settings' => array('method' => 'variable_contents')); // I have updated method name later.
decrypt('encrypted_text', $options, $method, $key_provider, $config); // It works now :)

```
> 0 votes

# Answer
For me turns out that the value of the body that was being retrieved had `<p>` tags around it.

Ex:

> `<p>`a:6:{s:4:"text";s:128:"Kuh1EzLdKbebW7WI7mPLKo/g2HEA4R3c+Y3b+IKF0MGH3Oa8Bc7x5Gh+u+9wmc8EKGyc4Gdudwtvb3n6EjXNL6cIrr6EZDSsHFafspObcxYpNJhQBKGAf6134PiC4jqv";s:6:"method";s:14:"mcrypt\_aes\_cbc";s:12:"key\_provider";s:4:"file";s:7:"options";a:0:{}s:15:"method\_settings";s:0:"";s:17:"provider\_settings";a:2:{s:4:"path";s:19:"sites/default/files";s:6:"method";s:13:"base64\_decode";}}`</p>`

so all I had to do was strip those tags.

```
  $body = $vars['message_body'];
  $body = strip_tags($body);
  $vars['message_body'] = decrypt($body);

```
> 0 votes

---
Tags: 7
---


title: Field value empty in submitForm

text:
# Question
Title: Field value empty in submitForm
I've got a form field that is empty (`""`) when I submit my form and I cant figure out where I am going wrong. The field in question is `reason` \- as in the reason why this record is being changed. I also include `vid` because that field is set and passed properly. Full source code of the relevant form here

Form:

```
public function buildForm(array $form, FormStateInterface $form_state, $part = NULL, $vid = NULL) {
    $form = array();

    //...

    $form['wrapper_form_fields']['reason'] = [
      '#type' => 'textarea',
      '#title' => '<span class="required">*</span>' . t('Reason:'),
      '#value' => '',
      '#rows' => 2,
      '#attributes' => [
        'maxlength' => 250,
        'class' => ['js-modal-reason'],
      ],
      '#prefix' => '<div class="reason-wrapper">',
      '#suffix' => '</div>',
    ];

    $form['vid'] = array(
      '#type' => 'hidden',
      '#value' => $vid,
    );

    //...

    return $form;
  }

```

It appears to render out properly,

---

---

The parameter is passed in the HTTP request,

---

---

But when I dump it out in `submitForm` I get a blank value.

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $reason = $form_state->getValue('reason');

    echo "<pre>";
    var_dump($reason);
    var_dump($form_state->getValues());
    echo "</pre>";
    die;
    //...
  }

```

Output:

```
<pre>string(0) ""
array(7) {
  ["vid"]=>
  string(5) "78897"
  ["reason"]=>
  string(0) ""
  ["send"]=>
  object(Drupal\Core\StringTranslation\TranslatableMarkup)#1021 (5) {
  ...

```

Full source code of the relevant form here. One notable design decision is that most of the logic is in a parent class. I have a parent class `InfusionCenterStatusForm` that creates forms that will change the status of an instance of a content type. This base class is refined in child classes like `InfusionCenterInactiveForm` which will specialize the base form to set a record to be `inactive`.

# Answer
You should remove the `#value` property. This is what is blanking it out. If you want it blank to start with, set `#default_value` instead.

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Textarea.php/class/Textarea/8.6.x
> 1 votes

---
Tags: forms
---


title: View using Path

text:
# Question
Title: View using Path
I'm having an issue combining the use of taxonomy terms, URL alias patterns and views.

**Here's my setup:**

**1)** Taxonomy: A basic taxonomy, lets call it "Blog Tags". In here I have a term like Mountains. You can see the URL alias is shown here as "blog/tagged/mountains".

**2)** URL alias pattern: The pattern is "/blog/tagged/\[term:name\]".

**3)** View: This is a page view, that uses the path /newsroom/tagged/%. I have a contextual filter "Content: Has taxonomy term ID", that uses a specified "Blog Tags" taxonomy type.

*The following does not work:*

*The following does work*, but I cannot edit/translate my terms after applying:

Any idea what I can do differently to get this working?

# Answer
Poster opted to use the TVI module, which greatly simplifies trying to get Views to display over the default term page(s).
> 1 votes

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


title: Drush not "seeing" Drupal installation

text:
# Question
Title: Drush not "seeing" Drupal installation
I have a drupal installation running in a vagrant virtual machine. This works fine, but when I try to use Drush on this site I get very peculiar behavior. The modules that are listed when I run "drush pm-list" are all from a non-existent Drupal 8 installation. I have tried setting --root= and --uri= but to no avail. Drush simply ignores my real Drupal 7 installation and instead outputs non-existent modules from a non-existent installation??

# Answer
Try running `drush` from *inside* the VM.

First, use `vagrant ssh` to get inside.

Then, change directory to the docroot:

`cd /vagrant/docroot/`

You should be able to run Drush commands from there.

In theory, if you know how to set up Drush aliases, you won't need to do that, but this method is a useful shortcut.

Let me know if it works -- and good luck!
> 0 votes

# Answer
Thanks for the suggestion, but I figured out what was going on. It turns out that when vagrant sets up a virtual machine, it creates a version of drush that is 8.(something). It also turns out that version 8 of drush is not compatible with Drupal v7 which is what my site is. In order to get drush to work I had to download an earlier version (I ended up with 5.9). Once I did that, everything worked just fine.
> 0 votes

---
Tags: drush
---


# Question
Title: The following module is missing from the file system: (Theme name)
In D7, I'm getting many of these warnings:

```
User warning: The following module is missing from the file system: bootstrap_barrio.
For information about how to fix this, see the documentation page.
   in _drupal_trigger_error_with_delayed_logging()
      (line 1143 of /home/xxxxx/www/www/includes/bootstrap.inc).

User warning: The following module is missing from the file system: XXXXX.
For information about how to fix this, see the documentation page.
   in _drupal_trigger_error_with_delayed_logging()
      (line 1143 of /home/xxxxx/www/www/includes/bootstrap.inc).

```

The problem is that those 'modules':

1. Are actually themes in the site.
2. They are being used and the files are there (under `/sites/all/themes/`)

I've installed the Missing Module module and it didn't detect those themes as missing.

Why is Drupal confusing modules with themes and how can I remove those messages?

# Answer
> 1 votes
This is probably due to the modules changing locations since they where installed. One way to fix this is to just edit the system table. You can do this via Drush like this:

```
drush sql-cli

> select * from system where name = 'bootstrap_barrio';

Verify that the path column is not correct.

> update system set path='correct path here' where name = 'bootstrap_barrio';

```

If the path is correct, then it might be a directory rights issue. E.g. either the module or a parent can't be read by the webserver.

---
Tags: 7
---


# Question
Title: How do I alter a database schema defined from another module?
Since `hook_schema_alter()` was removed from Drupal 8, how do I alter any existing schema defined from another module in Drupal 8?

I have used `mymodule_update_8201` (`hook_update_N()`) in my .install file, but no new field or column gets added into my existing table. Is there any other way to achieve this?

This is the code for the first module (a.install).

```
function a_schema() {
  $schema['my_table'] = array(
    'fields' => array(
       'type' => array(
          'description' => 'registration type',
          'type' => 'varchar',
          'length' => 255,
        ),
     ),
  );
}

```

This is the code for the second module (b.install).

```
/**
 * Implements  hook_update_N().
 */
    function b_update_8201() {
     $spec = array(
        'type' => 'varchar',
        'description' => "New Col",
        'length' => 20,
        'not null' => FALSE,
      );
     $schema = Database::getConnection()->schema();
     $schema->addField('my_table', 'newcol', $spec);
     return $schema;
    }

```

# Answer
hook\_schema\_alter() was not used for adding fields to the schema, it was used for reporting alterations to the schema by your module. This was so that functions such as drupal\_get\_schema() knew the alterations you had made. These functions have all been removed from Drupal 8 however, so there is no need to report your changes in hook\_schema\_alter().

You can add fields to another schema using:

```
\Drupal::service('database')->schema()->addField()

```

Documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Schema.php/function/Schema%3A%3AaddField/8.2.x
> 6 votes

# Answer
For D7 it's like this, utilizing db\_change\_field:

```
/*
 * Implements hook_install()
 */
function mymodule_install() {

  db_change_field('table_name', 'field_name', 'field_name', array(
    'description'   => 'Some description',
    'type'          => 'text',
    'not null'      => TRUE,
    'size'          => 'big',
  ));

}

```
> 1 votes

---
Tags: 8, database
---


# Question
Title: Rendered Webform has no Javascript attached
I've created a simple filter that allows webforms to be rendered anywhere in a node with a tag like this: \[webform:machine\_name\]

The code to render the form is as follows:

```
$webform = \Drupal::entityTypeManager()->getStorage('webform')->load($machineName);
$viewBuilder = \Drupal::service('entity_type.manager')->getViewBuilder('webform');
$formBuild = $viewBuilder->view($webform);
return render($formBuild);

```

It works insofar as the form is displayed, client-side validation is working.

BUT none of the webform-specific JS is attached (e.g. input masks don't work). I assume this is because Drupal doesn't know it needs to attach the libraries.

How do I attach those libraries? Preferably in a method that can be invoked from the code that renders the filter, as if it's in a separate place things would start to get more complicated.

EDIT:

Following 4k4's feedback, here's the code that I'm now using. It works as above, without the libraries being attached:

```
foreach ($renderArrays as $tag => $renderArray) {
  $renderContext = new RenderContext();
  $renderedOutput = $this->renderer->executeInRenderContext($renderContext, function () use (&$renderArray) {
    return $this->renderer->render($renderArray);
  });
  $metaData = BubbleableMetadata::createFromRenderArray($renderArray);
  if (!$renderContext->isEmpty()) {
    $metaData = $metaData->merge($renderContext->pop());
  }
  $result = $result->merge($metaData);
  $text = str_replace($tag, $renderedOutput, $text);
}
$result->setProcessedText($text);

```

For completeness, $renderArrays contains:

```
['[webform:machine_name]' => [
  '#type' => 'webform',
  '#webform' => 'machine_name',
]]

```

# Answer
Now you return bare HTML without any attached meta data for caching, libraries and so on.

Also Webforms provides a render element, so this is all you need to build a webform:

```
$build = [
  '#type' => 'webform',
  '#webform' => $machineName,
];

```

The important part though is that the filter you put the token in handles the attached metadata correctly. It needs to do it similar to Entity Embed:

```
    $result = new FilterProcessResult($text);
    ...
    // We need to render the embedded entity:
    // - without replacing placeholders, so that the placeholders are
    //   only replaced at the last possible moment. Hence we cannot use
    //   either renderPlain() or renderRoot(), so we must use render().
    // - without bubbling beyond this filter, because filters must
    //   ensure that the bubbleable metadata for the changes they make
    //   when filtering text makes it onto the FilterProcessResult
    //   object that they return ($result). To prevent that bubbling, we
    //   must wrap the call to render() in a render context.
    $entity_output = $this->renderer->executeInRenderContext(new RenderContext(), function () use (&$build) {
      return $this->renderer->render($build);
    });
    $result = $result->merge(BubbleableMetadata::createFromRenderArray($build));

```

https://cgit.drupalcode.org/entity\_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

Edit: Improved bubbling of metadata:

```
    $render_context = new RenderContext();
    $entity_output = $this->renderer->executeInRenderContext($render_context, function () use (&$build) {
      return $this->renderer->render($build);
    });
    $meta_data = BubbleableMetadata::createFromRenderArray($build);
    if (!$render_context->isEmpty()) {
      $meta_data = $meta_data->merge($render_context->pop());
    }
    $result = $result->merge($meta_data);

```

---

If you are looking for an easier solution you could for example add the webform to $variables in preprocess to render it in a node template. Then the attached libraries bubble up in the right place automatically.
> 5 votes

# Answer
Even after adding the META data bubbling, which is the correct approach for processing a filter, the libraries were still not being included.

It turns out that came down to the way I was sending the output from my custom field widget to the template.

I was originally sending this to the template:

```
[
  '#markup' => check_markup($field_content, 'full_html')
]

```

When in order to correctly run the filters and attach the libraries, I should have been sending:

```
[
  '#type' => 'processed_text',
  '#text' => $field_content,
  '#format' => 'full_html',
]

```

Funnily enough it was this post from 4k4 (who also helped me above) that pointed me in the right direction:

https://drupal.stackexchange.com/a/238780/70895
> 1 votes

---
Tags: 8, webforms
---


title: Show core fields before Profile2 fields

text:
# Question
Title: Show core fields before Profile2 fields
I have fields added to Drupal 7 core users (Config \> People \> Account settings \> Manage fields) which are common to multiple user roles.

I also have fields on a Profile2 profile, which I only want to display for people registering for that role.

I cannot find a way to show the core user registration fields before the Profile2 fields. Tried Manage Fields and Display Suite, but unless you show the Profile2 fields on ALL user registration forms (which of course I don't want to do, as these fields are only relevant to one role on the Drupal site) I can't reorder them.

Been looking for a solution for over a year. Profile2 project on Drupal.org won't answer, Profile2 Reg Path project on Drupal.org won't answer either. Totally stuck, and very surprised that I seem to be the only one with this issue. I have this issue on multiple sites now.

# Answer
You can use the `hook_form_alter()` to alter the form and change the weight attribute, if your field is `field_username` you can use something like this:

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'YOUR_FORM_ID') {

    $form['field_username']['#weight'] = -50;
    $form['field_email']['#weight'] = -49;
  }
}

```
> 2 votes

# Answer
Checkout this thread - https://www.drupal.org/project/profile2\_regpath/issues/2502261#comment-12892275. Essentially:

My user fields (such as "email" and "username/password") suddenly dropped below several Profile2 fields on the registration page. MY fix:

1. Go to /admin/config/people/accounts/fields.
2. Click "Show row weights" above and to the right of the fields.
3. I then gave Email and Username/Password a weight of -999 and -998, respectively. They then moved to the top of the list on the registration page, since they have the lowest numbers.
> 1 votes

---
Tags: 7, users, display-suite
---


title: Why can only administrators see blocks?

text:
# Question
Title: Why can only administrators see blocks?
I'm using the Paragraphs and Block field modules to display a list of nodes within the content of a page. This works great while authoring, but as soon as I log out from the administrator account, the node list vanishes from the page. The component is still there, but the content is not rendered.

Here's is the twig template for my block paragraph type:

```
{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
'paragraph--id--' ~ paragraph.id.value,
]
%}

<div{{ attributes.addClass(classes) }}>
  {{ content }}
</div>

```

Not a lot going on, as you can see.

Does anyone have any experience with the block field module and can walk me through this?

EDIT:

I did some digging into the block field module source, and determined that this is the line of code causing the failure:

```
if (!$block_instance || !$block_instance->access(\Drupal::currentUser())) {

```

More specifically, it's the second condition. So for whatever reason, the current user doesn't have access to the block instance unless the current user is an administrator. Does anyone know how to solve this?

EDIT 2: I should probably mention that the blocks I'm trying to show are created by a view. I double checked that the `access` property on the generated blocks should allow all user roles.

EDIT 3: I did a little more digging, and verified that if I return `AccessResult::allowed()` from `Drupal\views\Plugin\Block\ViewsBlockBase::blockAccess`, the problem disappears. So what's happening is the view is saying the block ID is inaccessible for some reason.

EDIT 4: I discovered that setting the "Bypass content access control" permission on all users fixes the issue. However, I'm not sure this is desirable. Is there a way to fix the issue without setting this?

# Answer
FACEPALM

ok, I found the ideal solution. When I looked at my authored nodes in /admin/content, it listed them all as Status: Published. HOWEVER, when I selected all of them, selected "Publish Content" from the action dropdown, and hit "Apply to selected items", suddenly everything appeared in the view block field.

My guess is that something in the database needed to be updated. Seems like a bit of a bug, though - this should have been automatically handled by either Drupal or the block\_field module.

Anyway, fixed now.
> 4 votes

# Answer
I too had similar problem, the solution is to grant access to permissions to anonymous user to view paragraph content.

In **Paragraphs Type Permissions -\> Some Para Test : View content** givining permission to anonymous user solves the problem.
> 2 votes

---
Tags: 8, blocks, paragraphs
---


# Question
Title: How to override other module function/hook from my custom module?
I'm currently working on a custom module which holds a list of organization IDs that will be used to match with an attribute I get from a SAML idP response.

I'm currently using the saml\_sp SAML Service Provider module which has hooks/functions for finding the Drupal user and log it in, otherwise create a new user if none exists with that email.

I need to check if the org. ID matches any of the IDs in my custom module's table entries instead, so there's a substantial amount of modifications needed to change this workflow.

Preferably, I wish not to do any modifications to the saml\_sp code as future updates of that module or fresh installations would cause havoc and the login won't work.

Is there a way to bypass saml\_sp's hooks/functions so that my custom module can "take over" once the particular hook/function in saml\_sp gets called?

There seems to be a lot of mixed opinions about this. Personally I don't see the point in not being able to do this, as the typical Drupal installation consist of an orgy of modules and they should all be able manipulate each other, right? Or am I missing another simpler solution to the problem?

# Answer
> 0 votes
In general, if a module does not provide a hook, some other will do. You could check if some hook in core fits to what you need to do. Depending on what is the final result of your data change, you could perform it after a module generates the data to be changed, and before the data gets saved, for example. By another hand if a module already uses the same hook you want to use it is still possible to rely on the weight of your module to be sure it will run afterwards. By the description of your specific requirements (login a user and create a user) `hook_user_login` and `hook_user_presave` could be used.

---
Tags: 7, hooks
---


# Question
Title: Editing a Field Collection element in a custom module
In a custom module, I'd like to to edit a Field Collection element. The element is linked to a taxonomy but I think the code would look quite similar if it was to a content type.

I've read a lot of documentation, source code, forum entries and Drupal articles, but I'm stuck.

In my `hook_form()` implementation, I've got:

```
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'my_fc_field_name'));
// In a content type, use ('node', $node) instead
$field_collection_item->setHostEntity('taxonomy_term', $term);

// Not sure if those three lines are usefull
$field_node_example_values = field_get_items('taxonomy_term', $term, 'my_fc_field_name');
$field_node_example_ids = field_collection_field_item_to_ids($field_node_example_values);
$field_node_example_fc_items = field_collection_item_load_multiple($field_node_example_ids);

// Not sure if this line is correct
$form_state['field']['my_fc_field_name'] = $field_node_example_fc_items;

/* All examples below produce the same result : only one instance of the FC form appears, with no existing values and no buttons */

module_load_include('inc', 'field_collection', 'field_collection.pages');

// 1/
$form = field_collection_item_form($form, $form_state, $field_collection_item);

// OR

// 2/
$form['my_form_entry'] = array();
field_attach_form('field_collection_item', $field_collection_item, $form['my_form_entry'], $form_state);

// OR

// 3/
$output = drupal_get_form('field_collection_item_form', $field_collection_item);
$form['my_form_entry'] = $output;

```

So, **my goal** would be to get the same result as "out of the box" FC edit form, a nice fieldset with as many instances as exist, with Remove and Add buttons.

To be clear, I can see this type of form when I edit the taxonomy term, but I'd like to do it in a custom module.

I've look into the FC module, specifically the `field_collection_field_attach_form` and `field_collection_field_widget_form` functions, but I'm not sure how I could use them.

Some useful articles and forum entries:

# Answer
Strictly speaking on how to edit a field collection entity, once you have the field collection ID (you would get it from a field on your host entity, for example), you can load the collection using entity\_metadata\_wrapper, change it and them save it back.

```
$collection = entity_metadata_wrapper('field_collection_item', $collection_id);
// Do your change
// ...
$collection->save();

```
> 0 votes

---
Tags: 7, entities
---


title: How can I add field to the view?

text:
# Question
Title: How can I add field to the view?
I have created a view, which displays different content types. I have added some fields for dispalying (image, title, description). The issue for me is that not every node has an image. When it doesnt have the Drupal renders only title and description. How can I force adding image field for all nodes, even when it doesnt exist?

In my css I am using an :empty selector to add default background image.

# Answer
> 3 votes
In the view configuration settings for the Image field, there is a "No Results Behavior" section that allows html text input:

You can add some html code like:

```
<img src="/sites/default/files/no-results.jpg" alt="Description">

```

to add an anchor image that only displays in the View if there are no Image files attached to the node field.

---
Tags: views, 8
---


# Question
Title: Migrate Site from aegir Drupal hosting platform to Acquia hosting
I have three sites hosted in Aegir hosting environment. No I need to move them to Acquia hosting. Here are some doubts I have:

1. Should I need to move the code as a normal multisite setup to Acquia?
2. Since the codebase is extracted from aegir environment, I don't have any files on the drupal root like install.php, update.php?

Sorry I haven't worked so much with aegir. So this might sound dump. Please help me with this.

# Answer
> 1 votes
Disclaimer: I do not use Acquia and don't know their service.

> Should I need to move the code as a normal multisite setup to Acquia?

The documentation seems to say that multisite is supported: https://docs.acquia.com/cloud/multi-site

You would probably need to copy the platform from /var/aegir/platforms. If you look in that directory, each directory is a pretty normal Drupal multisite codebase.

> Since the codebase is extracted from aegir environment, I don't have any files on the drupal root like install.php, update.php?

The platform is just a normal Drupal codebase, it should have these files (even if it doesn't use them).

The hard part will be to move the databases, you will (presumably) need to create them in the Acquia frontend, and change the settings.php file of each site to use the new database info. Aegir creates a drushrc.php but in a non-Aegir environment you can just take the settings and move them into settings.php.

Hope this helps.

# Answer
> 0 votes
Move the website by packing all of the files in the Drupal installation in a zip archive & using FTP/FXP to transfer. Use the Backup & Migrate module or phpMyAdmin to make copies of the database. Replace any missing files from Drupal core that Aegir removes. You may consider doing a complete upgrade of core & contributed modules customized by Aegir to the latest Drupal version. Then run update.php & the multi-site should be working as normal on Acquia Cloud.

---
Tags: migrations, aegir
---


# Question
Title: How do I profile a site that is on shared hosting?
I run a commerce website in a shared hosting, from time to time it's being too slow, I tryied many ways to find the cause (css/js agreggation,enable caching, views caching, disabling some big modules :update manager,database logging,l10n,i18n, disabling no used modules, setting cron job to never) without result.
I'm not an experienced php developer, and I want to profile my website, I know that I have to install some tools in the server, so **I want to ask if there is a way to do that in my shared hosting**.
fortunately I'm allowed to enable many extentions and change some settings in my cpanel, below a screenshot of what I'm allowed to do.

# Answer
> 0 votes
Two of the most important optimizations to consider adding to optimize Drupal web server performance for ecommerce are APC & Memcached.

With Memcached, you will need to install the Drupal integration module & make some edits to the settings.php file. (tutorial)

With APC, there is also a Drupal integration module, but you need to edit the php.ini file on the web server. (tutorial)

You can also see if your web host supports Zend Opcache on shared hosting. Otherwise make sure to run Drupal 8 on PHP 7.x settings & upgrade to NGINX, Varnish Cache, & Redis solutions for the best web server performance for ecommerce.

---
Tags: performance
---


# Question
Title: How do I display a message to users, with the selections they has made from the contextual filter?
I have a view with more than one contextual filters. For example, filter on Age, and Gender. if the filter is on Age, and/or gender I would like to display a message to the user regarding the selections he/she has made. i.e, Message to user: "you are filtering on age"... How can i achieve this? I thought about writing my own module to do it, but i figured there might be an exiting module, or solution that does this already.

Thank!!

# Answer
You can add a Header to the view, some of the tokens you can add include the Contextual filter values
> 2 votes

---
Tags: views
---


# Question
Title: Make one reference and load the other automatically (Entity Reference)
I have a content type "songs", lets say a node has a reference to 4 or 5 other nodes. What I want is when I create a new node, I just need to make a reference to one node and the other 4 nodes will be loaded automatically.

Is that possible?

# Answer
Broadly if your node reference is required your user must to fill it on node creation. So you could try to use hook\_node\_presave or in the form layer you could have your submit handler to deal with that. Once you get the reference chosen by the user you would need to retrieve the other 4 related references that will be also added as siblings in the multi valued node reference field. By another hand if you want to make all of this visible in the form before it gets submitted you could use hook\_form\_alter (in case you don't have your own hook\_form) to add a behavior to the node reference field form element and if it has just a checkbox widget you could simply automatically check the other nodes to be referenced using the behavior to react the check box that has been checked.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to display the default user picture programatically?
I'd like to print a user's image in a View's template file. If the user hasn't set an image yet, the default user picture (set to `public://pictures/default.jpg` at `Configuration > People > Account settings`) should be rendered.

I used the following code:

```
<?php $account = user_load($user->uid); ?>
<?php if (isset($account->picture->uri)) {
          $path = $account->picture->uri; }
      else {$path = "public://pictures/default.jpg"; } ?>
<?php $array = array('style_name' => 'picture',
                     'path' => $path,
                     'alt' => 'Picture'); ?>
<div class="user-image"><?php print theme('image_style', $array); ?></div>

```

That works perfectly, but I don't really like the `isset` approach, because it makes me think that it was redundant to specify the default image path in the configurations. Is there another method that uses the default path automatically?

# Answer
> 3 votes
It's a bit of a strangled route - Drupal itself uses some conditionals in `template_preprocess_user_picture()` to make that decision:

```
if (!empty($account->picture)) {
  // @TODO: Ideally this function would only be passed file objects, but
  // since there's a lot of legacy code that JOINs the {users} table to
  // {node} or {comments} and passes the results into this function if we
  // a numeric value in the picture field we'll assume it's a file id
  // and load it for them. Once we've got user_load_multiple() and
  // comment_load_multiple() functions the user module will be able to load
  // the picture files in mass during the object's load process.
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

```

If it suits your use case, you can just set the `user_picture_style` variable to your style name, and use `theme_user_picture()`:

```
$build = array(
  '#theme' => 'user_picture',
  '#account' => $user,
);
$picture = drupal_render($build);

```

The caveat is that `user_picture_style` is a global var, so if you want to use something different for the style used elsewhere in the site, you're stuck with reproducing the same logic as the preprocess function above.

# Answer
> 1 votes
From Clive's answer, I got the solution to render node author's image using the below codes:

First of all, we need to get the uid

```
$node = $variables['node'];
$author = user_load($node->uid);

```

Then using the uid we can render the user's image like this

```
<img src="<?php print file_create_url($author->picture->uri); ?>" alt="user picture" />

```

To get other fields of a user account we have to use `field_get_items`

```
$field = field_get_items('user', $author, 'field_mac_name');

```

then render the fields using `print render($field[0]['value']);`

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


# Question
Title: What is the basic concept behind revisons in term of performance?
On a Drupal 8 project, I am planning to allow revisions to be created for one "content type" which consist of around 40 different fields !

Can someone explain the concept behind on how Drupal save the revisions ?

My main concern is that the "Content type" in question will have in one year around "one million +" nodes with at least "3 revisions" for each node.

Could this affect the performance of the website ?

Revisions are treated as separated nodes as well ?

**Update:**

Any node of this content type will live on the website for a period of 1 year and then will be deleted for good !

# Answer
Drupal essentially stores a copy of the node each time a revision is created. So if you're making alot of text edits it will be your database size that will mainly increase because of enabling revisions. (But drupal will also keep any files uploaded that are associated with previous revisions)

So normally for nodes you have about 3 core tables with a row for each node. Then you have a table for each field you add to content types e.g. "node\__field\_my\_field" which holds the live content for that field.

So with a million nodes you'd expect 1 million rows in the core node tables and up to 1 million rows in each of your field tables for each node (If you populate every field for every node)

If you enable revisions a few new tables get created to start tracking each revision, I think its 2 extra core tables and then a revision table for each field. But this time every time you make a revision it add a row to all these tables. So with your 1 million nodes with 3 revisions you will effectively quadruple your database storage requirement

But in terms of site performance it shouldn't really have too much effect as databases can scale well
> 3 votes

---
Tags: 8, nodes
---


# Question
Title: How to make node hierarchy with siblings and child pages
I want to make a node hierarchy menu which will display the child pages and siblings if child pages don't exist. I want to have the following structure

`parent
 child
 child
 child` or

`parent
 sibling
 sibling`

# Answer
> 0 votes
You will need to create a entity reference field to find the parent node. On each child select the parent it belongs with.

In Views you can then create a "menu" by using views field views and passing the parent (content ID) argument into the child view.

In your parent view filter, make sure and filter by Parent is Empty to show only parents if there are no children.

On your child view, make sure Context has the entity reference to the parent.

---
Tags: navigation
---