# Question
Title: How to wrap a fields or other elements in div block?
I want to wrap these elements in one div (this div should be before div class = row) but I don't know where to add this div

Example:

```
<div class="col col-lg-4 col-md-4 col-sm-4 col-xs-6 ">
            <div class = "my_custom>
             <div class="views-field views-field-title">
             <div class="views-field views-field-field-image">
             <div class="views-field views-field-field-product-reference">
             <div class="views-field views-field-commerce-price">
            </div>
        </div>

```

I am using Bootstrap theme and views\_bootstrap module.

# Answer
You could create a template for your view fields:

**views-view-fields--\[view-name\]--\[machine-name\].tpl.php**

```
Example: views-view-fields--hello-world--block-1.tpl.php

```

In template file you add code like this, this is just an example, modify as you need:

```
<div class="example">
 <div class="row">
   <div class="col-xs-6 col-sm-4">
     <div class="my_custom">
       <?php echo $fields["title"]->content .
                  $fields["body"]->content .
                  $fields["field_product_reference"]->content .
                  $fields["commerce_price"]->content;
       ?>
     </div>
   </div>
 </div>
</div>

```

Place your template file in `/sites/all/themes/YOURTHEME/templates` folder and **clear/flush cache to see changes**.
> 0 votes

# Answer
In case you want a simpler answer with no coding needed just use Views Fieldset. So install the module, add your row class on the view (Format \> Settings \> Row Class).

Then add a fieldset (Fields \> Add \> Global: Fieldset), in the settings of the fieldset choose div and to the HTML classes add the column classes. Don't forget to to go to Fields \> Rearrange and put your fields in the fieldset group.

That's it.
> 1 votes

---
Tags: 7, theming
---


title: Drupal 8 Views Translated relationships

text:
# Question
Title: Drupal 8 Views Translated relationships
I have a View with relationships (to referenced entities) that have translations. This causes duplicate rows in the results for each of the referenced entities translations.

You probably know of this behavior as it is the same as in this bug: https://www.drupal.org/node/2582535

I have tried to find a workaround (distinctt query, aggregation, filter by distinct count=1, filter by page language) but with no result. If you know of an alternative i would be happy and grateful to know it.

View Query:

> SELECT DISTINCT node\_field\_data.nid AS nid, node\_field\_data.title AS node\_field\_data\_title, node\__field\_description.field\_description\_value AS node\__field\_description\_field\_description\_value, node\__field\_requirement\_priority.field\_requirement\_priority\_value AS node\__field\_requirement\_priority\_field\_requirement\_priority\_, node\_field\_data\_node\__field\_required\_by\_sub.title AS node\_field\_data\_node\__field\_required\_by\_sub\_title, field\_submodules\_node\_field\_data.title AS field\_submodules\_node\_field\_data\_title, field\_submodules\_node\_field\_data\__node\__field\_order.field\_order\_value AS field\_submodules\_node\_field\_data\__node\__field\_order\_field\_or, node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_order.field\_order\_value AS node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_ord, node\__field\_order.field\_order\_value AS node\__field\_order\_field\_order\_value, MIN(node\_field\_data.nid) AS nid\_1, MIN(node\_field\_data\_node\__field\_required\_by\_sub.nid) AS node\_field\_data\_node\__field\_required\_by\_sub\_nid, MIN(node\_field\_data\_node\__field\_dependencies.nid) AS node\_field\_data\_node\__field\_dependencies\_nid, MIN(field\_submodules\_node\_field\_data.nid) AS field\_submodules\_node\_field\_data\_nid FROM {node\_field\_data} node\_field\_data LEFT JOIN {node\__field\_required\_by\_sub} node\__field\_required\_by\_sub ON node\_field\_data.nid = node\__field\_required\_by\_sub.entity\_id AND (node\__field\_required\_by\_sub.deleted = '0' AND node\__field\_required\_by\_sub.langcode = node\_field\_data.langcode) LEFT JOIN {node\_field\_data} node\_field\_data\_node\__field\_required\_by\_sub ON node\__field\_required\_by\_sub.field\_required\_by\_sub\_target\_id = node\_field\_data\_node\__field\_required\_by\_sub.nid LEFT JOIN {node\__field\_dependencies} node\__field\_dependencies ON node\_field\_data.nid = node\__field\_dependencies.entity\_id AND (node\__field\_dependencies.deleted = '0' AND node\__field\_dependencies.langcode = node\_field\_data.langcode) LEFT JOIN {node\_field\_data} node\_field\_data\_node\__field\_dependencies ON node\__field\_dependencies.field\_dependencies\_target\_id = node\_field\_data\_node\__field\_dependencies.nid LEFT JOIN {node\__field\_submodules} node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_submodules ON node\_field\_data\_node\__field\_required\_by\_sub.nid = node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_submodules.field\_submodules\_target\_id AND node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_submodules.deleted = '0' LEFT JOIN {node\_field\_data} field\_submodules\_node\_field\_data ON node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_submodules.entity\_id = field\_submodules\_node\_field\_data.nid LEFT JOIN {node\__field\_description} node\__field\_description ON node\_field\_data.nid = node\__field\_description.entity\_id AND (node\__field\_description.deleted = '0' AND node\__field\_description.langcode = node\_field\_data.langcode) LEFT JOIN {node\__field\_requirement\_priority} node\__field\_requirement\_priority ON node\_field\_data.nid = node\__field\_requirement\_priority.entity\_id AND (node\__field\_requirement\_priority.deleted = '0' AND node\__field\_requirement\_priority.langcode = node\_field\_data.langcode) LEFT JOIN {node\__field\_order} field\_submodules\_node\_field\_data\__node\__field\_order ON field\_submodules\_node\_field\_data.nid = field\_submodules\_node\_field\_data\__node\__field\_order.entity\_id AND (field\_submodules\_node\_field\_data\__node\__field\_order.deleted = '0' AND field\_submodules\_node\_field\_data\__node\__field\_order.langcode = field\_submodules\_node\_field\_data.langcode) LEFT JOIN {node\__field\_order} node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_order ON node\_field\_data\_node\__field\_required\_by\_sub.nid = node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_order.entity\_id AND (node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_order.deleted = '0' AND node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_order.langcode = node\_field\_data\_node\__field\_required\_by\_sub.langcode) LEFT JOIN {node\__field\_order} node\__field\_order ON node\_field\_data.nid = node\__field\_order.entity\_id AND (node\__field\_order.deleted = '0' AND node\__field\_order.langcode = node\_field\_data.langcode) WHERE (( (node\_field\_data\_node\__field\_required\_by\_sub.nid IN('1000', '1010', '1020', '1030', '1040') ) )AND(( (node\_field\_data.status = '1') AND (node\_field\_data.type IN ('e\_proc\_req')) )))AND( (node\_field\_data\_node\__field\_dependencies.nid IS '') OR (node\_field\_data\_node\__field\_dependencies.nid IN ('')) ) GROUP BY node\_field\_data.nid, node\_field\_data\_title, node\__field\_description\_field\_description\_value, node\__field\_requirement\_priority\_field\_requirement\_priority\_, node\_field\_data\_node\__field\_required\_by\_sub\_title, field\_submodules\_node\_field\_data\_title, field\_submodules\_node\_field\_data\__node\__field\_order\_field\_or, node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_ord, node\__field\_order\_field\_order\_value HAVING (( (COUNT(DISTINCT node\_field\_data.nid) = '1') )) ORDER BY field\_submodules\_node\_field\_data\__node\__field\_order\_field\_or ASC, node\_field\_data\_node\__field\_required\_by\_sub\__node\__field\_ord ASC, node\__field\_order\_field\_order\_value ASC

# Answer
> 2 votes
Update: Found a workaround by removing the duplicate rows in pre render. It is not nice but it achieves the wanted result.

```
function my_module_views_pre_render(ViewExecutable $view) {
if ($view->id() == 'my_view') {
    $newresult = array();
        foreach ($view->result as $row) {
            if (in_array($row->_entity->id(), $newresult)) {
                unset ($view->result[$row->index]);
            }
            else {
            array_push($newresult, $row->_entity->id());
            }
    }
} }

```

# Answer
> 0 votes
You should definitely create a "translation" filter criteria in your view. I think there should be also a workaround / exact filter to make constraints on relation entities!

---
Tags: views, 8
---


# Question
Title: How to add a view mode caching dependency in my custom block?
I have a block which renders fields of a node. The output of each field is controlled in the view mode settings of the node entity. Now, how can I add caching which is depended on the view mode settings?

# Answer
> 1 votes
Found it out :)

Using `entity_get_display` to actually load the display view settings of the current node and then just merge the tags:

```
<?php

public function getCacheTags() {
  if ($node = $this->getNode()) {
    $cacheTags = Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    $display = $this->getEntityViewDisplay(); // function which uses entity_get_display
    $cacheTags = Cache::mergeTags($display->getCacheTags(), $cacheTags);
  }
  else {
    $cacheTags = parent::getCacheTags();
  }

  return $cacheTags;
}

```

---
Tags: 8, caching, entities
---


# Question
Title: How to use fields of a flag instead of only toggling the flag?
I have created a flag (using the Flag module) called `status` and a field to it and named it `remarks`. Now, how do I let users to flag other users and fill in the remarks field for that particular flag.

All I am able to do is toggle the flag.

I couldn't find any documentation on it and the complimentary module of flag called flagging form is obsolete.

When a user flags another user, I want a pop-up to appear asking them for remarks before flagging the user.

# Answer
> 1 votes
When configuring flag(s) (using the Flag module), you can indeed attach fields to them. However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

> By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.
>
> Navigate to `Administration > Structure > Flags` page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

---
Tags: 7, entities, flags
---


# Question
Title: Unable to generate html using theme_table in block view
I have created a block\_view, In that block I want to show dynamic table.

I have written following code.

```
$table_headers = array(t('User'), t('Relation'),t('Period') );
foreach ($result as $row) {
            $table_rows[] = array(
            $row->name,
            $row->relation,
            $row->period_from,
           );
         }
 dpm($table_rows);

```

In above `$table_rows` array, I am getting following elements

If I am using

```
$table_html = theme_table($table_headers,$table_rows);
$block['content'] = $table_html;

```

then getting following error on page

```
The website encountered an unexpected error. Please try again later.

```

If I used

```
$table_html = theme('table',$table_headers,$table_rows);
dpm($table_html);
$block['content'] = $table_html;

```

I am getting following html on page

Please suggest were I made mistake and what should I do.

# Answer
The error is how you pass the parameters to the theme hook. You should use the following code.

```
$block['content'] = theme('table', array('header' => $table_headers, 'rows' => $table_rows));

```

In Drupal 7, theme hooks receive their parameters in an array.

You could also use the following code, since on Drupal 7 you can directly use a render array.

```
$block['content'] = array(
  '#theme' => 'table',
  '#header' => $table_headers,
  '#rows' => $table_rows
);

```

If a module modified the *table* theme hook, and you don't understand which variables the modified version uses, or in general, if you don't know which variables are used from a theme hook, you can print the value returned from `theme_get_registry()` to check that.
For example, in my test site, `drush ev "\$hooks = theme_get_registry(); var_export(\$hooks['table']);"` prints me the following.

```
array (
  'variables' => array(
    'header' => NULL,
    'rows' => NULL,
    'attributes' => array(),
    'caption' => NULL,
    'colgroups' => array(),
    'sticky' => true,
    'empty' => '',
  ),
  'type' => 'module',
  'theme path' => 'modules/system',
  'function' => 'theme_table',
)

```
> 1 votes

# Answer
Assuming Drupal 7, and assuming `$table_rows` and `$table_headers` contain valid data, this is what you need:

```
$block['content'] = [
  '#theme' => 'table',
  '#rows' => $table_rows,
  '#header' => $table_headers,
  '#empty' => 'Nothing to see here...',
];

```
> 1 votes

# Answer
Assuming drupal 7, and assuming $table\_headers and $table\_rows have correct data.

```
$table_headers = array(t('User'), t('Relation'),t('Period') );
foreach ($result as $row) {
            $table_rows[] = array(
            $row->name,
            $row->relation,
            $row->period_from,
           );
         }

$output = theme('table', array('header' => $table_headers, 'rows'=> $table_rows));

```
> 0 votes

---
Tags: 7, theming, blocks
---


# Question
Title: Views contexual filter based on nid (not from URL)
I am using Viewfield module to display taxonomy terms of a node is referencing to. I am not using the default taxonomy field available in views because I want more freedom on manipulating the rendered taxonomy terms.

When I am in the node page I use contextual filters and I provide the default value from the URL. Easy. But...

For listing nodes of a taxonomy term I use views also and I want the same functionality in there.

The only way I can do this is by providing the default value from the nid of every node (row). So how can I get the nid as a contextual filter in such case?

Thanks

# Answer
Use the Views Field View module and add Content: Nid as a field and check mark ☑ exclude from display.

Add **Global: View** a field and pass `[%nid]` token/replacement pattern as an argument as contextual filter.

Note: make sure it's arranged above your View field view so you have access to the `[%nid]` replacement pattern/token.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I get the vote result in Vote API?
I have installed the rate module, and found out that the votes associated to a node are stored in the votingapi\_vote table.
Is there a function to use to get the sum of all the votes for a node?

# Answer
> 2 votes
As you have installed the Rate module, then you can use the function rate\_get\_results(), which can be called as `rate_get_results('node', $nid, $widget_id)`; `$nid` is the node ID of the node for which you want to get the result, and `$widget_id` is the identifier of the widget used to cast the vote.
The result is an array that contains many values (some of them are present only for a particular widget); in particular `$output['rating']` is the rating, and `$output['count']` is the number of the votes.
If the widget saves the sum of the votes, then `$output['rating']` (where `$output` contains the result returned from `rate_get_results('node', $nid, $widget_id)`) contains the sum of the votes, which is what you are looking for.

# Answer
> 1 votes
Just use \_votingapi\_get\_standard\_results()!

# Answer
> 0 votes
First create the followings relationships:

Content: Vote results -- Value type: No filtering -- Aggregation function: Average vote.

Second, create the same relationship again changing the Aggregate function to: Number of votes and the identifier to: Vote result (rank.)

Third, add the following Sort criterion: Vote results: Value (desc.)

Last, add another sort criterion identical to the one you just created except that you will select the second relationship (Vote result (rank.) The sort order is also descending.

That will give you the desired results: The nodes are now properly ranked.

You can test this by enabling Text to display under the stars: Both user's and average vote in the rating field.

# Answer
> 0 votes
With Drupal 7, you can get vote information programatically using the function votingapi\_select\_results().

Ex:

```
$criteria = array();
$criteria["entity_id"] = $nid;
$criteria["entity_type"] = "node";
$criteria["value_type"] = "points";
$criteria["tag"] = "hopper";
//$criteria["function"] = "count";   // don't set, and get an array of all.

$res = votingapi_select_results($criteria);

```

If you then examine (ex: dpm($res)) you can see that $res is an array of all the information you will need for each "function" of your voting widget.

To figure out which "value\_type" and "tag" to use, look at the votingapi\_cache table.

---
Tags: 7
---


# Question
Title: Installing Drush - permission denied error
I just successfully installed Drush user composer into the .composer/vendor/bin folder. When I try to run "drush status" I get an error sh: /Users/Marianna/drush: Permission denied

What do I do now?

# Answer
You can follow following two links, they are simple two steps and make the Drush running perfectly with no issue, even you can upgrade drush with that.

(1) How to install the Drush using Homebrew. And after that follow following steps to Symlink the php file location between your servers and MAMP.

(2) MAMP: Symlink PHP to /usr/bin/php

I was facing the same issue and re-installed using above steps and this set of two links worked perfectly.
> 1 votes

# Answer
I solved this by removing drush from the User folder.
> 0 votes

---
Tags: drush
---


# Question
Title: import local drupal site with database already exist
i create a local website in my laptop and now i want to work on the project from an other laptop, after installing the module backup and migrate and active it , i download the public files settings and default database, after that in aquia dev desktop i choose import local drupal site then i choose the folder (public files downloaded) as my local code base folder and for database i choose start with Mysqldatabase dump file, at the end, after i click on the link: my local site, it shows me this :

Not Found

The requested URL / was not found on this server.

# Answer
You can use Backup & Migrate Module for importing and exporting DB's.

> Backup/Restore multiple MySQL databases and code
> Backup of files directory is built into this version
> Add a note to backup files Smart delete options make it easier to manage backup files Backup to FTP/S3/Email or NodeSquirrel.com Drush integration Multiple backup schedules AES encryption for backups
> 0 votes

---
Tags: 7, migrations, configuration
---


# Question
Title: How to fix my problem when trying to create a Drupal sub-theme with Drush?
I get the following error when I try to run the "drush fst foundation-subtheme" command.

```
sh-3.2# drush fst foundation-subtheme
The drush command 'fst foundation-subtheme' could not be found.  Run `drush cache-clear drush`  [error]
to clear the commandfile cache if you have installed new extensions.
Drush was not able to start (bootstrap) the Drupal database.                                    [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this
case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have
no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

```

Drush was attempting to connect to:

> Drupal version : 7.32
> Site URI : http://default
>
> Database driver : mysql
> Database hostname : localhost
> Database port : 3306
> Database username : root
> Database name : drupal
> PHP executable : /usr/bin/php
> PHP configuration :
> PHP OS : Darwin
> Drush script : /Users/Marianna/.composer/vendor/drush/drush/drush.php Drush version : 8.1.3 Drush temp directory : /tmp
> Drush configuration :
> Drush alias files :
> Drupal root : /Users/Marianna/Documents/Sites/Link-New
> Drupal Settings File : sites/default/settings.php
> Site path : sites/default

I get the following error when I try to install foundation with drush:

```
sh-3.2# drush --uri=http://linkengineering en zurb_foundation
Command pm-enable needs a higher bootstrap level to run - you will need to invoke drush from a  [error]
more functional Drupal environment to run this command.
The drush command 'en zurb_foundation' could not be executed.                                   [error]
Drush was not able to start (bootstrap) the Drupal database.                                    [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this
case you can select another site with a working database setup by specifying the URI to use with
the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have
no access to it in a jailed shell. See http://drupal.org/node/1428638 for details.

```

Drush was attempting to connect to:

> Drupal version : 7.32
> Site URI : http://linkengineering
> Database driver : mysql
> Database hostname : localhost
> Database port : 3306
> Database username : root
> Database name : drupal
> PHP executable : /usr/bin/php
> PHP configuration :
> PHP OS : Darwin
> Drush script : /Users/Marianna/.composer/vendor/drush/drush/drush.php Drush version : 8.1.3 Drush temp directory : /tmp
> Drush configuration :
> Drush alias files :
> Drupal root : /Users/Marianna/Documents/Sites/Link-New
> Drupal Settings File : sites/default/settings.php
> Site path : sites/default

# Answer
The issue mostly will be with environment/php and this is issue with MAMP (mismatch of path your MAMP-php and Server-php). Follow this link from that article.

> The Solution: A Symlink
>
> For the sake of ease, let’s just make your terminal sessions use the same PHP executable as MAMP. So run this:
>
> ```
> $ mv /usr/bin/php /usr/bin/php.bak
> $ ln -s /Applications/MAMP/bin/php/php5.5.3/bin/php /usr/bin/php
>
> ```

But you need to check path as per your folders.
> 2 votes

---
Tags: 7, theming, drush
---


title: How to update a field's value?

text:
# Question
Title: How to update a field's value?
Like the `field_get_items` function, is there a function to update a field's value? I want to update a field of type *user reference*.

# Answer
> 5 votes
In this example I load a node and change the value of a field called `field_context` and then saves the updated node:

```
$node = node_load($nid);
$node->field_context[$node->language][0]['value'] = 'foo';
node_save($node);

```

Use `var_dump` to show what fields your node contains.

# Answer
> 1 votes
You need to load your node, change it, and save it with `node_save($node)`.

# Answer
> 1 votes
Although the accepted answer works fine but a new and easier way is to use Entity API and its wrapper classes. You can find more info about Entity Metadata Wrappers here. Here is how the code would look like

```
$node_wrapper = entity_metadata_wrapper('node', $nid);
$node_wrapper->field_custom_field = 'foo';
$node_wrapper->save();

```

The wrapper will take care of validating your data as well.

---
Tags: 7, entities
---


# Question
Title: how to load custom Field Type into a custom Module (form)
I'm trying to make a set of field type (location field type which contain of: country, City, Address, Google map which store lat & long, etc.) and this 'set' of field i need to load into my custom module (form).

so if i have:

**FieldType**

```
<?php

/**
 * @file
 * Contains \Drupal\arm_main\Plugin\Field\FieldType\CustomField.
 */

namespace Drupal\arm_main\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface as StorageDefinition;

/**
 * Plugin implementation of the 'custom' field type.
 *
 * @FieldType(
 *   id = "custom",
 *   label = @Translation("Custom"),
 *   description = @Translation("Stores custom data."),
 *   category = @Translation("My Category"),
 *   default_widget = "custom_default",
 *   default_formatter = "CustomFieldDefaultFormatter"
 * )
 */

class CustomField extends FieldItemBase {

  const COUNTRY_ISO2_MAXLENGTH = 2;

  public static function propertyDefinitions(StorageDefinition $storage) {

    $properties = [];

    $properties['a'] = DataDefinition::create('string')
      ->setLabel(t('Label A'))
      ->setRequired(TRUE);

    $properties['b'] = DataDefinition::create('string')
      ->setLabel(t('Label B'))
      ->setRequired(TRUE);

    $properties['c'] = DataDefinition::create('string')
      ->setLabel(t('Label C'));

    $properties['d'] = DataDefinition::create('float')
      ->setLabel(t('Label D'));

    $properties['e'] = DataDefinition::create('float')
      ->setLabel(t('Label E'));

    $properties['f'] = DataDefinition::create('integer')
      ->setLabel(t('Label F'));

    return $properties;
  }

  public static function schema(StorageDefinition $storage) {

    $columns = [];
    $columns['a'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    $columns['b'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    $columns['c'] = [
      'type' => 'text',
      'length' => 255,
    ];

    $columns['d'] = [
      'type' => 'float',
      'size' => 'big',
      'default' => 0.0,
      'not null' => FALSE,
    ];
    $columns['e'] = [
      'type' => 'float',
      'size' => 'big',
      'default' => 0.0,
      'not null' => FALSE,
    ];
    $columns['f'] = [
      'type' => 'int',
      'length' => 10,
      'not null' => FALSE,
    ];

    return [
      'columns' => $columns,
      'indexes' => [],
    ];
  }

  public function isEmpty() {

    $isEmpty =
      empty($this->get('a')->getValue()) &&
      empty($this->get('b')->getValue()) &&
      empty($this->get('c')->getValue()) &&
      empty($this->get('d')->getValue()) &&
      empty($this->get('e')->getValue());

    return $isEmpty;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();

    $constraints[] = $constraint_manager->create('ComplexData', array(
      'value' => array(
        'Length' => array(
          'max' => static::COUNTRY_ISO2_MAXLENGTH,
          'maxMessage' => t('%name: the country iso-2 code may not be longer than @max characters.', array('%name' => $this->getFieldDefinition()->getLabel(), '@max' => static::COUNTRY_ISO2_MAXLENGTH)),
        )
      ),
    ));
    return $constraints;
  }

} // class

```

**FieldWidget**

```
<?php

/**
 * @file
 * Contains \Drupal\arm_main\Plugin\Field\FieldType\CustomFieldDefaultWidget.
 */

namespace Drupal\arm_main\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'custom_default' widget.
 *
 * @FieldWidget(
 *   id = "custom_default",
 *   label = @Translation("Custom"),
 *   field_types = {
 *     "custom"
 *   }
 * )
 */
class CustomFieldDefaultWidget extends WidgetBase {

/**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'size' => 60,
      'placeholder' => '',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['size'] = array(
      '#type' => 'number',
      '#title' => $this->t('Textfield size'),
      '#default_value' => $this->getSetting('size'),
      '#required' => TRUE,
      '#min' => 1,
    );
    $element['placeholder'] = array(
      '#type' => 'textfield',
      '#title' => t('Placeholder'),
      '#default_value' => $this->getSetting('placeholder'),
      '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();

    $placeholder = $this->getSetting('placeholder');
    if (!empty($placeholder)) {
      $summary[] = t('Placeholder: @placeholder', array('@placeholder' => $placeholder));
    }else {
      $summary[] = t('No placeholder');
    }
    $summary[] = t('Textfield size: @size', array('@size' => $this->getSetting('size')));

    return $summary;
  }

  public function formElement(FieldItemListInterface $items, $delta, Array $element, Array &$form, FormStateInterface $formState) {

    $countries = \Drupal::service('country_manager')->getList();

    $element['a'] = [
        '#type' => 'select',
        '#options' => $countries,
        '#empty_value' => '',
        '#default_value' => (isset($items[$delta]->value) && isset($countries[$items[$delta]->value])) ? $items[$delta]->value : NULL,
        '#description' => t('Description here'),
      ];

    $element['b'] = [
      '#type' => 'textfield',
      '#title' => t('Title B'),
      '#default_value' => isset($items[$delta]->b) ?
          $items[$delta]->b : null,
      '#empty_value' => '',
      '#placeholder' => t('B Here'),
    ];

    $element['c'] = [
      '#type' => 'textfield',
      '#title' => t('Title C'),

      '#default_value' => isset($items[$delta]->c) ?
          $items[$delta]->c : null,

      '#empty_value' => '',
      '#placeholder' => t('C Here'),
    ];

    $element['intro'] = [
      '#type' => 'markup',
      '#markup' => t('<strong>some text here...</strong>'),
      '#prefix' => '<div>',
      '#suffix' => '</div>',
    ];

    $element['d'] = [
      '#title' => t('Title D'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->d) ? $items[$delta]->d : NULL,
      '#empty_value' => 0,
      '#placeholder' => t('D Here'),
      '#attributes' => array(
        'data-d-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['e'] = [
      '#title' => t('Title E'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->e) ? $items[$delta]->e : NULL,
      '#empty_value' => 0,
      '#placeholder' => t('E Here'),
      '#attributes' => array(
        'data-e-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['f'] = [
      '#title' => t('Title F'),
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]->f) ? $items[$delta]->f : NULL,
      '#empty_value' => 7,
      '#placeholder' => t('F Here'),
      '#attributes' => array(
        'data-f-delta' => $delta,
        'class' => array('custom-field-watch-change'),
      ),
    ];

    $element['open_but'] = [
      '#type' => 'button',
      '#value' => t('Set button Marker'),
      '#attributes' => array(
        'data-delta' => $delta,
        'id' => 'but_setter_' . $delta,
      ),
    ];

    $element['clear_fields'] = [
      '#type' => 'button',
      '#value' => t('Clear Fields'),
      '#attributes' => array(
        'data-delta' => $delta,
        'id' => 'clear_fields_' . $delta,
        'class' => array('custom-field-clear'),
      ),
      '#suffix' => '</div>',
    ];

    $element['preview'] = [
      '#type' => 'item',
      '#title' => t('Preview'),
      '#markup' => '<div class="custom-field-preview" data-delta="' . $delta . '"></div>',
      '#prefix' => '<div class="custom-field-widget right">',
      '#suffix' => '</div>',
    ];

    return $element;
  }

} // class

```

how do i load it into FormBase programmatically in here:

```
class testCreateForm extends FormBase {

  public function __construct($coreService, $mainService) {      }
  public static function create(ContainerInterface $container) {      }
  public function getFormId() {      }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['someSample'] = array(
      '#type' => 'details',
      '#title' => t('Add new things'),
      '#description' => t('desc here'),
      '#open' => TRUE,
    );
    $form['someSample']['test'] = array(
      '#type' => 'textfield',
      '#title' => t('test'),
      '#description' => $this->t('Your test code'),
      '#default_value' => "",
      '#size' => 10,
      '#maxlength' => 8,
      '#required' => TRUE,
    );
    $form['someSample']['custom'] = array( // i did this but not work
      '#type' => 'custom',
      '#title' => t('Custom Title'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {      }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

```

# Answer
i found some tutorial here: https://docs.acquia.com/articles/drupal-8-creating-elements-theming-elements-and-managing-frontend-libraries

and it works to me, so generally all you need to build is an element class, define your element class, apply it to template then should be done.

if someone interested, i dont mind to write more detailed here

Thanks
> 0 votes

# Answer
The purpose of a field type is defining a field that is then attached to an entity. Once the field is attached to an entity, its widget will be used for entering the data, and its formatter will be used to show the entered data.

See for example the *email* field type. It's implemented by the `EmailItem` class; its default widget is implemented by the `EmailDefaultWidget`, which in `£mailDefaultWidget::formElement()` uses the following code.

```
  $element['value'] = $element + array(
    '#type' => 'email',
    '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
    '#placeholder' => $this->getSetting('placeholder'),
    '#size' => $this->getSetting('size'),
    '#maxlength' => Email::EMAIL_MAX_LENGTH,
  );
  return $element;

```

With a field type, you will never directly output it in a form. That is only the purpose of its widget.

If you want to just have something to use directly in a form, you need to implement a form input element, which is what Drupal does with the `Email` class, for example.

As in this case, a widget class for a field type can use the form input element defined from another class.
> 1 votes

---
Tags: 8, forms
---


title: Issues with PSR-0 in hook_cron

text:
# Question
Title: Issues with PSR-0 in hook_cron
after hours trying to solve this issue by myself and searching for solutions in Google I thought that maybe someone may already faced this.

Scenario: I am running `drush site-install` The installation goes well until it hits a hook\_cron (don't really know why) and tries to instantiate a a class. If I run `drush cron` on an installed site it works as a charm as is only when I am installing the site that this happens.

I use PSR-0 to bootstrap the namespaces and the implementation looks much like this:

```
/**
 * Implements hook_boot().
 */
function MY_MODULE_boot() {
  //Autoload classes PSR-0
  $namespaces = array(
    'COMPANY\MY_MODULE'     => array(__DIR__ . '/lib'),
  );
  MY_MODULE_register_class_namespace($namespaces);
}

/**
 * Registers a class namespace with the Composer autoloader
 *
 * @param  array  $namespaces
 */
function MY_MODULE_register_class_namespace(array $namespaces = array()){
  static $loader = null;
  if (!$loader) {
    $loader = require_once realpath('.') . '/vendor/autoload.php';
  }

  foreach ($namespaces as $namespace => $namespace_path) {
    $loader->add($namespace, $namespace_path);
  }
}

```

This is the error I get in the console:

```
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Class 'COMPANY\MY_MODULE\Repository\MYCLASSRepository' not found in
<path to module>, line 588

```

I would really appreciate any help with this one. Thanks in advance and sorry about my English.

# Answer
> 1 votes
Apparently there is an issue with the way Drupal bootstraps when doing a fresh install. I solved the issue by adding a call to:

```
module_invoke_all('boot');

```

Hope it helps you if you come up with the same issue.

---
Tags: drush, cron
---


title: Help with hook_views_pre_build()

text:
# Question
Title: Help with hook_views_pre_build()
I have set up a View to show a list of stories, and then set up an attachment to my View that puts the first 4 stories at the top of the View styled differently. I need those 4 to only show on the first page of items. Every other page will show the normal styling without the top 4. I have created a custom module using the following code. However, now every item is showing on one page. I have set number of items for the pager in the main view to 10 with an offset of 4, and in the attachment it is set to 4. Any suggestions?

```
<?php
/**
 * Implements hook_views_pre_build().
 */
function custom_stories_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {
    // if 'attachment_1' is not defined, we assume it is the first page.
    if (empty($_GET['attachment_1'])) {
      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      $item_num = $views->get_items_per_page() - $views->get_offset();
      $views->set_items_per_page($item_num);
    }
    else {
      // Remove attachment for other pages.
      $views->is_attachment = TRUE;
      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }
}

```

# Answer
EDIT

You can try the below code its working fine for me.

```
$views->items_per_page($item_num); instead of
$views->set_items_per_page($item_num);

```

Related questios

May be this can help you
> 0 votes

---
Tags: views, hooks
---


# Question
Title: How to send an email 1 minute after a node is created or updated by using a scheduled Rules Component?
So far, I've used Rules to unpublish a node 2 minutes after it is created or updated (testing for now). Now, I'm trying to send an email reminder to the node author 1 minute after the node is created or updated. So far, this is what I've done:

* Create rules component \>\> action set "***send email***":

+ Scheduled evaluation date: node:changed
    + add offset: 1 minute
    + User node reminder: node:source:author (i also tried node:author).
* Create new rule "schedule email publishing":

+ Event: After saving new content
    + Condition 1: content is of type: advertisement
    + Condition 2: content is published
    + Action: Schedule component evaluation: Rules Component: ***send email***.

What am I doing wrong?

# Answer
> 1 votes
There are a couple of things in your Rule and Rules Component that are either wrong, or should be simplified, such as:

* the scheduling part of it belongs in your Rule, not in your Rules component.
* nowhere you have an "identifier" for the task to be scheduled (each scheduled task requires an identifier).
* all your Rules Component should have to do, is to send an eMail to "some user" (= the node author in your case), indicated by a parameter of the component.
* what should happen if the same node is updated twice in say 30 seconds?

Read on for an example of a Rule and Rules Component to achieve what you're trying to do.

### Step 1:

Here is the Rules **Component** to be created (in Rules export format, just import it in your own environment via copy-paste):

```
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly eMail reminder (Subject)",
          "message" : "Friendly eMail reminder (Message body) ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Obviously, the ***Subject*** and ***Content*** of the eMail may need review / tuning, while you might also want to use some other ***From*** eMail ID.

### Step 2: Create a "Rule" using the Rules Component

Here is the **Rule** to be created, in Rules export format (just import it in your own environment via copy-paste, after you changed (twice) the machine name `article` to `advertisement` to fit your case; then change the rule from inactive to active):

```
{ "rules_send_email_reminder_to_node_author" : {
    "LABEL" : "Send email reminder to node author",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [ { "node_is_published" : { "node" : [ "node" ] } } ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[node:author]-[node:nid]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : "+1 minute",
          "identifier" : "[node:author]-[node:nid]",
          "param_user_to_notify" : [ "node:author" ]
        }
      }
    ]
  }
}

```

Note that this rule refers to the *Rules Component* from the previous step. And it also includes an extra Rules Condition that the node must be published (similar to the Rules Condition in your question).

The `schedule_delete` that is part of this rule is to ensure that previously "scheduled" eMails will get removed when updating a node multiple times during a very short period like 20 seconds. That way it only triggers 1 eMail, and related to the most most recent update (imagine you add some extra data from the node content to the message body, in that case you don't want to eMail outdated information, right?).

Also important is the identifier you use for these scheduled tasks. In this case I used `[node:author]-[node:nid]` (= "`author`", followed by a "`-`" and then the nodes's "`nid`"). That way you have a unique task identifier for every node of each author.

### Step 3: Review your timings

Rules Components scheduled for execution using `Rules Scheduler`, will actually be executed "next time cron runs" (after the scheduled date/time has arrived). So make sure to actually run cron and be patient enough for cron to have run.

Example: if you want to send the eMail after 1 minute, but cron only runs every 60 minutes, and the last cron ran 5 minutes ago, then you'll have to wait another 55 minutes before an attempt will be made for the eMail to be delivered.

---
Tags: 7, rules
---


# Question
Title: Can there be content sent the a vanilla Drupal 8 sites' views that isn't a node?
Is it possible to add content into views that is not searchable from google? I am trying to find out if the content sent to views has to be of a type node. (I think there are other modules for importing xml into views and such, but I am asking for just the vanilla views)

# Answer
You don't import things into a View; you configure a View with certain criteria, and that basically runs a query against the database, the results of which are formatted and rendered according to the rest of the View config.

It's not restricted to nodes, many entity types and pseudo-entity types can be queried, as Views is very extensible.

You mention *importing xml into views* \- in reality that happens by 2 separate processes - importing XML and creating content/entities from it, then setting up a View to display that content.

Don't think of a View as a container. It's essentially a sophisticated HTML report builder that knows how to get and format Drupal data.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to pass variables into link path within l() function?
I am wondering how to pass variables into a the path argument for a link created with `l()`. The path looks like `registration-history/listing/$node->nid/$sku/$node->created/$start_date` And the link text is in `$registration_count`.

# Answer
Some Examples

**Example 1: Link to front page**

```
<?php
// example 1:  front page
print l(t('Home'), '<front>');
?>

```

**Example 2: Link to front page and open in new window**

```
<?php
print l(t('Home'), '<front>',array('attributes'=>array('target'=>'blank')));
?>

```

**Example 3: How to use html**

```
<?php
print l('<span class="front">Home</span>', '<front>',array('html' => TRUE));
?>

```

**Example 4: How to use image instead of text link**

Lets create my picture path

```
<?php
global $base_url;
$path = "$base_url/sites/default/files/ceo5.png";
print l('<img src="'.$path.'" alt="Webemania CEO Image" />', 'sites/default/files/ceo5.png', array('html' => TRUE));
?>

```

**Example 5: Add class, ids, etc**

```
<?php
// add a new class to my php ini configuration path
print l(  t('PHP ini configuration'),  'node/3',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf') ));
?>

```

**Example 6: Adding query string to links**

Adding a query string to example 5

```
<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>

```

The output will be:

http://webemania.com/blog/php-ini-configuration?id=5&status=ok

**Example 7: Adding destination to query link**

```
<?php
print l(  t('edit'),  'node/'.$nid.'/edit',  array('query' => drupal_get_destination() ));
?>

```

**Example 8: Create a hash-only link (to #)**

```
<?php
print l('linktext', '', array('fragment' => ' ', 'external' => TRUE));
?>

```

**Example 9: Specific portions of a page**

Use fragment attributes Go to php ini configurations short open tag portion: PHP Short open tag

```
<?php
l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'fragment' => "php-tag")));
?>

```

**References:**

How and why to use l() function to create links in Drupal
> 6 votes

# Answer
For reference, the way I solved this question:

```
$url = "registration-history/listing/$node->nid/$sku/$node->created/$start_date";

return l(t("Link text"), $url, array('attributes' => array('nid' => 'node->nid')));

```

I don't know if this is the best way, but it works.
> 1 votes

---
Tags: 7, navigation
---


# Question
Title: how to load retrieve form value from custom element
i just done build a custom element based on this tutorial: https://docs.acquia.com/articles/drupal-8-creating-elements-theming-elements-and-managing-frontend-libraries

so let say my element type is "location"

so i have:

```
$form["location"] = [
      '#type' => 'location',
      '#label' => $this->t('Supplier Location'),
      '#theme' => 'supplier_location',
];

```

so inside type location there are a couple fields (e.g. textfield, select, etc.)

the problem here is: when i submit my form, i couldn't get those value:

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
        drupal_set_message($key . ': ' . $value); // i cant catch my custom element value here T_T why?
    }
  }

```

so apparently my custom element field value is not catched in submitform during submit, any idea why?

~~here is my custom element class code:~~ actually, below is the sample working code after discussion with @clive

```
<?php
/**
 * @file
 * Contains \Drupal\module\Element\Location.
 */

namespace Drupal\module\Element;

use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a location element.
 * @FormElement("location")
 */
class Location extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#element_validate' => [[$class, 'validateLocation']],
      '#process' => [[$class, 'processLocation'],[$class, 'processGroup']],
      '#pre_render' => [[$class, 'preRenderGroup']],
      '#theme' => 'location',
      //'#theme_wrappers' => ???, //what is theme wrappers?
    ];
  }

  /**
   * Prepare the render array for the template.
   */
  public static function processLocation(&$element, FormStateInterface $form_state, &$complete_form) {

    $countries = \Drupal::service('country_manager')->getList();
    $element['address'] = [
        '#type' => 'textfield',
        '#title' => t('Address: '),
        '#description' => t('Your Address'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your address here',
        ]
    ];

    $element['zip'] = [
        '#type' => 'textfield',
        '#title' => t('Zip: '),
        '#description' => t('Zip Code'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your Zip Code here',
        ]
    ];

    $element['city'] = [
        '#type' => 'textfield',
        '#title' => t('City: '),
        '#description' => t('Select City'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your city here',
        ]
    ];

    $element['state'] = [
        '#type' => 'textfield',
        '#title' => t('State: '),
        '#description' => t('Select State'),
        '#default_value' => "",
        '#size' => 136,
        '#required' => FALSE,
        '#attributes' => [
          'id' => 'id',
          'placeholder' => 'Enter your State here',
        ]
    ];

    $element['country'] = [
        '#type' => 'select',
        '#title' => t('Country: '),
        '#options' => $countries,
        '#default_value' => '',
        '#required' => TRUE,
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['latitude'] = [
        '#type' => 'hidden',
        '#title' => t('latitude: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['longitude'] = [
        '#type' => 'hidden',
        '#title' => t('longitude: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    $element['zoom'] = [
        '#type' => 'hidden',
        '#title' => t('zoom: '),
        '#default_value' => "",
        '#attributes' => [
          'id' => 'id',
        ]
    ];

    // Add the library
    $element['#attached'] = ['library' => ['module/arm_location_field_library']];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
      //what should i do here?
      return $input;
  }

  /**
   * Validation callback for a location element.
   *
   * @param array $element
   *   The form element whose value is being validated.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   */
  public static function validateLocation(&$element, FormStateInterface $form_state, &$complete_form) {
    //what should i do here?
  }

}

```

# Answer
Your form element needs to extend the `FormElement` class, rather than `RenderElement`.

Because of these few lines of code in `ElementInfoManager::buildInfo`:

```
// If this is element is to be used exclusively in a form, denote that it
// will receive input, and assign the value callback.
if ($element instanceof FormElementInterface) {
  $element_info['#input'] = TRUE;
  $element_info['#value_callback'] = array($definition['class'], 'valueCallback');
}

```

along with these in `FormBuilder::doBuildForm`:

```
// Handle input elements.
if (!empty($element['#input'])) {
  $this->handleInputElement($form_id, $element, $form_state);
}

```

more generic render elements won't be considered capable of providing input, and their values won't make it into the form state.

To fix (untested):

* Replace `use Drupal\Core\Render\Element\RenderElement` with `use Drupal\Core\Render\Element\FormElement`
* Replace `@RenderElement("location")` with `@FormElement("location")` in the annotation
* Change your class to extend `FormElement`: `class Location extends FormElement`
* Rebuild the cache
> 2 votes

---
Tags: 8, forms
---


# Question
Title: How to create a checkbox to turn-off/on email notifications each time when a node is published or updated?
How can I make a checkbox for turn-off/on sending e-mail notifications to users each time when I publish or change a node (in Drupal 7)? I mean, I don't need to send notifications each time I changed a node (or published it).

I used an editor interface in Drupal 6 (maybe earlier) and it included a similar checkbox: I could turn-off/on sending email notification to users. Here is a picture of it (last checkbox):

# Answer
> 0 votes
Unless you want to re-invent the wheel, you should have a look at the Message Stack, which does exactly what you are asking for (and much more ...). The Message Stack consists of these modules (quotes are from the module's project page):

* Message:

> The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.
* Message Notify.

> This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
* Message Subscribe.

> With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium.

If you want to have a closer look at the Message Stack and see it at work in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the *Answers Notification* sub-module, which allows logged in users to subscribe to selected questions (= nodes of content type "Question"), and so that they receive notifications (using the Message Stack) when Questions receive Answers (= nodes of content type "Answer").

# Answer
> 0 votes
You can easily do this using rule module. Follow below steps for your case:

1. Create a tern\_on\_off (Boolean type) field in the content type.
2. Create a rule with event update node and in condition add data comparson and compare tthe value of tern\_on\_off. and in the action add Send mail under System and add the data.

You are done.

---
Tags: 7, notifications, forms
---


# Question
Title: How to get delta of a file from within hook_tokens
I am trying to create a delta token in my module. In hook\_tokens, I manage to get the file object, but I have no clue on how to get the delta of my file...

Here is my implementation of hook\_token\_info

```
function artprod_token_info() {
  $types = array();
  $tokens = array();

  $types['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );
  $tokens['delta']['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );

  return array(
    'types' => $types,
    'tokens' => $tokens
  );
}

```

Here is the beginning of my implementation of hook\_tokens

```
function artprod_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'delta') {
    $file=$data['file'];
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'delta':
          $replacements[$original] = $file->delta();// NOT WORKING
          break;
      }
    }
  }
  return $replacements;
}

```

# Answer
Here is the solution I found:

Firstly, I have slightly rewrite the hook\_token\_info to "store" the field name of my file field in the token name:

```
function mymodule_token_info() {
  $types = array();
  $tokens = array();

  $types['delta'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of the field.')
  );
  //I name the token like my file field name for a futur use
  $tokens['delta']['field_my_file_field'] = array(
    'name' => t('Delta'),
    'description' => t('Provide the delta of field_my_file_field.')
  );

  return array(
    'types' => $types,
    'tokens' => $tokens
  );
}

```

Then in hook\_tokens: I get the fid of my file and I compare it with all the fid's values of $mynode-\>field\_my\_file\_field. When both fid matches, I use the delta for my replacement:

```
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'delta') {
    // Get the fid to compare with the field attached to my node
    $file_fid = $data['file']->id();
    // loop throught all the tokens
    foreach ($tokens as $name => $original) {
      // As the token name is also the name of the field,
      // I can loop the field values. This allow me to create
      // other tokens for other fields
      foreach ($data['node']->{$name} as $delta => $file_item) {
        // compare the value with the fid
        if ($file_item->getValue()['target_id'] == $file_fid) {
          //if it matchs, I can use this delta as a replacement
          //for my token (I add 1 as a personal choice)
          $replacements[$original] = $delta + 1;
        }
      }
    }
  }
  return $replacements;
}

```
> 0 votes

# Answer
It's the relationship between a file entity and another entity via a reference field that has a delta, not the file entity itself. A single file could, theoretically, be referenced by many entities, via multiple separate fields, or even twice in the same entity - meaning it doesn't conceptually have a single delta related to it.

What you'll need is to run an `EntityQuery` with sufficient contextual conditions to narrow down to one result, load up that parent entity, and loop through the field values until you find your file, giving you the delta.

If your use case enforces that a file can only be referenced by a single entity, it'll be a lot easier to implement. But it would probably be safer to include at least some kind of limiting.
> 2 votes

---
Tags: 8, tokens
---


title: Block not showing on page

text:
# Question
Title: Block not showing on page
I have a weird issue with a D6 site... A block I've created will not show up on the page. It appears to be disabled in the blocks list, although other blocks that /are/ showing up seem to be disabled as well. When I try to move it to a region, it jumps back to 'disabled' region.

Has anyone run into this issue and found a solution? Any help would be much appreciated!

# Answer
> 1 votes
Likely a different module is being used to control block display: Context or Panels would be the most likely options. It's possible someone wrote a custom module to disable blocks in the standard blocks interface to force you away from it.

*Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.*

---
Tags: 6, blocks, theming
---


# Question
Title: Associate one item of content with one taxonomy term
I have a view of type 'term' that displays in a grid, all the terms in a vocabulary. I need to display 2 images per term, but this is not possible I believe. (E.g. the taxonomy Image module only allows you to add one image per term).

So I thought maybe a solution to this would be to create another content type with one piece of content per term. And then associated each one with one of the vocabulary terms. And then create relationship in the view to link them. However I cant figure out how to get the view to do this. Is this possible?

# Answer
> 0 votes
It's possible, but not terribly easy in D6.

In Drupal 6 (unlike 7 and 8) vocabularies were not fieldable, so the approach you took is a reasonable one. You probably do not need a relationship in the view, just adjust the filter to include content types of the new type, and then use sorting to move the to the start or end of the result set. You could sort by content type or use the usually ignored "sticky" field on the nodes if its not in use (set all your new images to be sticky and then sort the list to place them where you want).

You could also create a block that uses the same filter pattern as the original view, but limit to the new content type and the only 2 results. Then place that block on the page that's displaying the grid.

*Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.*

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


# Question
Title: How to update a biblio field with Entity Metadata Wrapper?
I can update a field using Entity Metadata Wrapper (EMW). Here's how I can accomplish this.

```
$node_wrapper = entity_metadata_wrapper('node', $nid);
$node_wrapper->field_custom_field='new value';

```

However, I'm not able to access and update biblio fields provided by biblio module in the same way. This code won't work

```
 $node_wrapper->some_biblio_field='new value';

```

How can I update biblio fields using EMW?

# Answer
> 2 votes
The Bibliography module isn't using D7's field API. It's misleading since the module's manage fields UI (**/admin/structure/types/manage/biblio/fields**) does make it appear as if it's using the field API; however it installs its own database schema for storing data for Bibliography nodes.

As such, Entity API's EMW isn't much help in your case.

---
Tags: 7, entities
---


title: Completely removing cache

text:
# Question
Title: Completely removing cache
I've set `$settings['cache']['bins']['render'] = 'cache.backend.null;` and `$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null;` in local.settings.php, but I’m having a hard time dumping variables out to a page from a hook that runs once early on (`hook_entity_bundle_field_info_alter()`). If I do a simple var\_dump (or dpm, etc.) from here, variables will show up when running `drush cr` in the console, but not when hitting a new page in the browser afterwards. Does anyone know how I can set up debugging so I'm able to look at these variables in the browser?

# Answer
> 4 votes
What you did only uses the null backend render cache bins.

Field definitions are cached in the discovery bin, you either have to set that to null as well, but that will make your site very slow. You can also simply truncate `cache_discovery` manually in the database and then do another request in the browser.

# Answer
> 2 votes
As an addition to the great answer from Berdir for the specific problem this is for the more general question in the title:

You never have a completely cleared cache and it would nearly be impossible to remove all caching activities from drupal, because there are too many.

`drush cr` does not only clear caching tables, but also rebuilds all essential data drupal needs to organize itself like database schemas and routing. The code involving this is then not rerun on a request.

To get the debug output in the browser a simple solution would be to clear and rebuild the cache in the browser instead of drush.

But I found debugging these things with drush quite effective by reading the debugging messages in the console, make a quick change in code and run drush again.

---
Tags: 8, caching
---


# Question
Title: Creation of a Content Type to Meet Required Use Case
How do I achieve the following Use Case?

**Use Case Example**
Widgets, Inc. offers franchising opportunities. They have 3 different franchising levels (bronze, silver and gold).

Widgets, Inc. needs to create a Incident Report(Add New Content) any time an associated franchise has a problem.

They need 3 different types of Incident Reports(Content Types).

1. Bronze Incident Report
2. Silver Incident Report
3. Gold Incident Report

Each Incident Report contains two elements:

1. Text field for entering report
2. A static, uneditable list of Franchises within the same tier(Bronze, Silver and Gold)

The problem is in adding the second element. I am not sure how to do this. The second element represents a secondary data source, created from an HTML or PHP page.

# Answer
> 0 votes
The answer is: https://www.drupal.org/project/iframe

"A custom field, which lets you add a complete iframe to your content types; including Src-URL, setting width and height, optionally a title above, and optionally a target attribute."

This gives a user the ability to import data from a secondary source.

---
Tags: entities, javascript, hooks, external-scripts
---


# Question
Title: How to send an email to the admin when user fails to login?
I need to implement the functionality to notify the admin user via email whenever someone fails to login entering wrong password. Basically simple email format containing the username for failed account to login. Can someone give guidance or suggestion?

P.S: I checked the Rules module but it doesn't have required Rules event like "*When user fails to login*".

# Answer
> 2 votes
People mistype or use wrong alternate passwords all the time. Would be overkill to send e-mail on a first failed attempt.

**For security reasons, Drupal blocks user account after 5 login failed attempts.**

You can use Rules Block/Unblock User to send e-mail when user gets blocked. (failed 5 times)

> This module adds rules events, as well as some default rules, for when a user account is blocked or unblocked.

# Answer
> 1 votes
You can send mail only those user to whom has an data against the user name provided on login time. You can send mail using `hook_mail`. So on user login time you have to validate the data.

> 1. define a validation function using `form alter()`.
> 2. validate user authentication (how to validate)
> 3. if fail fetch user data and call `drupal_mail` function more info.

I hope it will help you

---
Tags: 7, forms, users, rules, hooks
---


# Question
Title: Accessing values entered in custom fields added to install_configure_form
In my installation profile, I have added a text field to the install\_configure\_form by including:

```
if (!function_exists("system_form_install_configure_form_alter")) {
  function system_form_install_configure_form_alter(&$form, $form_state) {
    $form['site_information']['site_name']['#default_value'] = st('Organization name');
    $form['site_information']['org_short_name'] = array(
      '#type' => 'textfield',
        '#title' => st('Short name'),
        '#description' => st('This will be used as a casual reference to the association throughout the site. If left blank, the Site name will be used.'),
      '#attributes' => ['placeholder' => 'e.g. FBI'],
        '#size' => 60,
        '#maxlength' => 60,
    );
    // Move the email to the bottom
    $form['site_information']['site_mail']['#weight'] = 1;
  }
}

```

Now, I'm trying to read and persist what the user entered using a \_submit function:

```
function my_profile_install_configure_form_submit(&$form, $form_state) {
  $values = $form_state['values'];
  $name = !empty($values['org_short_name']) ? $values['org_short_name'] : $values['site_name'];

  variable_set('short_name', $name);
}

```

Unfortunately, I don't think the `my_profile_install_configure_form_submit` function is getting called because the `short_name` is not getting created. How should I be accessing and persisting the custom elements in that form?

Thanks!

# Answer
> 0 votes
Altering the site configuration form is not different from altering other forms, as done from a module.

If myprofile.profile is used in your profile, its content should be similar to the following one.

```
  function myprofile_form_install_configure_form_alter(&$form, $form_state) {
    $form['site_information']['site_name']['#default_value'] = st('Organization name');
    $form['site_information']['org_short_name'] = array(
      '#type' => 'textfield',
        '#title' => st('Short name'),
        '#description' => st('This will be used as a casual reference to the association throughout the site. If left blank, the Site name will be used.'),
      '#attributes' => ['placeholder' => 'e.g. FBI'],
        '#size' => 60,
        '#maxlength' => 60,
    );
    // Move the email to the bottom
    $form['site_information']['site_mail']['#weight'] = 1;

    $form['actions']['submit']['#submit'][] = 'myprofile_install_configure_form_submit';
  }

  // Notice which argument is passed by reference.
  function myprofile_install_configure_form_submit($form, &$form_state) {
    $name = !empty($form_state['values']['org_short_name']) ? $form_state['values']['org_short_name'] : $form_state['values']['site_name'];

    variable_set('short_name', $name);
  }

```

As for `variable_set()` working in this case, it works, since `install_configure_form_submit()` (the default submission handler for the site configuration form) uses it.

```
  variable_set('site_name', $form_state['values']['site_name']);
  variable_set('site_mail', $form_state['values']['site_mail']);
  variable_set('date_default_timezone', $form_state['values']['date_default_timezone']);

```

---
Tags: forms, hooks, configuration, installation-profiles
---


# Question
Title: Discard views filter on field from referenced taxonomy term when relationship isn't present
I want to show two content types (A and B) in one view. 'A' has a relationship with a taxonomy term 'foo', 'B' doesn't have this relationship. So the relationship isn't required. However when I use a field from 'foo' as a filter in the filter criteria no nodes of content type B are shown, the nodes of content type A are shown correctly.

Is it possible to configure the view such that it doesn't look at the filter with the referenced field for nodes of content type B?

If something isn't clear, ask me!

Thanks!

# Answer
> 1 votes
Yes, you want to use *Grouped Filters* in Views. In the View UI, there's an *Add/Or, Rearrange* option next to the **Filter Criteria** section.

This allows you to create a complex grouping of filters. To use an example that matches your conditions, here's a setup using Drupal's Standard installation with *Basic Page*/*Article* nodes and *Tags* taxonomy that's exclusive to *Article*:

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


title: Resetting admin user details

text:
# Question
Title: Resetting admin user details
I forgot my drupal admin password and tried resetting it using forgot password option, but it fails to work( does not send the mail).

Drupal 8 is installed on my localhost. I tried manually editing the users table in the database, so I deleted the user with uid 1(admin) and also deleted corresponding data for uid 1 from users\_field\_data table.

I am unable to figure out the value to be inserted for uuid in users table. I tried giving 1 for uid, my\_name for uuid and md5(password), but the login fails. uuid seems to be encrypted somehow and i can't figure how.

Also, I am using wamp, so I haven't tried using drush or drupal console for version 8.

I found two relevant answers on topics " Insert “uuid” in “users” and Is there a good and recent documentation on the UUID API in Drupal 8 core? ", but not of much help.

# Answer
> 1 votes
You can't easily manually insert a user record. The password is not an MD5 hash, it a salted SHA-256 hash.

You hopefully made a backup, you should restore that. From there, you should consider to use drush, which is the by-far easiest way to log in, with drush uli to generate a one-time login link or drush upwd, to set the password of a user.

---
Tags: users, 8
---


# Question
Title: How to validate fields with the Rules module?
I have created a Rule with the Rules module to validate the form on submission.

I try to compare the values of two fields to ensure one not higher than the other. But I couldn't find the appropriate Rules Actions to stop the form submission and prompted an error message.

Please advise.

**Event:** After saving new content of type Article

**Condition:** Data comparison Parameter: Data to compare: \[node:field-price-A\], Operator: is greater than, Data value: \[node:field-price-B\]

**Actions: ??**

# Answer
> 3 votes
It sounds like you don't have the supporting module Rules Forms: https://www.drupal.org/project/rules\_forms

This module adds form validation for existing (core) forms and custom forms from contrib modules.

The documentation states that Rules Forms can:

Validate the values of form elements during form validation. Set form errors when rule-based validation fails.

# Answer
> 1 votes
Have a look at the Rules Forms Support module. More details about it (from its project page):

> Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
>
> For help getting started with Rules Forms Support, please see the module documentation.
>
> Features
>
> * Activate events for form creation, validation, and submission on a form-by-form basis.
> * Target individual form elements or the entire form in conditions and actions.
> * Manipulate the attributes of a form element like title, description, weight, and more.
> * Validate the values of form elements during form validation.
> * Set form errors when rule-based validation fails.
> * Redirect users to a different page upon viewing or submitting a form.
> * Examine the attributes of elements in active forms with the element inspection tool.

Especially the "***Set form errors when rule-based validation fails***" should help to address your question.

More details about how to use this module can be found in the community documentation "Altering & validating forms".

---
Tags: rules
---


# Question
Title: How to disallow selected roles to edit node titles?
In project I have a content type that the owner only allows to edit some fields. I used the Field Permissions module in order to configure field edit permission and it works fine in fields.

But this module doesn't support permissions for the "**TITLE**" field. In my project the default users & roles don't have permission to edit title and some fields.

Any recommendations for a solution for this issue?

# Answer
You could use the Title module

This converts the Title to fields API and should work with permissions as well. Basically it replaces the node title with a field
> 8 votes

# Answer
You could use the WikiTools module.

Among its features:

> Move Protection: Disallow change of node titles for users without administer nodes permission.

While it is only in alpha for D7, I am using it to protect titles on several sites, and have not experienced any problems.
> 3 votes

# Answer
Implementing such restrictions is pretty forward by using the Rules module. Here are the highlights of how to do so:

* Don't allow updates to the title of a node of type "Article" (replace by any other type you want).
* But do allow users with a specific role (such as "*administrators*", but it can be any role) anyhow. So updates to the title should be allowed by such role (only).
* If an attempt to update a title of an article is discovered by a user who does not have the administrator role, then just ignore the attempted update to the title (but do save all other updates to the node).

To implement this scenario, just use this rule for it:

```
{ "rules_verify_updates_to_node_title" : {
    "LABEL" : "Verify updates to node title",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "NOT data_is" : { "data" : [ "node-unchanged:title" ], "value" : "[node:title]" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Tampering rejected ... An attempt to update the title of node with ID \u0022[node:nid]\u0022 was discovered (from \u0022[node-unchanged:title]\u0022 to \u0022[node:title]\u0022), by user \u0022[site:current-user]\u0022, who does not have the authorization to do so. The attempted update of the title has not been saved (all other updates were applied).",
          "type" : "error"
        }
      },
      { "data_set" : { "data" : [ "node:title" ], "value" : "[node-unchanged:title]" } }
    ]
  }
}

```

If somebody who is not an administrator (the role that corresponds to role id = "3") tries the above scenario (with the above rule enabled), that user will get a Drupal error message similar like this one:

> Tampering rejected ... An attempt to update the title of node with ID "`X`" was discovered (from "Original title of this article" to "Attempted update of title of this article"), by user "`Some.Userid`", who does not have the authorization to do so. The attempted update of the title has not been saved (all other updates were applied).

Obviously, `X` and `Some.Userid` will be replaced by the actual node ID and username.

Works like a charm ... Similar approach for any other node property ... And straight forward to apply for any other content type (instead of "Article"), or just all content types.
> 0 votes

---
Tags: users
---


# Question
Title: How can I add a save button in my page variant?
I have created two variants of **user edit** page, one displays the entire form and other displays only a couple of fields of that form.

I have created a selection rule so that one triggers when is needed and other runs as default form mode.

But the problem is the first variant, which only have two fields doesn't have any save button.

This is what my panels look like:

This is what I did with that variant:

# Answer
> 0 votes
This is a known issue with recent activity =\> enter link description here

Solution:

After you apply the latest patch to ctools, you need to add a "User form actions / buttons" element to your page.

Your page variant should look sth like this:

And the rendered form now comes with a submit button:

Good luck!

---
Tags: 7, forms, panels, display-suite
---


title: Use a custom field with a custom entity

text:
# Question
Title: Use a custom field with a custom entity
How can I use a custom field with a custom entity?

Based on Drupal examples, how I can use `field_example_rgb` (from field\_example) in my own custom content entity with bundles?

I will add this field to the main entity table.

I tried the following.

```
$fields['rgb'] = BaseFieldDefinition::create('string')
    ->setLabel(t('RGB'))
    ->setDescription(t('RGB Color'))
    ->setSettings(array(
        'default_value' => '',
        'max_length' => 255,
        'text_processing' => 0,
    ))
    ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -5,
    ))
    ->setDisplayOptions('form', array(
        'type' => 'field_example_rgb',
        'weight' => -5,
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

```

I can install the module without errors, but when I create an new type and go to "Manage form display" I get the following error:

> Drupal\Component\Plugin\Exception\PluginNotFoundException: The "field\_example\_rgb" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

---

I don't know what was the problem, after make the module completely new I get no error. But I get a normal text field and not the "`field_example_rgb`".

I try to explain more in detail what I have made.

Create new module

```
drupal@server:~/public_html$ drupal generate:module
Enter the new module name:
> customfield
Enter the module machine name [customfield]:
>
Enter the module Path [/modules/custom]:
> /modules/testing
Enter module description [My Awesome Module]:
> Testing custom field
Enter package name [Custom]:
> Testing
Enter Drupal Core version [8.x]:
>
Do you want to generate a .module file (yes/no) [yes]:
>
Define module as feature (yes/no) [no]:
>
Do you want to add a composer.json file to your module (yes/no) [yes]:
>
Would you like to add module dependencies (yes/no) [no]:
> field_example_rgb
Do you confirm generation? (yes/no) [yes]:
>
Generated or updated files
Site path: /home/drupal/public_html
1 - modules/testing/customfield/customfield.info.yml
2 - modules/testing/customfield/customfield.module
3 - modules/testing/customfield/composer.json
drupal@server:~/public_html$ drupal generate:module

```

Create a custom content entity with bundles:

```
drupal@server:~/public_html$ drupal generate:entity:content
Enter the module name [customfield]:
>
Enter the class of your new content entity [DefaultEntity]:
> Test
Enter the machine name of your new content entity [test]:
>
Enter the label of your new content entity [Test]:
>
Enter the base-path for the content entity routes [/admin/structure]:
>
Do you want this (content) entity to have bundles (yes/no) [no]:
> yes
Is your entity translatable (yes/no) [yes]:
> no
Generated or updated files
Site path: /home/drupal/public_html
1 - modules/testing/customfield/customfield.permissions.yml
2 - modules/testing/customfield/customfield.links.menu.yml
3 - modules/testing/customfield/customfield.links.task.yml
4 - modules/testing/customfield/customfield.links.action.yml
5 - modules/testing/customfield/src/TestAccessControlHandler.php
6 - modules/testing/customfield/src/Entity/TestInterface.php
7 - modules/testing/customfield/src/Entity/Test.php
...
18 - modules/testing/customfield/customfield.module
// generate:entity:config
Enter the base-path for the config entity routes [/admin/structure]:
>
drupal@server:~/public_html$

```

Add only the following code to `modules/testing/customfield/src/Entity/Test.php`:

```
$fields['rgb'] = BaseFieldDefinition::create('string')
  ->setLabel(t('RGB'))
  ->setDescription(t('RGB'))
  ->setSettings(array(
    'max_length' => 50,
    'text_processing' => 0,
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'field_example_rgb',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

Install the module:

```
drupal@server:~/public_html$ drupal module:install customfield
Installing module(s) customfield
[OK] The following module(s) were installed successfully: customfield
// cache:rebuild
Rebuilding cache(s), wait a moment please.
[OK] Done clearing cache(s).
drupal@server:~/public_html$

```

Then I create a new type of Test an show for the RGB-Field, but i only get a textfield (see screenshot).

I'm on the wrong way? Is this not possible? I think it is ver uggly to gerate for every custom field a new table...

# Answer
> 1 votes
I'm not certain, but I think the reason why you are not given the option for the rgb widget on your field, is that your field is not an rgb field. I think you're creating a text field and calling it rgb.

You need to create a field of type "rgb". I suspect you want BaseFieldDefinition::create('rgb'), but have a look at the docs or a different example. You may well also need a "use" statement that refers to rgb.

---
Tags: entities, 8
---


# Question
Title: How to create a specific menu for specific users?
I'd like to know how can I create a menu like so:

* `Menu X` which appears when a `Member X` performs a login, for example when a simple user login, a Menu with 4 sections appears
* but when a `Member Y` (for example a user as manager) performs a login, instead of `Menu X` (= simple user menu), this time a `Menu Y` (menu manager with 7 sections) appears.

any suggestions?

# Answer
This you can do easily with Roles for Menu module.

> This module allows you to restrict access to menu items based on user roles. It is used when you don't want to copy your whole menu just because for one specific role you want to hide one menu item.

1. Define the user role (in your case X and Y) in your site.
2. Then as per user role you can set the menu items, so the menu will be automatically gets display based on Role.

Other similar module is Menu item visibility

> This module exposes configurable and extendable visibility settings for menu links.

Both does pretty much similar activity.

**Illustration for Menu item visibility module.**

*Steps:-*

**1.** **Module:** Download and enable the module.

**2.** **Creating User Role:** Now, for example you want to set two user role X and Y. Hence, create by going at People/Permission/Roles -\> add two user roles, like userX & userY as shown in following image.

**3.** **Creating a User:** Now, create two user, as shown in following image by going at People/ -\> add new user, and give corresponding role which we created in step-2. You can see all specifications in the image.

**4.** **Menu item creation:** I have created a 7 Menuitems in the section Main menu by going as Structure/Menus/Main menu.

Now, during the each Menu item creation, you will find the following option at the end of page, and from there selection, FOR WHICH USER YOU WANT TO SHOW THAT MENU-ITEM. Like in follwoing case we want to show Menuitem1 to userX and userY both.

I gave the user role visibility as below, because, I want to show first 4 item to userX Role and all other to userY Role.

```
Item               Roles Selection
Menuitem1     userX     userY
Menuitem2     userX     userY
Menuitem3     userX     userY
Menuitem4     userX     userY
Menuitem5               userY
Menuitem6               userY
Menuitem7               userY

```

**5.** **Test:** Now, if you Login using userXexample(which has useX role) you will see only four items, and for userYexample(which has userY role) you will see 7 items.
> 4 votes

# Answer
Basically, you create 2 menus. One menu with the links for regular/authenticated users and another menu for Administrator with the admin links.

Then go to blocks (`/admin/structure/block`) and find the menu blocks and click configure. Then set the visivility to the approprate user roles.
> 1 votes

---
Tags: 7, users, navigation
---


title: Set the value of a date field

text:
# Question
Title: Set the value of a date field
I am trying to set the value of a user field which is a date. If i check the database, the date is in this format:

2016-06-30T07:52:51

I have the user ID and a new Unix timestamp value that I want to overwrite the existing value with.

The following shows no error messages but does not change the date

```
$account = \Drupal\user\Entity\User::load($email_result); // pass your uid
$account->set('field_expiry_date',strval(date('c',($new_expiry))));

//$field = $account->field_expiry_date;
//$field->set(date('c',($new_expiry)));
//$field = $account->get('field_expiry_date');
//$field->setValue(date('c',($new_expiry)));

```

What is wrong with this code?

# Answer
> 6 votes
The problem is more than likely that the `'c'` format includes the timezone, which is not (currently) included in storage.

The storage format for fields that have both date and time is defined by the datetime module as `DateTimeItemInterface::DATETIME_STORAGE_FORMAT`, which is `'Y-m-d\TH:i:s'`.

Something like this will work:

```
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\Entity\User;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

$date = DrupalDateTime::createFromTimestamp($new_expiry, 'UTC');
$account = User::load($email_result);
$account->field_expiry_date->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
  'timezone' => 'UTC',
]);
$account->save();

```

Just remember that date+time values in storage are implicitly UTC, so if you are setting the value manually, you need to ensure that what you are saving represents what you want, but converted to UTC.

---
Tags: users, entities, 8
---


# Question
Title: New content pane (in view) not showing up for adding to panel
Added new content pane as part of my view. Even after saving, and clearing the cache, this pane is not showing up on the available panes list when adding content to Geary type panel/column in Drupal 7. Could this be a configuration issue?

# Answer
> 2 votes
Turns out you have to save prior changes to the panel in question. In the list of panels you'll see a padlock icon and a hover-caption of "you have locked this panel, until you save these changes."

Once you save the panel in question, you'll see new content panes that you've created in a View.

---
Tags: 7, views, panels
---


# Question
Title: How to calculate the average Fivestar rating correctly?
The anonymous visitors and registered users on my website can rate nodes through a comment with a Fivestar field. I display the average rating on the node's page. While testing this mechanism, I found out that the average isn't calculated correctly when multiple anonymous users vote with a comment. I suspect that only the last vote of a certain uid is taken into account: since all anonymous users have a uid equal to 0 - even if their name in the comment is different - they are considered as the same person.

In order to solve this problem, I did some research to how Fivestar calculates averages. All comments and corresponding votes of anonymous users are stored seperately in the database, so I can certainly use all the available information. I think that I also located the function in `fivestar.module` (lines 45-59) that calculates the average:

```
function fivestar_microdata_suggestions() {
  $mappings = array();

  // Add the review mapping for Schema.org
  $mappings['fields']['fivestar']['schema.org'] = array(
    '#itemprop' => array('aggregateRating'),
    '#is_item' => TRUE,
    '#itemtype' => array('http://schema.org/AggregateRating'),
    'average_rating' => array(
      '#itemprop' => array('ratingValue'),
    ),
    'rating_count' => array(
      '#itemprop' => array('ratingCount'),
    ),
  );

  return $mappings;
}

```

My situation is as follows: I use the average rating of a node in Rules and Views too, so I'm looking for an easy solution. Surely, I expect that I can calculate the correct average with Views or Computed Field, but implementing the usage of this average elsewhere could require quite a lot of adaptations.

Therefore, I would first like to ask you whether you have faced this problem as well. If so, how did you solve it? Is it possible to somehow "overwrite" the way Fivestar calculates averages programatically? I'm not familiar with how one uses schema.org or what information that website provides...

# Answer
> 0 votes
According to me, the insufficient support for anonymous voting is due to an underdeveloped Voting API (see my comment on this issue on drupal.org). Since I am not a professional programmer, I am not able to solve this matter on my own, so I looked for a workaround, using the Rules, Views and Computed Field modules. These are the main steps to solve the problem:

1. Create a comment View with all the comments on a node which have a non-zero voting field. Compute the average vote with aggregation.
2. Add a new computed field for nodes, which stores the result of the previously created View. The safest option is to add the code in a custom module (see the module's documentation).
3. In order to update the computed field from step 2, it is necessary to save the corresponding node again. To do that, I created a simple Rule which launches after a comment is edited or deleted.
4. Additionaly, if you want users to be allowed to vote only once, you can create a node Flag *Reacted* and Rules which (un)flag a node when (a comment is deleted) it receives a comment. Next, use `HOOK_form_comment_form_alter()` in your custom module to hide the voting field in the comment form when the current user has already flagged the actual node with *Reacted*.

---
Tags: 7, rating
---


# Question
Title: Where is the "Add fields" button on content types when using the Minimal installation profile?
I just installed Drupal 8.1.x and used the Minimal installation profile.

I added a new content type, but how do I add additional fields? I don't see a button anywhere.

# Answer
The minimal profile lives up to its name - the vast majority of modules aren't installed when using it.

This include the core Field UI module, which provides the UI you're missing. Just enable that module and you should see a "Manage fields" link as the default option in the table from your screenshot.
> 4 votes

---
Tags: 8, installation-profiles
---


# Question
Title: How to find/download latest drupal version via bash?
I'm trying to pull up the latest Drupal release, and download it via a bash script.

I don't have any idea on how I can do that, except that I found out I can list the files on the FTP server, and get all the filenames containing Drupal, like so:

```
lynx --dump http://ftp.drupal.org/files/projects/ | awk '/http/{print $2}' | grep drupal-7 > latest.txt

```

How I can pull the latest version from that list, and download it?

# Answer
> 3 votes
This command will do it.

```
wget  http://ftp.drupal.org/files/projects/$(wget -O- http://drupal.org/project/drupal | egrep -o 'drupal-[0-9\.]+.tar.gz' | sort -V  | tail -1)

```

Here goes the explanation.

```
wget -O- http://drupal.org/project/drupal |  # <- Download drupal main download site
    egrep -o 'drupal-[0-9\.]+.tar.gz' | # <- searching drupal-[0-9\.]+.tar.gz pattern
                                        # Also only showing the matched pattern
    sort -V  |  # <- sort it by version number (default sort order is ascending)
    tail -1  | grab the last name which would be highest version

```

After this we get something like `drupal-7.12.tar.gz` or `drupal-7.12.zip`. Then it gets replaced in the final `wget` invocation.

```
wget  http://ftp.drupal.org/files/projects/drupal-7.12.tar.gz

```

# Answer
> 8 votes
For all your command line and script needs there is Drush. To download the latest Drupal 7 with it, you simply do

```
drush pm-download drupal

```

# Answer
> 1 votes
If GNU grep is available and GET from perl's libwww, you can use the following, but it will fail if the format of their project page ever changes:

```
wget $(GET http://drupal.org/project/drupal | grep -Po '(?<=<a href=")http://ftp.drupal.org/files/projects/drupal-7[.]\d{1,2}[.]tar[.]gz(?=">tar.gz)')

```

# Answer
> 1 votes
The currently accepted answer no longer works after the update to the Drupal website.

This method utilizes the update XML and should hopefully be more reliable.

As stated in other answers, the best option is to use drush, but if that is not an option then this should do:

```
wget $(wget -O- -q https://updates.drupal.org/release-history/drupal/7.x | grep -oPm1 "(?<=<download_link>)[^<]+" | head -1)

```

Credit to this stackoverflow answer for the XML extraction: https://stackoverflow.com/a/17333829/2383249

# Answer
> 0 votes
I know @Shiplu's answer works best for OP, but just to add a comment; sometimes you may find it convenient to ask Apache which is the newest file:

```
$ wget 'http://ftp.drupal.org/files/projects/?C=M;O=A' -O- | egrep -o 'drupal-[0-9\.]+\.zip' | tail -1
(snip)
drupal-7.12.zip

```

The above URL was copied from the link labelled as "Last Modified". See also

# Answer
> 0 votes
If you can install (and don't mind installing) the nokogiri cli (e.g. `sudo apt-get install ruby-nokogiri` on ubuntu), you could do the following

```
nokogiri https://updates.drupal.org/release-history/drupal/7.x -e 'print @doc.at_xpath("//download_link/text()")'

```

which outputs

```
https://www.drupal.org/project/drupal/releases/7.50

```

---
Tags: files
---


title: Add sorting and filtering in code

text:
# Question
Title: Add sorting and filtering in code
I need to add sorting to a view in code but can't seem to get this to work. This is my code so far.

```
$view = Views::getView('name_of_the_view');
if (!$view) {
  // some irrelevant code to handle a non existing view
}
$view->setDisplay('name_of_the_display');
$view->setArguments([$searchString]);
$view->setCurrentPage($page);

$view->execute();

```

As far as I know, I need to add `$view->sort` and `$view->filter` before the execute method but don't know what to set this to.

Do I have to pass the name of the sort/filter handler (i.e. 'random') or the class name (i.e. Drupal\views\Plugin\views\sort\Random) or an instance of a sort/filter handler or something else?

# Answer
I was confused by `$view->setExposedInput` saying it accepts `$filters` as argument, but it actually works for sorting as well. So with that function you can set your exposed filters AND sorts

```
$view->setExposedInput([
  'your_filter' => $your_filter_value, //your exposed filter
  'sort_by' => 'your_field', //your exposed sort
  'sort_order' => 'ASC',
]);

```

Use above code before you execute view.

And make sure you exposed your filters and sorts in your view.
> 4 votes

# Answer
`Views::getView()` returns a `ViewsExecutable` object for which the following public properties are defined:

So, to add a filter in the view you loaded, you should use `$views->filter[] = $filter_object`.
> 1 votes

---
Tags: views, 8
---