title: Dynamically adding fields to form

text:
# Question
Title: Dynamically adding fields to form
I'm trying to create a form in which you can fill in user names. I want to dynamically add new textfields by pressing a button. I based my code on the following question (because it also uses Drupal 8 and supposedly should work).

However, unfortunately it doesn't add the fields. The code I'm using currently looks like this:

```
<?php
    /**
     * @file
     * Contains \Drupal\bulk_email\Form\EmailForm.
     */

    namespace Drupal\bulk_email\Form;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Component\Utility\UrlHelper;

    class EmailForm extends FormBase {
        public function getFormId() {
            return "bulk_email_form";
        }

        public function buildForm(array $form, FormStateInterface $form_state) {
            $form['#tree'] = TRUE;

            $form['users'] = array(
              '#type' => 'fieldset',
              '#title' => t('Users'),
              '#prefix' => '<div id="users-wrapper">',
              '#suffix' => '</div>',
            );

            $num_users = $form_state->getValue('num_users');
            if (empty($num_users)) {
                $num_users = 1;
            }
            for ($i = 0; $i < $num_users; $i++) {
                $form['users'][$i] = array(
                    '#type'  => 'textfield',
                    '#description' => t('Select a user.'),
                );
            }

            $form['users']['users_more'] = array(
                '#type' => 'submit',
                '#value' => t('Add one'),
                '#submit' => array($this, 'bulk_email_addfieldsubmit'),
                '#ajax' => array(
                     'callback' => array($this, 'bulk_email_add_more_callback'),
                     'wrapper' => 'users-wrapper',
                ),
            );

            $form['actions'] = array('#type' => 'actions');
            $form['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Send'),
            );
            return $form;
        }

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

        public function bulk_email_addfieldsubmit(array &$form, FormStateInterface $form_state) {
            $num_users = $form_state->get('num_users') + 1;
            $form_state->set('num_users', $num_users);
            $form_state->setRebuild(TRUE);
        }

        public function bulk_email_add_more_callback(array &$form, FormStateInterface $form_state) {
            return $form['users'];
        }
    }
?>

```

I'm most likely missing a small detail, but I can't seem to find it... Any help is appreciated.

# Answer
> 1 votes
Did you check if the submit is called in your ajax request?

```
public function bulk_email_addfieldsubmit(array &$form, FormStateInterface $form_state) {
    $num_users = $form_state->get('num_users') + 1;
    $form_state->set('num_users', $num_users);

```

If not, you can put this code in `buildForm()`. In this case you need to check if the triggering element is the correct one.

And another small issue, this line in `buildForm()`:

```
$num_users = $form_state->getValue('num_users');

```

Should be `get('num_users')`, because `getValue()` is for user input.

# Answer
> 1 votes
you can use something like this.

```
if (!empty($form_state['values']['field_name'])) {
    $form[]=array();//add your form elements to be shown after submit.
}
else {
    $form[]=array();//here your original form.
}
return $form;

```

in your form submit add

```
$form_State['rebuild']=true;

```

# Answer
> 1 votes
I did not find any solution to my problem and start to wonder whether it' a bad design decision or a bug.

Anyway, for other users, I used the following workaround:

First of all I removed all the code on adding these extra field. I only kept the actual text field where you enter the username. Then I added a new hidden field called user-collection.

The rest was done by adding a custom javascript. This script would detect wheteher a username has been entered (based on the autocomplete). It would then add ";" to the value of user-collection. It then clears the textfield. The result is a user-collection field, containing all the usernames entered. I finally also added a visual feedback which showed the content of user-collection (after some parsing).

It's only a work around and took me quite some effort as well, but it's better than nothing.

# Answer
> 1 votes
I might be wrong but you can also try changing the ajax callback to, assuming bulk\_email\_add\_more\_callback is not actually called.

```
'#ajax' => array(
                 'callback' => '::bulk_email_add_more_callback',
                 'wrapper' => 'users-wrapper',
            ),

```

And then in the actual callback get your values from the completeform. This was my problem, all values where correct but then I returned the old values.

```
public function bulk_email_add_more_callback(array &$form, FormStateInterface $form_state) {
        $form = $form_state->getCompleteForm()
        return $form['users'];
    }

```

# Answer
> 1 votes
i also have the same scenario. i can add and remove the textfields dynamically sucessfully using ajax in drupal 8. i attached the code below . actually i think you are following the examples fapi module and using add more form right?

there is some issue in fapi add more form in drupal 8. and patch is also there. so my self corrected the code for my scenario.

**First step :** we are working behind the logic of formstate variables . the value of formstate variables we may add or subtract the fields dynamically .

you need to set **$form\['#tree'\] = TRUE;** property when initial build form function.then only you can get proper submitted values in submit function.

```
$veritas_id = $form_state->get('veritas_id');
if ($veritas_id === NULL) {
  $veritas_id = $form_state->set('veritas_id', 0);
  $veritas_id = 0;
}

```

**Second step**

```
$form['veritasIds'] = [
  '#type' => 'fieldset',
  //'#title' => $this->t('#ID'),
  '#prefix' => '<div id="veritas-id-wrapper">',
  '#suffix' => '</div>',
];

  $form['veritasIds']['actions']['add_name'] = [
    '#type' => 'submit',
    '#limit_validation_errors' => array(),
    '#value' => t('add row'),
    //'#name'=>$veritas,
    '#submit' => array('::addOneVeritas'),
    '#ajax' => [
      'callback' => '::addmoreCallbackVeritas',
      'wrapper' => 'veritas-id-wrapper',
    ],

    '#attributes' => array('class'=> array('btn-transparent')),
  ];

  $form['veritasIds']['actions']['remove_name'] = [
  '#type' => 'submit',
  '#limit_validation_errors' => array(),
  '#value' => t('delete row'),
  '#submit' => array('::removeoneVeritas'),
  '#ajax' => [
    'callback' => '::addmoreCallbackVeritas',
    'wrapper' => 'veritas-id-wrapper',
  ],
  '#name'=>t('veritasremove'),

  '#attributes' => array('class'=> array('btn-transparent')),
  '#suffix' => t('<div class="id-wrapper">#ID</div>'),
  ];

  for ($i = 0; $i < $veritas_id; $i++) {
    $form['veritasIds']['id_' . $i] = [
      '#type' => 'textfield',
      '#attributes' => array('class'=> array('veritas-addfield')),
      //'#title' => t('Name'),
    ];
  }

```

here am created a fieldset . inside the fieldset only add row more and delete more button and added dynamic fields will be there.

**third step** $form\_state-\>setCached(FALSE); is needed submit and ajax callback functions will be

```
public function addmoreCallbackVeritas(array &$form, FormStateInterface $form_state) {
  $form = $form_state->getCompleteForm();
  return $form['veritasIds'];

```

}

```
public function addOneVeritas(array &$form, FormStateInterface $form_state) {
    $veritas_id = $form_state->get('veritas_id');
    $add_button1 = $veritas_id + 1;
    $form_state->set('veritas_id', $add_button1);
    $form_state->setRebuild();
  }

```

feel free to ask any doubts in this

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


# Question
Title: How do I fix the following security issue that were reported from a security check?
After running some security checks on my website with *Detectify & Tinfoil*, I'm faced with some concerns.

There seem to be a lot of security issues that I thought were covered by Drupal, and I'm unsure if I should be concerned with those or if there is a second layer of security that the scans are not checking.

The main vulnerabilities found by the scans are the following.

### CSRF vulnerabilities

On /login, /user/password, and /user/register should not core security protect these pages? It seems like a big vulnerability for standard core pages. This even after the website is HTTPS Only, following the steps found here.

### Exposed web.config and robot.txt

On root, is this something that I should obfuscate? I've found articles on files that should be removed from root (such as update.php) on a Drupal 8, but nothing on web.config and robot.txt protection.

### TLS 1.0 Deprecated

Is there a way to change this?

### XSS vulnerability/missing SRI (through Bootstraps cnd.jsdelivr/ 3rd party jquery CORS)

Is there a hook that can be implemented in this situation? Everything I tried so far has broken the website design, it seems that without going through Bootstraps CND Provider it misses the proper connections and i don't see a way to hash/secure Bootstraps' request.

I've seen quite a lot of documentation on Drupals' community about all these subjects, but (besides lot of content being for Drupal 7, which I'm not sure it applies for Drupal 8) I'm struggling to understand it.

Should I be worried of other possible vulnerabilities that the scan didn't flag?

# Answer
This is not a complete answer to all of your questions, but I hope to take some of your concerns away.

* CSRF protection for anonymous forms is not considered a vulnerability per this article. But that article recommends the seckit module for enforcing CSRF if you need it.
* The use of TLS is a server setting, not related to Drupal.
* `robots.txt` needs to be exposed to have crawlers detect it.
* `update.php` is protected by the session by default (user has to be logged in to use it, though this can be turned off in settings.php).

All of the above should not be an issue.

The usage of `web.config` might be an issue (I am no windows server expert), but to my understanding it is at the same level as `.htaccess` for Apache. These files do not form a security issue per sé, but improper use of them can. web.conmfig files can for instance be used to store passwords for folder or database access. Drupal uses it to do some redirects and to prevent access to several folders and files. (No new info to your attacker since he already knew of those files because of the generator meta tag.)

So summarizing, Drupal might not always use best practices (though in a quick search, I did not find any info on what would be a better location for web.config), Drupal's focus is on maximizing compatibility and working out of the box, but that does not make it unsafe.
> 1 votes

---
Tags: 8, security
---


title: Drush 8 database connection issue

text:
# Question
Title: Drush 8 database connection issue
I'm having trouble connecting to my databases. It worked a few days ago but can't seem to figure why it doesn't work now. It's a D8-site. Drush version is 8.1.12.

I've double-checked both the alias-file and settings.php-files (both on server & local) and database settings all appear correct. My local site runs on Mamp 4.1.1. and network access is allowed.

Here's the error I get when running sql-sync `drush sql-sync @local @dev`. Rsync works fine.

```
Unable to load class Drush\Sql\Sql                                                                                [error]
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your database connection details.' in /vendor/drush/drush/commands/sql/sql.drush.inc:541                [error]
Stack trace:
#0 /vendor/drush/drush/commands/sql/sql.drush.inc(252): drush_sql_get_class()
#1 [internal function]: drush_sql_dump()
#2 /vendor/drush/drush/includes/command.inc(422): call_user_func_array('drush_sql_dump', Array)
#3 /vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#4 [internal function]: drush_command()
#5 /vendor/drush/drush/includes/command.inc(199): call_user_func_array('drush_command', Array)
#6 /vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#7 /vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#8 /vendor/drush/drush/drush.php(12): drush_main()
#9 {main}
sql-dump failed.

```

And here's the aliases.drushrc.php (my local copy of course includes credentials:))

```
<?php

/* Tambourhinoceros Site */

$aliases["local"] = array (
 'root' => '', // local path
 'uri' => 'local.tambourhinoceros.net',  // local uri
 'path-aliases' =>
 array (
   '%dump-dir' => '/tmp',
   '%drush' => '/usr/local/bin',
   '%site' => 'sites/default',
 ),
 'remote-user' => 'tamb_dev',
 'ssh-options' => '-T',
 'databases' =>
 array (
   'default' =>
   array (
     'default' =>
     array (
        'database' => '', // local database
        'username' => '', // local database user
        'password' => '', // local database pw
        'host' => 'localhost',
        'port' => '8889',
        'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
        'driver' => 'mysql',
        'prefix' => '',
      ),
    ),
  ),
);

$aliases["dev"] = array (
  'root' => '', // remote path
  'uri' => 'drupal-85630-297475.cloudwaysapps.com', // remote uri
  'path-aliases' =>
  array (
  ),
  'remote-host' => '', remote IP
  'remote-user' => '', remote User
  'command-specific' =>
 array (
   'rsync' =>
   array (
     'mode' => 'rlptzO',
     'verbose' => true,
     'no-perms' => true,
   ),
 ),
 'databases' =>
 array (
   'default' =>
   array (
     'default' =>
     array (
        'database' => '', remote database
        'username' => '', remote  user
        'password' => '', remote pw
        'host' => 'localhost',
        'port' => '',
        'driver' => 'mysql',
        'prefix' => '',
      ),
    ),
  ),
)
?>

```

# Answer
Solved. And as usual the issue turned out to be much smaller and simple than I thought...

My local path was missing the "/web" segment in the end. After adding it both rsync and sql-sync works!

Thanks for all the input people.
> 1 votes

# Answer
It will be Solved by adding

```
--root=/full/path/to/your/webroot

```

to the drush command.
> 1 votes

# Answer
On your local connection, try adding "unix\_socket" option and point to your local mysql socket.

```
$databases['default']['default'] = array (
  'database' => '',
  'username' => '',
  'password' => '',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
  'unix_socket' => '/var/mysql/mysql.sock',
);

```

More complete steps to debugging: https://drupal.stackexchange.com/a/174128/25221
> 1 votes

---
Tags: database, drush
---


# Question
Title: What is the right way to get number of items from a field?
In code review I saw a developer using count($paragraph-\>field\_events) to get the number of referenced entities.

I thought, surely that can't work, that can't be right. So the question is, what is the correct way to get the number of items from a field on an entity?

# Answer
Using count() on a field is acceptable because there is an implementation of Countable::count in the ListInterface implemented by ItemList class where it overloads the count method to count the items, from which FieldItemList and EntityReferenceFieldItemList inherit.

So you can use:

```
$paragraph->field_events->count()

```

or

```
count($paragraph->field_events)

```

synonymously. They do the same thing.

From ItemList.php:

```
public function count() {
  return count($this->list);
}

```

If you'd like test this, you can play with this simple class. If you remove the "Implements Countable" calling count(a) on object a doesn't return the count() method, but if you add it back, it does. So on a low level, Drupal is using this so you can call count() on fields.
> 10 votes

---
Tags: 8, entities
---


# Question
Title: Entity Reference saved in database but null on `$entity->get('entity_reference_id')`
I'm having a very bizarre issue with an entity relationship in my models. I have 4 entity classes within Drupal: `DogEntity`, `BaseAnimalEntity`, `BaseToyEntity`, `DogToyEntity`. The following entity relationship is expressed: `DogEntity` -\> `DogToyEntity`.

I can see that the `DogEntity` table has a concrete value in the `DogToyEntity` column of the database. However, when I load the `DogEntity` entity, and then try to load the `DogToyEntity` from the `DogEntity`'s id it returns a `null` value. I don't understand why this is happening.

Below are the class definitions for the classes:

BaseAnimal Class:

```
abstract class BaseAnimal extends ContentEntityBase implements BaseAnimalInterface {
    /**
     * Everything is implemented correctly, the entity is created correctly
     * So I'm leaving stuff out for brevity
     */

    public function getArbitraryField() {
        // all getXFunctions follow the form: $this->get('value')->value;
        return $this->get('arbitrary_field')->value;
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields = parent::baseFieldDefinitions($entity_type);

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('The ID of the entity.'))
            ->setReadOnly(TRUE);
        // Standard field, unique outside of the scope of the current project.
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('The UUID of the entity.'))
            ->setReadOnly(TRUE);

        // elided other fields for brevity.

        return $fields;
    }
}

```

Dog Class:

```
/**
 * @ContentEntityType(
 *   id = "dog"
 *   ... eliding
 */
public class Dog extends BaseAnimal implements DogInterface {
    /**
     * Everything is implemented correctly, the entity is created correctly
     * So I'm leaving stuff out for brevity
     */

    public function getOtherArbitraryField() {
        // all getXFunctions follow the form: $this->get('value')->value;
        return $this->get('other_arbitrary_field')->value;
    }

    public function setDogToy(int $value) {
        $this->set('dog_toy_id', $value);
        return $this;
    }

    public function getDogToy() {
        return $this->get('dog_toy_id')->value;
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields = parent::baseFieldDefinitions($entity_type);
        $fields['dog_toy_id'] = BaseFieldDefinition::create('entity_reference')
            ->setLabel(t('Dog Toy'))
            ->setDescription(t('Dog\'s favorite toy.'))
            ->setSetting('target_type', 'dog_toy')
            ->setSetting('handler', 'default')
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'weight' => -3,
              ))
            ->setDisplayConfigurable('view', TRUE);
        return $fields;
    }
}

```

Base Toy Class:

```
abstract class BaseToy extends ContentEntityBase implements BaseToyInterface {
    /**
     * Everything is implemented correctly, the entity is created correctly
     * So I'm leaving stuff out for brevity
     */

    public function getArbitraryField() {
        // all getXFunctions follow the form: $this->get('value')->value;
        return $this->get('arbitrary_field')->value;
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields = parent::baseFieldDefinitions($entity_type);

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
            ->setLabel(t('ID'))
            ->setDescription(t('The ID of the entity.'))
            ->setReadOnly(TRUE);
        // Standard field, unique outside of the scope of the current project.
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
            ->setLabel(t('UUID'))
            ->setDescription(t('The UUID of the entity.'))
            ->setReadOnly(TRUE);

        // elided other fields for brevity.

        return $fields;
    }
}

```

Dog Toy Class:

```
/**
 * @ContentEntityType(
 *   id = "dog_toy"
 *   ... eliding
 */
public class DogToy extends BaseToy implements DogToyInterface {
    /**
     * Everything is implemented correctly, the entity is created correctly
     * So I'm leaving stuff out for brevity
     */

    public function getOtherArbitraryField() {
        // all getXFunctions follow the form: $this->get('value')->value;
        return $this->get('other_arbitrary_field')->value;
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
        $fields = parent::baseFieldDefinitions($entity_type);
        // Unnecessary fields elided for brevity.
        return $fields;
    }
}

```

So these entities are created and work correctly. The problem comes when I do something like:

```
$dog = Dog::create($fields);
$dog->save(); // now has ID of 1.

// do some other things...

$toy = DogToy::create($other_fields);
$toy->save(); // now has ID of 1.

// do some other things...

$dog->setDogToy($toy->id());
$dog->save();  // Now Dog->dog_toy_id = 1.

```

The above works perfectly. The database will be populated with the appropriate relationship, and I'm happy.

Then I'll try to do something like:

```
$dog = Dog::load(1); // loads correctly
var_dump($dog); // In here, the value of dog_toy_id is set correctly to 1, see above.
$toy = DogToy::load($dog->getDogToy());
var_dump($toy); // and $toy will be NULL

```

I've tried several sorts of seemingly trivial troubleshooting, debugging, etc. But I don't understand what is happening. I can see that `dog_toy_id` is set within the `Dog` class and that the column has a `1` on the `Dog` table. Something is happening in that `Toy::load()` and I don't understand what it is.

# Answer
The entity reference field has no `value` property. Use `target_id` in `Dog::getDogToy()` instead:

```
public function getDogToy() {
    return $this->get('dog_toy_id')->target_id;
}

```

Or `entity` to get the entity directly:

```
public function getDogToy() {
    return $this->get('dog_toy_id')->entity;
}

```

Then you don't need to load the DogToy entity:

```
$toy = $dog->getDogToy();

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Rule should not fire when user logs in with one-time-link from password recovery
I have a rule for user-login that redirects them to their content area and shows a welcome message with some instructions. But when a user uses the password recovery mechanism that rule should not fire. I have tried "path has URL alias" and "user/reset/\*" as value. But it did not work. I can't figure out what else i could use.

Reason is: users need their current password, which they don't know, when they are going manually to their user/n/edit page. When the rule wouldn't fire they'd be redirected to the correct password reset page without the current password requirement.

Thanks!

# Answer
You may want to give this a try:

* Rules Event: User has logged in.
* Rules Condition: Text Comparison with
    + Text Data Selector = `site:current-page:path`
    + Matching Text = `reset`
    + Comparison Operator = `contains`
* Rules Action(s): whatever makes sense.

I'm not 100% sure about the value of the "Matching Text" (if it's not `reset`, then adapt that value to something that fits for these kinds of one time login URLs).
> 3 votes

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


# Question
Title: Content Aware Caching for Commerce Related Views
Views Content Cache Project Page reads

> This module implements a views cache plugin that is aware of content and can provide caching for views, until the content in those views changes.

Do we have an equivalent for `Drupal Commerce`. So that when I have a view listing of Commerce Orders or Products, I can provide caching until the content(orders or products) in those views changes.

# Answer
The list of products uses Views, so in theory the module should work for views in admin/structure/views/view/commerce\_products
> 1 votes

---
Tags: commerce, caching
---


# Question
Title: How to get product variations inside webforms?
I have a product, `A`, `B`, `C` ... variations `foo`, `bar`, `tar`...

I am showing all three products in a url like `drupal.dev/all-products`.

I managed to display all three products via a webview. Now below these products I am making a webform to handle submissions, and in this webform I would like to be able to show all product variations, but there seems to be no way to fetch product variations in webforms.

How can I go about doing this?

# Answer
> 0 votes
You should be able to use the hook\_form\_alter() to achieve this in a custom module. As long as there is a relationship between the product and its variations you can use the hook\_form\_alter to add and remove variations from the form. You could also use the module controller to generate a custom twig template that renders content pull from the DB.

hook form alter - https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook\_form\_alter/8.4.x

custom twig template - https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

custom webform twig template - How to access webform elements in webform.html.twig

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


title: Create a link pointing to #

text:
# Question
Title: Create a link pointing to #
I am trying to make a link pointing to # but am unable to find a method that works.

The output i would like to see is

```
<a href="#">Example</a>

```

I have tried a few variations of the following without success.

```
$url = Url::fromUserInput('#');
$link_item = Link::fromTextAndUrl(t('Example'), $url);
return $link_item->toRenderable();

```

I have also tried using ::fromUri etc and am unable to find a method that produces tehd esired output, please help.

# Answer
> 8 votes
It's probably not possible to attach an empty fragment. See this code in `UrlGenerator::generateFromRoute()`:

```
if (isset($options['fragment'])) {
  if (($fragment = trim($options['fragment'])) != '') {
    $fragment = '#' . $fragment;
  }
}

```

If the fragment is empty it is ignored and no '#' shows up. This doesn't change if you provide the fragment in `Url::fromUserInput()`, because the fragment is transfered to the options and later processed by the same or similar code.

So you have to provide an anchor in the fragment:

```
$url = Url::fromUserInput('#anchor1');

```

or

```
$url = Url::fromRoute('<current>', [], ['fragment' => 'anchor2']);

```

As alternative option you can place a link with an empty fragment

```
<a href="#">{{ examplevariable }}</a>

```

either in a twig template or in an inline template in php.

# Answer
> 0 votes
The following code:

```
$link = \Drupal\Core\Link::fromTextAndUrl(
          t('Example'),
          \Drupal\Core\Url::fromUserInput('#', ['fragment' => '#'])
        )->toString();`

```

will return:

> `<a href="##">Example</a>`

---

Here is the example to return a custom path:

```
\Drupal\Core\Link::fromTextAndUrl(t('Example'), \Drupal\Core\Url::fromUri('base:/some/path'))->toString();

```

which returns:

> `<a href="/some/path">Example</a>`

---
Tags: 8, navigation
---


title: How to use grid widget in Drupalgap?

text:
# Question
Title: How to use grid widget in Drupalgap?
I cannot reproduce the grid widget. The page shows nothing except the title. Here is my code:

```
/**
 * Implements hook_menu()
 */
function test_grid_menu() {
  var items = {};
  items['test_grid'] = {
    title:'test grid',
    page_callback: 'test_grid_page',
  };
  return items;
}

function test_grid_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;
}

```

I also tried to put the theme('jqm\_grid', ...) in the page\_callback, but it does not work.

```
function test_grid_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;

var html = theme('jqm_grid', {
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
});
return html;

}

```

I place the jQuery Block code in the page\_callback. The page display is fine as expect, but the linking is a problem.(cannot reach the localhost node) It seems this can only give good display but without the function. (in my following code, search and the linking have no function).

```
function test_grid2_page() {

var  html = '<div><form><label for="search-1">Search:</label>';
     html += '<input type="search" name="search-1" id="search-1" value=""></form></div>';
     html += '<div class="ui-grid-b">';
     html += ' <div class="ui-block-a"><div class="ui-bar ui-bar-a" style="height:90px"><a href="javascript:drupalgap_goto("node/966");">Foo</a></div></div>';
     html += ' <div class="ui-block-b"><div class="ui-bar ui-bar-a" style="height:90px">Bar</div></div>';
     html += ' <div class="ui-block-c"><div class="ui-bar ui-bar-a" style="height:90px">Baz</div></div>';
     html += ' <div class="ui-block-a"><div class="ui-bar ui-bar-a" style="height:90px">Chop</div></div>';
     html += ' <div class="ui-block-b"><div class="ui-bar ui-bar-a" style="height:90px">Computer</div></div>';
     html += ' <div class="ui-block-c"><div class="ui-bar ui-bar-a" style="height:90px">Wine</div></div>';
     html += '</div>';
return html;
}

```

I have fixed the linking using l(...) and bl(...), but I would like my buttons fill all the grid. The name of the button also out of the range, so it just show partially. Here is the code and result:

```
var  html = '<div><form><label for="search-1">Search:</label>';
     html += '<input type="search" name="search-1" id="search-1" value=""></form></div>';
     html += '<div class="ui-grid-b">';
     html += ' <div class="ui-block-a"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Foo', 'node/966', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += ' <div class="ui-block-b"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Bar', 'node/1028', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += ' <div class="ui-block-c"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Baz', 'node/1021', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += ' <div class="ui-block-a"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Chop', 'node/1027', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += ' <div class="ui-block-b"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Computer', 'node/1021', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += ' <div class="ui-block-c"><div class="ui-bar ui-bar-a" style="height:90px">';
     html += bl('Wine', 'node/1025', {attributes:{'data-icon':'action'}});
     html += '</div></div>';
     html += '</div>';
return html;

```

# Answer
> 0 votes
Thanks to Tyler. I am giving more detail of the solution.

First download the new drupalgap.min.js from https://raw.githubusercontent.com/signalpoint/DrupalGap/7.x-1.x/bin/drupalgap.min.js and place it in the bin directory.

Modified the `index.html` where originally `<!-- DrupalGap -->
 <script type="text/javascript" charset="utf-8" src="bin/drupalgap-7.0.2.min.js"></script>` to the new `drupalgap.min.js`.

Then the grid widget from the drupalgap document http://docs.drupalgap.org/7/Widgets/Grid\_Widget starts to work! Both Render Array and theme('jqm\_grid', ...) can successfully do it. Just pick one. The code below is using render array.

```
/**
 * Implements hook_menu()
 */
function test_grid2_menu() {
  var items = {};
  items['test_grid2'] = {
    title:'test grid2',
    page_callback: 'test_grid2_page',
  };
  return items;
}

function test_grid2_page() {

var content = {};
content['my_grid'] = {
  theme: 'jqm_grid',
  columns: 2,
  items: [
    bl('Foo', 'foo'),
    bl('Bar', 'bar'),
    bl('Bar', 'bar'),
    bl('Baz', 'baz'),
    bl('Chop', 'chop')
  ]
};
return content;
}

```

# Answer
> 1 votes
@Clive, thank you for confirming, and for your efforts. @artphys, try the latest dev snapshot, `jqm_grid` is definitely supported: https://raw.githubusercontent.com/signalpoint/DrupalGap/7.x-1.x/bin/drupalgap.min.js

---
Tags: javascript
---


# Question
Title: How do I actually get a field value using field_view_value()?
I simply want to get the value of a field and have been told I should use field\_view\_value.

To this affect I have created:

```
$field_text_items = field_get_items('node', $node_context->data, 'field_text');

$field_text_items_value = field_view_value('node', $node_context->data, 'field_text', $field_text_items[0]['value']);

```

But running `dpm($field_text_items_value);` just returns an array with:

```
#markup (String, 1 characters ) h
#access (Boolean) TRUE

```

I'm assuming, because my field's value begins with a 'h', the `#markup` is only returning the first character for some reason.

Running `dpm($field_fcc_text_items[0]['value']);` returns the correct result so I know thing field is fine.

I've looked at the documentation linked above, but to be honest a lot of it doesnt make sense.

Would anyone be able to point me in the right direction here?

Thanks

As a side question, why is `field_view_value()` preferable to just using something like `$field_text_items[0]['value']` anyway?

# Answer
> 2 votes
You may have the field\_view\_value parameters wrong. Instead of the entity\_type-\> delta try loading the field first using field\_get\_items. Use the return value as the second parameter in field\_get\_items.

```
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

```

I took that answer from the blog: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

---
Tags: 7, entities
---


# Question
Title: How to allow users change theme for specific pages
A page has been created with panels which list all the contents of each user. I want to allow each user to be able to change the theme used for his own panel page. Whenever anyone visits the user panel page, they should see the theme of that user.

I have tried themekey but it only allows for sitewide theme.

What else can i do?

# Answer
You hook\_custom\_theme()

```
function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'Your Path') {
    return 'Your theme name here';
  }
}

```

Note: Clear cache and have a check

Or You can use Drupal module: ThemeKey

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.
> 1 votes

---
Tags: 7, theming, panels
---


# Question
Title: how give user based permissions for menu items?
i have 4 parent menu items for this i'm using superfish menu, how to give user based permissions to add a new page for particular parent menu only, example: menu item1(userrole1) --\> for this userrole1 has to add new pages under menu item1 only, like this i need to add role based menu items, please help me out. thanks in advance

# Answer
> 0 votes
You can set role-based permissions (/admin/people/permissions) per content type.

Then create Contenttype1 (/admin/structure/types/add) and Userrole1 (/admin/people/roles) and create a Views page for Contenttype1. Then set the page to be displayed under Menuitem1 in your menu settings (/admin/structure/menu).

---
Tags: users, navigation, taxonomy-terms
---


# Question
Title: How to change the check box to radio buttons Yes/No in tableselect form api?
How can I add a radio buttons with Yes/No options instead of the checkbox in the tableselect form (api)?

Here is the code in form.inc on line (3376):

```
$element[$key] = array(
        '#type' => 'checkbox',
        '#title' => $title,
        '#title_display' => 'invisible',
        '#return_value' => $key,
        '#default_value' => isset($value[$key]) ? $key : NULL,
        '#attributes' => $element['#attributes'],
      );

```

I changed the code like this:

```
$element[$key] = array(
        '#type' => 'radios',
        '#title' => $title,
        '#title_display' => 'invisible',
        '#options' => array(
          '1'   => t('Yes'),
          '0' => t('No'),
        ),
        '#return_value' => $key,
        '#default_value' => isset($value[$key]) ? $key : NULL,
        '#attributes' => $element['#attributes'],
      );

```

When I run it, it shows the form perfectly. But when I click the Submit button it gives me this error:

> "An illegal choice has been detected. Please contact the site administrator."

Any help?

# Answer
You need to set `'#multiple' => FALSE` on the tableselect where you declare it. This will set the tableselect to use radios rather than checkboxes.
> 1 votes

# Answer
`#return_value` is not a valid attribute for `#type' => 'radios'`(see Form API ). Try without that line.

And be aware of Anil Sagar comment : "*Rule one using Drupal CMS... **Never Ever change core files***" Means if you need to add radio buttons somewhere, do that in a custom module ...
> 0 votes

---
Tags: forms
---


title: How can I disable future dates?

text:
# Question
Title: How can I disable future dates?
I am developing a custom module, where I need to disable future dates in the date pop-up. How can I do this?

# Answer
> 1 votes
This can be achieved by adding an attribute `max`

```
$form['date'] = [
  '#title' => $this->t('Date'),
  '#type' => 'date',
  '#attributes' => [
    'type' => 'date',
    'min' => '-25 years',
    'max' => 'now',
  ],
  '#date_date_format' => 'd/m/Y',
];

```

Reference: https://api.drupal.org/comment/61733#comment-61733

# Answer
> -2 votes
```
$form['birthDate'] = array(
        '#type' => 'date_popup',
        '#title' => t("Birth Date"),
        '#date_format' => 'Y-m-d',
        '#date_year_range' => '-100:0',
        '#datepicker_options' => array('maxDate' => '-1 day' ),
        '#date_label_position' => 'invisible',
        '#required' => TRUE,
    );

```

---
Tags: 8
---


title: Get title of page

text:
# Question
Title: Get title of page
When I get the title on some pages, I get an empty title like *Home*. The code I am using in my subscriber is the following one.

```
class HistorySubscriber implements EventSubscriberInterface {
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('onResponse', 0);
    return $events;
  }

  public function onResponse($event) {
    $request = \Drupal::request();
    $route_match = \Drupal::routeMatch();
    $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
  }
}

```

It is an issue? How I can fix it?

# Answer
> 1 votes
The following code can be used to change page title.

```
// Alter page title.
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', 'Kontakt');
}

```

# Answer
> 0 votes
Try this

```
<?php
  $request = \Drupal::request();
  $title=t('Home');
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT) && !drupal_is_front_page()) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }

?>

```

this code return null in front page, then you should try to check if drupal\_is\_front\_page then show another title

# Answer
> 0 votes
Use this code inside your function and You will get title of any page like term, node page...

```
public function getCurrentPageTitle() {
    $title = 'DEFAULT TITLE';
    $request = \Drupal::request();
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      // For Taxonomy Term
      if (!empty($request->attributes->get('taxonomy_term'))) {
        $title = $request->attributes->get('taxonomy_term')->get('title')->value;
      }
      // For Node
      else {
        $node = \Drupal::routeMatch()->getParameter('node');
        if (!empty($node) && 'CONTENT_TYPE' === $node->bundle()) {
          $title = "CONTENT_TYPE_SPECIFIC_TITLE_SET";
          //$title = \Drupal::service('title_resolver')->getTitle($request, $route);
        }
        else {
          $title = \Drupal::service('title_resolver')->getTitle($request, $route);
        }
      }
    }
    return $title;
}

```

---
Tags: 8
---


# Question
Title: How to make Drupal Commerce tokens available in the Commerce Message module?
In addition to the Drupal Commerce module, I installed the Commerce Message module for Drupal 7. Everything works fine so far.

I created a new Rule to send a billing e-mail in addition to the order completed e-mail to the customer.

But now I have the problem that I can not apply any tokens that give me the address or full name of the customer. It seems, that the standard Drupal Commerce tokens do not work in the Commerce Message module.

I looked through the files of Commerce Message and I can only find a few tokens that do not help at all.

According to law I need to send billing information to the customer. Including the customer's full name and address.

How can I use the Drupal Commerce standard tokens with Commerce Message?

Also despite saying that it would be able to use multiple html tags it does not. Whenever I use `<em>` (for example: `<em>italic</em>`) it does not include such `<em>` in the e-mail (for example: it only includes `/italic/`).

Any help?

# Answer
> 2 votes
Even though your question is about the "Commerce Message" module, at its core your question relates to the Message module. And since you are using the Rules module, you can make the missing tokens (= *the commerce standard tokens*, as in your question ...) available by using the Replacement patterns for each message type.

So the answer to your question is "***Whatever token you're missing, just make it available via Rules, by creating a replacement token for them***". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.

These *Replacement tokens* are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

# Answer
> 0 votes
About this part of your question (near the end):

> ... use multiple html tags ...

That's really a different question, so here is a separated answer to that also: it must be that for the "Message text" you're using, you're using an HTML filter in which the `<em>` tag is not allowed (yet). So make sure to use an HTML filter in which it is allowed.

---
Tags: 7, commerce, tokens, message-subscribe
---


# Question
Title: How to clear cookie with cookie name on from submit?
When users fill values in node form input fields I set cookies of those values with help of javascript code, example :

```
    var date = new Date();
    date.setTime(date.getTime() + (60 * 60 * 1000));

 $('#edit-field-topic-und').on('change', function() {
            var section =  $(this).find("option:selected").val();
            console.log(section);
            if(section){
                $.cookie("section", section, { expires: date });
            }
        })

        $('#edit-field-topic2-und').on("change", function () {
            var topic = $(this).val();
            console.log(topic);
            if(topic){
                $.cookie("topic", topic, { expires: date });
            }
        });

        $('#edit-field-language-und').on('change', function() {
            var language =  $(this).find("option:selected").val();
            console.log(language);
            if(language){
                $.cookie("language", language, { expires: date });
            }
        })

```

If user does not submits from and next time come to node add form page, I set default values in from with help of form alter:

```
case 'link_node_form':
      /*show default values from cookie*/
      if (empty($form['nid']['#value'])) {

        if(isset($_COOKIE['section'])) {
          $form['field_topic']['und']['#default_value'] = $_COOKIE['section'];
        }

        if(isset($_COOKIE['topic'])) {
          $form['field_topic2']['und']['#default_value'] = $_COOKIE['topic'] ;
        }

        if(isset($_COOKIE['language'])) {
          $form['field_language']['und']['#default_value'] = $_COOKIE['language'];
        }

      // clear cookies after from submit
        $form['#submit'][] = 'custom_overrides_link_node_form_submit';

      }

```

Now when user submit form and node got created successfully cookie is not clearing or the cookies got values of last submitted node.

Please suggest how to clear / unset cookies when form get submitted.

```
function custom_overrides_link_node_form_submit($form, &$form_state) {

  if(isset($_COOKIE['section'])) {

    unset($_COOKIE['section']);
  }

  if(isset($_COOKIE['topic'])) {

    unset($_COOKIE['topic']);
  }

  if(isset($_COOKIE['language'])) {

    unset($_COOKIE['language']);
  }

}

```

# Answer
> 0 votes
By setting it to one hour ago time with empty value I managed to make it working according to my requirements.

```
function custom_overrides_link_node_form_submit($form, &$form_state) {

  if(isset($_COOKIE['section'])) {

    unset($_COOKIE['section']);
    setcookie("section", '', time() - 3600);
  }

  if(isset($_COOKIE['topic'])) {

    unset($_COOKIE['topic']);
     setcookie("topic", '', time() - 3600);
  }

  if(isset($_COOKIE['language'])) {
     unset($_COOKIE['language']);
     setcookie("language", '', time() - 3600);
  }

}

```

---
Tags: 7, forms, cookies
---


# Question
Title: How to get referenced fields of a particular node/content type?
I have a content type with reference field of type paragraph.

Using below code only gives me fields of content type and does not give referenced fields. How can I get referenced fields of a particular node type?

```
function hook_form_alter(array &$form, FormStateInterface &$form_state, $form_id) {
    $entityManager = \Drupal::service('entity.manager');
    $fields = $entityManager->getFieldDefinitions('node','media');
}

```

# Answer
> 0 votes
Once you have a `$node` object, you can get the referenced field value by the following code:

```
$node->get('field_reference')->referencedEntities();

```

Here, `field_reference` is a field of type `Entity reference revisions` referencing to the paragraph entity.

---
Tags: 8, paragraphs
---


# Question
Title: How to pass arguments to a view from Rules?
I am trying to use a view which depends on arguments but somehow it seems that the arguments are not passed to the view since I am getting no results. The view works when executed directly. The rule is triggered by Cron. Does Cron require any special permission to access the view? Any other ideas on solving this would be much appreciated

Rules is version 7.x-2.10 Views is version 7.x-3.16 Views Bulk Operation is 7.x-3.4+13-dev

```
{ "rules_send_reminder_1" : {
"LABEL" : "Send Reminder 1",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "Reminder" ],
"REQUIRES" : [ "rules", "views_bulk_operations" ],
"ON" : { "cron" : [] },
"DO" : [
  { "data_calc" : {
      "USING" : { "input_1" : [ "site:current-date" ], "op" : "+", "input_2" : 7776000 },
      "PROVIDE" : { "result" : { "result" : "Calculation result" } }
    }
  },
  { "drupal_message" : { "message" : "Fetching licenses that expire \u003C [result:value] and with status = 1" } },
  { "views_bulk_operations_action_load_list" : {
      "USING" : { "view" : "licence_reminder|default", "args" : "[result:value]\r\n1" },
      "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-list" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "drupal_message" : { "message" : "Processing licence with id : [list-item:license-id]" } },
        { "component_rules_reminder_1" : { "license" : [ "list-item" ], "status" : "1" } }
      ]
    }
  }
]
}
}

```

**Note**: I am hoping to find users that hold an expiring license, and that have been issued a new invoice which remains unpaid with the view (each user holds a status that indicates if the invoice has been issued and if it is paid or not). Then I will send the user a reminder email.

# Answer
> 1 votes
I think you're making it too complicated. As per the "*Any other ideas on solving this would be much appreciated ...*" in your question, I'd rather use the Views Rules module (instead of VBO), as further detailed below.

### 1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

> ... provides two types of elements in Rules, configured with a "Rules" view display:
>
> * **Views loop**: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.
> * **Collect view result rows (action)**: This action collects each variable in all view result rows into list variables for use in Rules.
>
> ***Tip***: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

### 2. Create a view of display type 'Rules'

After you enable the Views Rules module, you can use Views to create a view of the users you're interested in. I.e. "***those users that hold an expiring license, and that have been issued a new invoice which remains unpaid***" (as in your question). Add of view of display type ***`Rules`*** (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

### 3. Create a rule using the view of display type 'Rules'

Create a rule with the appropriate Rules Actions in it, using these guidelines:

* Use the link that says `Add view loop` to add a Views loop, and select the "Rules" display created in the previous step.
* Configure the parameters and variable names.
* For each user contained in your Views loop, perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the *Rules row variables* as suggested in the previous step, your actual eMail can use tokens such as `[usermail:value]`, `[username:value]`, etc.

### 4. Use the 'Rules Once per Day' module

Use the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

* You specify a **trigger hour** on the administration settings page for this module.
* The Rule trigger will then **run when cron tasks are first run after the start of that hour**. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

* The "Event" will only be triggered when a cron job is run.
* And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

***Easy, no?***

---
Tags: 7, rules, views
---


# Question
Title: Custom packaged CKEditor: Make buttons available on profle configuration page
We wanted buttons to add Definition Lists (dl, dt, dd tags) in CKEditor using this CKEditor plugin ckeditor-plugin-descriptionlist. There is already ckeditor\_descriptionlist module but not available for Drupal 7 at the moment.

So, we packaged CKEditor to have descriptionlist plugin in it. Here is that custom built CKEditor package: ckeditor-4.5.11-full-with-descriptionlist.zip.

Problem is that three buttons from descriptionlist plugin is not available in CKEdior profile configuration pages to add to any particular profile.

I know we can backport above mentioned ckeditor\_descriptionlist module to work in Drupal 7. But I am asking whether it will be possible to bring that buttons for configuration without using a drupal module as we have CKEditor package with required plugin?

# Answer
> 0 votes
I found the solution myself.

Earlier I was using "CKEditor 4 Presets Builder" available at https://github.com/ckeditor/ckeditor-presets . That is not required. I just have to put copy of descriptionlist plugin within "plugins" directory of CKEditor library. Then those three buttons started to appear in CKEditor profile configuration page.

---
Tags: 7, wysiwyg
---


# Question
Title: What is InstallerException and can it be thrown from a hook_install() implementation?
The documentation for this Exception class is this:

> Base class for exceptions thrown by installer.

By "installer" does it mean any hook\_install implementation? Which is what I assume, a counterpart to UpdateException? The hook\_install documentation makes no mention of this, so my best guess is that it is a part of some plugin ecosystem.

# Answer
No, this is not for hook\_install(), this exception is for errors during installation of a new drupal site:

*install.core.inc:*

```
function install_drupal($class_loader, $settings = []) {
  ...
  try {
    // Begin the page request. This adds information about the current state of
    // the Drupal installation to the passed-in array.
    install_begin_request($class_loader, $install_state);
    // Based on the installation state, run the remaining tasks for this page
    // request, and collect any output.
    $output = install_run_tasks($install_state);
  }
  catch (InstallerException $e) {
    ...
  }
}

```
> 1 votes

---
Tags: 8
---


title: How to load fields by target type?

text:
# Question
Title: How to load fields by target type?
I'm having a content type with referenced fields of paragraph type. How to get referenced fields in hook\_form\_alter?

Here are my fields:

```
[field_media_audio] => Drupal\field\Entity\FieldConfig Object
        (
            [deleted:protected] =>
            [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
                (
                    [id:protected] => node.field_media_audio
                    [field_name:protected] => field_media_audio
                    [entity_type:protected] => node
                    [type:protected] => entity_reference_revisions
                    [module:protected] => entity_reference_revisions
                    [settings:protected] => Array
                        (
                            [target_type] => paragraph
                        )

                    [cardinality:protected] => -1
                    [translatable:protected] => 1
                    [locked:protected] =>
                    [persist_with_no_fields:protected] =>
                    [custom_storage] =>
                    [indexes:protected] => Array
                        (
                        )

                    [deleted:protected] =>
                    [schema:protected] =>
                    [propertyDefinitions:protected] => Array
                        (
                            [target_id] => Drupal\Core\TypedData\DataReferenceTargetDefinition Object
                                (
                                    [definition:protected] => Array
                                        (
                                            [type] => integer
                                            [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object

```

# Answer
By what you can see in this var dump the field can hold any paragraph type, so you don't know which fields it may contain.

When you have restricted the field to one paragraph type, then load the field defintions for this type:

```
$fields_paragraph = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('paragraph', 'my_paragraph_type');

```
> 2 votes

---
Tags: 8, paragraphs
---


# Question
Title: How to use my own video and be able to play from a specific time?
I have Drupal 7 with the video module installed using ffmpeg. The video is playing fine. However, I noticed that users can only play from the beginning of the video. I would like to have users play from any specific time.

The embed video field module is only for embedding other videos so does not suit my needs.

# Answer
> 0 votes
May be you can try with javascript

```
document.getElementById('YOURVIDEOID').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

```

In jquery

```
var vid = $("#video")[0];
$("#button").click(function(){
    skipTime(100);
});

function skipTime(time) {
    vid.play();
    vid.pause();
    vid.currentTime = time;
    vid.play();
};

```

---
Tags: 7
---


# Question
Title: is it possible to hack a module by mymodule?
A few times i had (sadly and not proper) to hack a module, like changing some functions or default images, is it possible to hack a module in a proper way by "mymodule", in order to override simple things like changeing the returns of htlm or css with something like

```
mymodulefunction_moduleoriginalfunction(%args)

```

and make sure "mymodule" overrides my code running after original module?

# Answer
> 0 votes
No, it's not possible in the manner you are describing. However, Drupal provides many \_alter() hooks that allow various things to be altered as necessary, so that you don't have to hack anything.

However, without specifics on what you want to do, I cannot suggest any specific methods.

# Answer
> 0 votes
Every module provides hook api, you can simply use that or create and apply patch as per your needs. Its a bad practice to hack or change the code in any core/contrib module.

---
Tags: 7
---


title: Loop in Rules not picking up VBO data

text:
# Question
Title: Loop in Rules not picking up VBO data
I have a Views of users (friends of the current user) and I have added a VBO field to it. The objective is that when an event is created by the current user, their friends receive an email about it.

I created a Rule, and using VBO (release 7.x-3.3), I try to send an email to people. Right now, the loop is not picking up any data, even if the View is working properly. Am I missing something?

PS: The rule first shows a message to confirm that it has been triggered, and I am testing the loop with a status message.

```
{ "rules_test_loop_triggeredvbo" : {
"LABEL" : "test_loop_triggeredVBO",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "views_bulk_operations" ],
"ON" : { "node_insert--event" : { "bundle" : "event" } },
"DO" : [
  { "drupal_message" : { "message" : "Rule when event is created is TRIGGERED" } },
  { "views_bulk_operations_action_load_list" : {
      "USING" : {
        "view" : "clone_of_profile_friends|page",
        "args" : "[site:current-user]"
      },
      "PROVIDE" : { "entity_list" : { "entity_list" : "A list of entities" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-list" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "drupal_message" : { "message" : "User has friend:  [list-item:name]" } }
      ]
    }
  }
]
  }
}

```

# Answer
Have a look at these VBO issues:

Since you're using the 7.x-3.3 release of VBO, I recommend you retry your scenario with at least the 7.x-3.4 release. However, as per this comment you might only get it to work using the latest DEV version of VBO.
> 0 votes

---
Tags: 7, rules, views
---


# Question
Title: How to link to a page created with views
I have a custom page that show a list of item generated by a view.

These items should link to each item page that is a custom page as well created by another view and that use contextual filter (id from url) to show it.

How can I link from the list to the specific view? The system says page not found (404). I use this:

```
var link = l('' + row.title, 'pathview/' + row.nid);

```

`pathview/` is the path assigned in the view (if i write it in the browser it works)

The browser console show this in the link (72 is an example):

```
<a href="#" onclick="javascript:drupalgap_goto('pathview/72');" class="ui-btn ui-btn-icon-right ui-icon-carat-r">Item Title</a>

```

Thanks in advance, Cris.

# Answer
This docs page has a perfect example for what you need here: http://docs.drupalgap.org/7/Views/Displaying\_a\_View/Views\_Render\_Array

The only difference is, first you need to create a page in your app that takes in a page argument (http://docs.drupalgap.org/7/Pages/Page\_Arguments).

Then when it comes time to render that page, add a `View` widget/render-array to your page. You'll configure that `View` widget to pull from `'pathview/' + nid`
> 1 votes

# Answer
Ok, I've done some research and after a lot of try, these are my 2 pages:

# Custom module for the page with the list of items out of a drupal views

```
function mymodule_list_menu() {
  var items = {};
  items['articles'] = {
    title: 'Friend\'s list',
    page_callback: 'mymodule_list_articles_page'
  };
  return items;
}

/**
 * The page callback to display the view.
 */
function mymodule_list_articles_page() {
  try {
    var content = {};
    content['my_articles_list'] = {
      theme: 'view',
      format: 'ul',
      path: 'my-articles', /* the path to the view in Drupal */
      row_callback: 'mymodule_list_articles_list_row',
      empty_callback: 'mymodule_list_articles_list_empty',
      attributes: {
        id: 'my_articles_list_view'
      }
    };
    return content;
  }
  catch (error) { console.log('mymodule_list_articles_page - ' + error); }
}

/**
 * The row callback to render a single row.
 */
 function mymodule_list_articles_list_row(view, row, variables) {
  try {
      if (row.immagine.indexOf('http') > -1){
          img = {
              my_custom_image:{
                theme:'image',
                path:row.immagine,
                alt:'gift',
                title:'gift'
              }
            };
            img1 = row.immagine;
        }else{
          var image_html = theme('image', { path: row.immagine.src });
          img = image_html;
            img1 = "---";
        }
      var title_html = row.nome+" "+row.cognome.charAt(0)+"."+" "+row.title;
       var image_html = theme('image', { path: row.img.src });

      var link = l('' + title_html + image_html, 'singlegiftapp/' + row.nid);
      return link;

   }
  catch (error) { console.log('mymodule_list_articles_list_row - ' + error); }
}

function mymodule_list_articles_list_empty(view, variables) {

  return t('Sorry, no articles were found.');

}

```

# Custom module for the page with the single item after clicking one in the previuos list and that call another drupal views

```
  function mymodule_single_menu() {
  var items = {};
  items['singlegiftapp/%'] = {

    page_callback: 'mymodule_single_page',
    pageshow: 'mymodule_single_pageshow',
    page_arguments: [1]
  };
  return items;
}

function mymodule_single_callback(callback, nid) {
  node_load(nid, {
    success: function(node) {
      callback.call(null, node.title);
    }
  });
}

function mymodule_single_container_id(nid) {
  return 'gift-' + nid;
}

function mymodule_single_page(nid) {
 var content = {};
  content['divname'] = {
    theme: 'jqm_item_list',
    title: '',
    items: [],
    attributes: { id: 'divname' }
  };
  return content;
 }

function mymodule_single_pageshow(nid) {
  var path_to_view = 'singlegiftapp/'+nid;
  views_datasource_get_view_result(path_to_view, {
    'success':function(data){

    if (data.nodes.length > 0) {
        var items = [];

        $.each(data.nodes, function(index, object){
              var row = object.node;

             var image_html = theme('image', { path: row.img.src });

               var description =
                '<h1>' + row.title + '</h1>' +
                '<p> ' + row.field_anothertext+ '</p>';
               var dato = t(description+image_html);
              items.push(dato);

        });
         drupalgap_item_list_populate("#divname", items);
      }
    }

  });

}

```

These 2 module are working for me based on my views. Hope that would help to someone...
> 0 votes

---
Tags: javascript
---


title: Entity reference by title

text:
# Question
Title: Entity reference by title
I'm using the Feeds module and entity references heavily on my site to add, update, and link content. Unfortunately, the data I'm using has a number of records that are named the same, which causes issues when matching Entity References through GUID.

Is there a way to import entity reference fields through Feeds but using title and content-type instead?

# Answer
> 1 votes
I believe I've found an answer to this problem.

Using the Feeds Tamper module, I can add use the Entity Fields Query Finder plugin to lookup against any other field belonging to a particular content type.

In my case I'm saving the lookup key I need in a field, and then matching against that field & content type.

# Answer
> 0 votes
> Title **and** content-type

By default, there is no way to do that.

So you have 2 choices:

A) Go by the referenced nid instead.

B) Create a custom parser, see the The developer's guide to Feeds.

---
Tags: entities, feeds
---


# Question
Title: How to fetch data from database in mail template
I'm desperatly trying to get data from the database using a custom module (which is based on ubercart funds) to send a costomized email.

Here is how it makes email :

```
drupal_mail('ubercart_funds', 'escrow_cancel_from', user_load($transaction['uid'])->mail, language_default(), array('transaction' => $transaction['transaction_id']));

```

Implementing the mail template :

```
function ubercart_funds_theme() {
  return array(
'escrow_cancel_from' => array(
          'variables' => array('transaction' => NULL),
          'template' => 'theme/emails/ubercart-escrow-cancel-from',
      ),
   )
}

```

Sending the email :

```
function ubercart_funds_mail($key, &$message, $params) {

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
  $message['headers']['Content-Transfer-Encoding'] = '8Bit';

  if ($key == 'escrow_cancel_from') {
    $message['subject'] = token_replace('Escrow Payment at [site:name] was Cancelled');
    $message['body'][] = theme('escrow_cancel_from', array('transaction' => $params['transaction']));
  }
}

```

}

And in the template (ubercart-escrow-cancel-from.tpl) :

```
$transaction = db_query("SELECT * FROM {ubercart_funds_transactions} WHERE transaction_id=" . $variables['transaction']);

```

So actually I should have all the data from ubercart\_funds\_transactions which store the amount for example. But impossible to get any values. Moreover I would like to have the user name whereas I just have the user uid in ubercart\_funds\_transactions. So I tried to load it with user\_load() but things seems to be protected ... Here is what I get if I do a print\_r($transaction); :

```
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [needsCleanup:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [UpdateQuery] => UpdateQuery ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => **** [username] => **** [password] => ****, [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 5989e447343638.05601838 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) [escapedNames:protected] => Array ( [cache_bootstrap] => cache_bootstrap [registry] => registry [name] => name [filename] => filename [cache] => cache [base.uid] => base.uid [base] => base [uid] => uid [pass] => pass [mail] => mail [theme] => theme [signature] => signature [signature_format] => signature_format [created] => created [access] => access [login] => login [status] => status [timezone] => timezone [language] => language [picture] => picture [init] => init [data] => data [users] => users [base.fid] => base.fid [fid] => fid [uri] => uri [filemime] => filemime [filesize] => filesize [timestamp] => timestamp [file_managed] => file_managed [cache_field] => cache_field [m.entity_type] => m.entity_type [m.entity_id] => m.entity_id [m] => m [entity_id] => entity_id [revision_id] => revision_id [metatag] => metatag [cache_rules] => cache_rules [cache_form] => cache_form [ubercart_funds_user_funds] => ubercart_funds_user_funds [transaction_id] => transaction_id [ubercart_funds_transactions] => ubercart_funds_transactions [cache_token] => cache_token ) [escapedAliases:protected] => Array ( [name] => name [filename] => filename [uid] => uid [pass] => pass [mail] => mail [theme] => theme [signature] => signature [signature_format] => signature_format [created] => created [access] => access [login] => login [status] => status [timezone] => timezone [language] => language [picture] => picture [init] => init [data] => data [fid] => fid [uri] => uri [filemime] => filemime [filesize] => filesize [timestamp] => timestamp [entity_id] => entity_id [revision_id] => revision_id ) ) [queryString] => SELECT * FROM ubercart_funds_transactions WHERE transaction_id=39 )

```

How can I get the amount and user name ? What am I doing wrong ?

# Answer
> 1 votes
You're not getting the transaction data because you haven't executed the statement:

```
$transaction = db_query(...)->fetchObject();

```

A couple of other notes:

1. Don't run queries in the template, use a preprocess function to set up the vars and pass them in.
2. Don't concatenate parameters into an SQL string, you'll leave yourself wide open to injection attacks.

All-in-all, something like:

```
function mymodule_preprocess_escrow_cancel_from(&$vars) {
    $sql = 'SELECT * FROM {ubercart_funds_transactions} WHERE transaction_id = :id';
    $args = [':id' => $vars['transaction']];
    $vars['transaction'] = db_query($sql, $args)->fetchObject();

    $vars['user_name'] = $GLOBALS['user']->name;
}

```

That will convert the `$transaction` variable in your template into the object loaded from the DB, and give you the user name in `$user_name` too.

You'll need to clear cache after adding the preprocess function for the registry to pick it up.

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


# Question
Title: Module is reported to be missing, but it's present and active
I have a field type that have some default dependencies, such as Ctools and Views. I need the *Able Player* module, which is for Drupal 7. I installed this module, configured the *Able Player* libraries and checked that all is OK in the report section. This module is installed in /sites/all/modules/able\_player folder. In my info file I wrote the following line.

```
dependencies[] = able_player.

```

When I attempt to activate my module, Drupal says that the *Able Player* module is missing, but it is present and active.

For a test, I tried some other modules, such as the *jQuery Update* module, and it works fine.

Why does Drupal say the module is missing?

# Answer
You can not install a Drupal 7 module on Drupal 8. That's not possible.

The module needs to be converted to Drupal 8. Drupal reports the module as missing because the .info file is now info.yml, so Drupal does not find a able\_player.info.yml file anywhere and correctly reports the module as missing.
> 1 votes

---
Tags: 8
---


# Question
Title: How do I keep fields from being in the same row?
I've attached a pic to show what I'm talking about. I'm using 'fluid-grid' in Views. Drupal 7. Thanks so much!\[1\]

# Answer
Find the class of the element/field above (using your browser's developing tool) and try this CSS:

```
.field_my_field:after {
  visibility: hidden;
  display: block;
  content: "";
  clear: both;
  height: 0;
}

```

Change the "field\_my\_field" with your class name. Clear Drupal cache. It should push the next element below.
> 0 votes

---
Tags: views
---


title: Get the parent menu of the node

text:
# Question
Title: Get the parent menu of the node
I've a node, which is linked to a sub menu in the main navigation. I would like to get the url and title for the parent menu of the sub menu selected.

I've used it, but it is not working. I'm trying to use it in hook\_node\_view()

```
$node_id = $entity->id();
      $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
      $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
      $build['result'] = $result;
      kint($result);

```

In twig, I'm calling it as

```
{{ content.result }}

```

But it is not working..

# Answer
If you want to get the parent of the menu link use `getParent()`:

```
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
if ($link = reset($links)) {
  if ($parent = $link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}

```
> 10 votes

# Answer
Get parent menu of any type of page:

```
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$route_match = \Drupal::routeMatch();
$route_name = $route_match->getRouteName();
$route_parameters = $route_match->getRawParameters()->all();
$menu_links = $menu_link_manager->loadLinksByRoute($route_name, $route_parameters);

if (!empty($menu_links)) {
  $menu_link = reset($menu_links);
  if ($parent = $menu_link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}

```
> 2 votes

---
Tags: theming, 8, navigation
---


# Question
Title: Can i create custom content type without define .yml file in module?
Sorry for my bad english grammar. I write a module, allows the user to upload a file that contain list of content types infomation. Then my module will auto create content type for user. But i don't know how to create content type without hard define many .yml file.

# Answer
If your content type is fairly straight forward (i.e. using only Drupal's fields), you can create the content type within the `http://localhost/admin/structure/types/add` link and once you have it built the way you want it you can export it via: `http://localhost/admin/config/development/configuration/single/export`.

It will even give you the name of yaml file to boot!

If that avenue is not sufficient then you can follow: This tutorial about building custom drupal content entities; it is lengthy in nature, which is why I will elide the details.

And if you're going to use that tutorial, then I would suggest using drupal console to generate the boilerplate code for you. It makes things quite simple. Drupal Console, among other things, manages the generation of content entity boilerplate code. It is quite helpful.
> 0 votes

---
Tags: 8
---


title: Why isn't there a "node" table?

text:
# Question
Title: Why isn't there a "node" table?
After installing Drupal 7, the site seems to run fine, however looking in phpMyAdmin I don't see a "node" table. According to this image, used from the documentation on Drupal.org, it should have that table.

>

When I try to run various SQL queries that mention the "node" table they fail. However the Views module shows Drupal apparently internally able to query against the "node" table.
Also, using a raw SQL module I am able to write SQL against node.title, for example. However, it fails from phpMyAdmin.

I notice that Drupal 8 installations on the same server seem to have a *node* table. If it's relevant, these were all installed with Softaculous on Arvixe.

What is going on here?

# Answer
Yes, drupal 7 does have a node table. The reason why your database does not might be either because you are looking at the wrong database or perhaps because your configuration are using a database prefix. Look in your `sites/default/settings.php` file and check if you are using a prefix. For example:

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => 'd7_',
);

```

or

```
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'host' => 'localhost',
  'database' => 'example',
  'username' => 'user',
  'password' => 'password',
  'prefix' => array(
    'node' => 'd7_',
  )
);

```

The first example would prefix all tables in the database with `d7_`, while the second would only change the name of the `node` table.
> 3 votes

---
Tags: 7, nodes, database
---


# Question
Title: View files from multiple (filtered) nodes
I have content type Band and content type Performance. Performance has a reference field to the Band. Both content types have a media field where you can attach photos and videos. What I am trying to do is have the files from a specific Band and its Performances show up in a section (view) in the Band page. And I also want to sort them based on the Date each of the files has in its field.

All my efforts so far have been in vain. Tried to make this work with a content type view and with a file view. I feel like I will have to work with reference filters but again I can't seem to figure out how these work. I have been searching for far too long.

Any tips?

# Update

Here are two screenshots of two attempts that managed to manually bring the results I am looking for, but don't really feel right.

## Attempt #1

Attempt #1 tries to filter the performances and bands by taking the band name into a filter (performances have the auto label feature that adds the band name in their title). However if I have a band called "lost" and another one called "lost in space" I think I can't filter them correctly.

## Attempt #2

Attempt #2 uses two reference filters (this is the first time I tried to do anything with reference filters so I guess I am using them wrong in the first place). The first reference filter brings the band node and the second brings the same band's performance nodes. If I put the node id in the preview filter below I get the correct results. However in this case that view does not accept a node id as a contextual filter because it's a file view. If I try to put a contextual filter it automatically binds to the relationship underneath it and then the reference filters don't work.

It won't let me post the reference filter views, but they are pretty basic. One takes the band id as input and renders the... band id (monkey patching at its best). The other takes the band id as input and returns the band's performances ids as a reference filter list.

# Answer
> 0 votes
Here is a different approach, give this a try:

* Ok, get rid off all the **FILTER CRITERIA** except for `File: type = image`
* Under Advanced, add **RELATIONSHIP** of `[Your Entity Reference Field
Name]` make sure you select the one that says, "Referec**ing**" and NOT "Referenc**ed**".
* For your **FIELDS** `File: name` and `Content: title`, click on them and for relationship select your `Content Referencing Content from [Your Entity Reference Field Name]`

* Under Advanced, add a **CONTEXTUAL FILTER** of `nid`.

+ Select provide default value
    + `Content ID from url` (This will automatically pick up the nid (node id) from the Band node/page.

* Lastly, would be to add **SORT CRITERIA** and add the date field.

---
Tags: views, entities, media
---


# Question
Title: Selecting a car, then selecting tires based on which tires the car can have
Sorry, I can't express my problem without having to abstract it into something simple, I hope gets my point across. It has also been pretty much impossible to search Google etc., for this particular issue as I can't properly formulate it.

Imagine a content type called "Order".

You go to create a new Order. Where you can choose a car, and tires for THAT car. The only tires you can choose, have been defined on the car itself, when it was created.

So if you choose a tiny car, the tractor wheels are not shown as a choice of tires. Because on that tiny car, the tractor wheels haven't been selected.

On the car node, there's a field\_usable\_tires, where you can select the different tires that car can use.

My problem is how to make the "tires" selection on the create Order form change, dependent on the tires the car can have, when a car is selected.

Really hope someone out there understands my issues and can help! :)

/Dan

# Answer
> 0 votes
Is tires a dropdown list on the order content type?

If so, I think you might just need to manipulate the states, https://api.drupal.org/api/examples/form\_example%21form\_example\_states.inc/function/form\_example\_states\_form/7.x-1.x

I haven't used this module in a long time, but it might work for you, https://www.drupal.org/project/conditional\_fields

# Answer
> 0 votes
In similar situation, what I did, was to create an ajax callback on the field. I'm working on D8.

```
$form['field_name']['widget']['#ajax'] = array(
    'callback' => 'my_callback',
    'wrapper' => 'edit-field-organisation',
    'event' => 'change',
    'method' => 'replace',
    'effect' => 'fade',
  );

```

And in the callback I fetch the related content based on user selection. In my case I had to do with taxonomy terms. And replace the values in my second selectbox.

```
function my_callback($form, $form_state) {
  //Here get the selected value
  $organisation_id = $form_state->getValue('field_organisation')[0]['target_id'];

  $option = '<option value="_none">- Select a value -</option>';
  if(!is_null($organisation_id)){
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($organisation_id);
    $sector_list = $term->get('field_sector')->getValue('list');

    foreach ($sector_list as $key=>$item){
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($item['target_id']);
      $option .= "<option value='" . $item['target_id'] . "'>" . $term->getName() . "</option>";
    }
  }
  $response = new AjaxResponse();

  $output = '<select data-drupal-selector="edit-field-sector" id="edit-field-sector" name="field_sector" class="form-select required" required="required" aria-required="true">' . $option . '</select>';
  $response->addCommand(new ReplaceCommand('#edit-field-sector', $output));

  return $response;

}

```

Maybe there is a better way to fetch the terms but this works.

# Answer
> 0 votes
Create two vocabulary 1\> Car 2\> Tires . Now add term relation in tires vocabulary and select car vocabulary.

Now when you create a order . onchange of car select call a AJAX behalf selected car tid get you tries related to you car and replace tries field option by that option .

Thanks

---
Tags: nodes, forms
---


# Question
Title: How to group and merge results together in Views?
I have Views setup to list only nodes of a certain type and group them by a field. It looks somewhat like this:

*Group 1:
Title A
Title B*

*Group 2:
Title C*

Now I want to merge the Titles togehter so it looks like this:

*Group 1:
Title A & Title B*

*Group 2:
Title C*

How can I do this?

# Answer
> 0 votes
You can achieve this in following ways,

1) Choose your views format as table under Format 'Format: Table', Then click settings. You can find a table listing your selected fields. near to each field there is an option to choose column. There choose your Title B s column to Title A and in the separator provide '&' . Ensure Grouping field has chose. Now you will get a display in following format Group 1: Title A & Title B

OR

2) After grouping, Choose Exclude from display option for your Title A field. Then for second field choose Rewrite results. There you can find Replacement patterns. Use your token in appropriate format. eg. \[title\] & \[nid\]

Hope this may helps you

# Answer
> 0 votes
I think views aggregator module may help you
https://www.drupal.org/project/views\_aggregator

---
Tags: views
---


# Question
Title: How can I insert into table a row which contains an auto incremented field?
I am using drupal 7.41, I have a database table and it contains an auto incremented column/field. I am trying to insert some data into that table by using `db_insert` but it keeps displaying syntax error. Am I missing something in this syntax?

```
db_insert('my_table')
-> fields(array(
    'id' => NULL, //my auto incremented field...
    'name' => $form_state['values']['name'],
    'link' => $form_state['values']['link],
    'group' => 2 /* I have already tried this field with and without integer data and string data. Eg '2' and 2*/
    )) -> execute();

```

My mysql table contains four columns: id (Auto incremented, int), name (varchar(50)), link(varchar(200)), group (int).

I have tried every syntatic way but no to avail. And lastly here is my error message when I execute the query above:

I think there is no access violation here, since I was able to insert some other rows into different tables. Only difference is that that table has no auto incremented integer field and other integer fields. Just two varchar fields.

Thank you.

# Answer
The problem is you are using the keyword GROUP as a column name. Drupal's PDO code doesn't always escape column names, so you should avoid using MySQL keywords.

See the MySQL documentation.

> Most of the reserved words in the table are forbidden by standard SQL as column or table names (for example, GROUP).
> 2 votes

# Answer
You have used MySQL keyword "group" as a column name, so you should change MySQL keyword or use grave accent key with filed name.
> 0 votes

---
Tags: database
---


title: Percentage save issue on form submit

text:
# Question
Title: Percentage save issue on form submit
I am working in drupal8.I have created five forms all belonging to a single content type.i have around 50 fields in this content type.I have ten fields in a single form.This form has to be filled by the applicant.For each form we have given 20% completion.If i fill one form i shld get 20% completed.If i fill next from i shld get 40% completed and so on.I have created my form and basic crud operations are done.i dont know how to give this percentage of completion.Plz can anyone suggest how this completion percentage has to be done.

# Answer
The reason your current code isn't working is because your submit handler doesn't follow the correct naming convention (i.e. FORM\_FUNCTION\_NAME\_submit) and you don't explicitly attach the submit handler to the form anywhere so it's not being run.

You can solve this by simply changing the nameof your submit handler:

```
function example_form_form1_submit($form, $form_state){

```

Or you could look at `system_settings_form()` which automates much of this process for you.
> 0 votes

---
Tags: forms
---


title: Hide "Add to Cart" if already purchased

text:
# Question
Title: Hide "Add to Cart" if already purchased
How would I hide the "Add to Cart" button if the product line item already exists in \[user\] orders?

The situation is an online course, where the a user will buy access to a node. But once they have brought it, they still need to go back to the node to view the content. But we do not want to show the "Add to Cart" button as they have already brought it.

There is a very similar question here: Hide price and add to cart form for purchased product But this only hides the Cart button for 1 SKU. How would this be modified to look at all SKUs in \[user\]'s orders and hide "add to Cart"?

# Answer
> 0 votes
So I found this code here: http://agileadam.com/2012/04/drupal-commerce-add-to-cart-form-tweaks-registration-improvements/

Change $product-\>type to your product type

I also changed $form\['submit'\]\['#disabled'\] = TRUE;
to
$form\['submit'\]\['#attributes'\]\['disabled'\] = 'disabled';

---
Tags: commerce
---


# Question
Title: Redirect a user after delete last product from cart in drupal commerce?
I am using commerce in my drupal site.I need to redirect a user if he delete last item from cart. Any hook available for this?

# Answer
You can use Rules module for that , in event remove item from cart check if shopping cart is empty if so redirect user
> 0 votes

# Answer
Probably you can try below code to check if there is any product left in the cart when you delete product using AJAX. If this returns true you can redirect using jquery or javascript.

```
   $order = commerce_cart_order_load($user->uid);
   $has_products = false;
   if($order && !empty($order->commerce_line_items)) {
          foreach ($order->commerce_line_items['und'] as $line_item_id) {
             $line_item = commerce_line_item_load($line_item_id['line_item_id']);
          if($line_item->type == "product")
               $has_products = true;
    }
  }
  // If the cart is empty...
  if (!$order || !$has_products) {

```

Hope this helps...:)
> 0 votes

---
Tags: commerce
---


title: Cancel email in hook_mail

text:
# Question
Title: Cancel email in hook_mail
In hook\_mail() I might discover that some part of the email couldn't be generated (maybe when trying to load a variable from an external system it fails).

How can I cancel the sending? I don't want to send an email with an error message in it.

Example code:

```
function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'some_email':
      $foo = Something::fetchSomething($params['bar']);
      if (!$foo) {
        // I don't want to send this email any more
      }
      else {
        $message['body'][] = t('Important information about @foo.' ['@foo' => $foo]);
      }
      break;
  }
}

```

Does that make sense? Or should all parameters be loaded and processed before hook\_mail() and in hook\_mail() you assume to always have those params available?

# Answer
> 3 votes
You can do the access check from `hook_mail_alter` instead of `hook_mail` (let it prepare the default message based on parameters, and alter it later) by something like:

```
function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

```

**Note:** You should clear the cache in order to make the changes effective.

---
Tags: 8, emails
---


# Question
Title: How to access variables in a fieldset with variable_get
```
function bi_mx_enhancement_form($form, &$form_state) {
    $form['bi_mx_enhancement_government_ws'] = [
        '#type' => 'fieldset',
        '#title' => t('Government Web Service Settings'),
        '#tree' => true,
        '#collapsible' => true,
    ];
    $form['bi_mx_enhancement_government_ws']['base_url'] = [
        '#type' => 'textfield',
        '#title' => t('Base URL'),
        '#default_value' => variable_get('base_url', 'https://'),
        '#description' => t('The base URL of the Government Web Service for Medic Validation. NOTE: Do not add a trailing slash.'),
        '#required' => true,
    ];

    return system_settings_form($form);
}

```

Variable base\_url does not get saved, I always get the default value in the form.

I took a look at Drush, and it is like this:

```
bi_mx_enhancement_government_ws:
  base_url: 'http://52.203.204.11:8282/api/medicos'

```

# Answer
Since you are setting #tree to `TRUE`, the values will be saved in the *bi\_mx\_enhancement\_government\_ws* persistent variable, which will contain an array. For the code you are showing, its value will be similar to the following one.

```
array(
  'base_url' => 'https://'
);

```

Instead of `variable_get('base_url', 'https://')`, consider using the following code.

```
$values = variable_get('bi_mx_enhancement_government_ws', array());
$ws_base_url = $values['base_url'];

```

When you are now using `variable_get('base_url', 'https://')`, you should use `$ws_base_url`.

Since you seem to just use a single setting for that fieldset, I would rather use `'#tree' => FALSE`, if that form doesn't have any other form field which is using *base\_url* as identifier.
> 2 votes

---
Tags: 7, forms, configuration
---


# Question
Title: How to configure Views to determine pages never visited by anonymous users?
I want to find out and list the pages that never get visited by anonymous users. Google Analytics just shows pages that are visited at least once.

How can I configure views to create a kind of flag for "visited" or the like?

Thanks!

# Answer
> 4 votes
You may want to use the Flag, Rules and Views modules, as further detailed below ...

### Step 1

Enable the Flag module, and create a global flag which you label something like "Visited by an anonymous user".

That way, later on, any node that is NOT flagged by this flag, is one of the nodes that your question is about.

### Step 2

Enable the Rules module, and create a custom rule that looks like so:

* Rules Event: Content is viewed.
* Rules Condition: Current user has role "anonymous".
* Rules Action(s): Flag the node being viewed (using the flag from Step 1).

### Step 3

Enable the Views module, and create a view of all nodes that are NOT flagged. Those are ***the nodes that have not been visited at least once by an anonymous user***.

### Step 4

After you complete (implement) the previous steps, the (Views) results you get are correct as of the date you completed the previous steps. If you do have some type of historical (logging) information available about anonymous users visiting nodes, it would be a matter of using that information to also "flag" those nodes, so that your (Views) results would become more accurate/complete. And if you can make that info available in the format of some view, you could use the Views Bulk Operations (VBO) module, combined with another custom rule to also flag those nodes.

---
Tags: 7, views, google-analytics
---


# Question
Title: Is it possible to convert separate (matching) managed files to a single shared file?
I'm finishing up a Commerce store that has tens of thousands of imported products. In a slightly simplified form, here's my problem: Each has a unique primary image and a common secondary image. The import has created a separate secondary image of the exact same file for each product, which obviously creates enormous redundancy and uses much disk space unnecessarily.

Is there a safe way to convert all of the secondary images into a single, shared image in the database and filesystem? (I'm envisioning some kind of database SQL to make multiple products reference the same image, and then hoping that Drupal will clean up the orphan files automatically -- am I looking in the right direction?)

(Drupal 7)

# Answer
For small scale issues of this nature, the Duplicate Images module may be exactly what you need to step through the process of identifying and removing duplicates. (At the moment it bogs down and fails with huge numbers of duplicate images).

> # What does this module do?
>
> In a multi step form (like update.php) this module executes the following steps:
>
> 1) Search for duplicates
>
> * Searches are done on the public and/or private file system
> * It searches for file names ('filename' as used by pathinfo) that end with \_{n} and whose part before that also exists as separate file name.
> * It compares file size and md5 hash (see md5\_file) to determine if these are real duplicates or possible duplicates.
> * The results are presented as a list whereby for the possible duplicates clickable thumbnails are shown so you can visually compare them. For documents just a clickable icon is shown.
>
> 2) Search for usages
>
> * Look if a managed file record is defined for the duplicate (and the original).
> * Searches for references to the managed file in user pictures, all image and file fields, all fields that according to their field schema have a foreign key to the file\_managed table.
> * Searches for URI references to the file or a(n image style) derivative in selected text and link fields.
>
> 3) Update usages
>
> * Found references to the managed file record are updated to refer to the managed file record of the original (or if that does not yet exist, the uri field is simply updated).
> * Found textual usages are changed to refer to the URI of the original document.
> * Note 1: this phase uses the entity\_save() function of the entity api (contrib and thus a dependency) to ensure that caches are cleared, hooks are called, file\_usage is update, rules are executed, etc.
> * Note 2: this phase does keep track of failed updates so that the next phase can skip managed file records or files that are still being referred to.
>
> 4) Delete duplicates
>
> * All managed file records that are no longer referred to are deleted.
> * All duplicate files that ar no longer referred to are deleted.
> 0 votes

---
Tags: media, files
---