# Question
Title: Looping through taxonomy terms and adding them to term reference field with Rules
I have a content type called Items.

Within the items I have 3 unlimited term reference fields.

Location (field\_location\_pi)
Phase (field\_phases\_pi)
Structure (field\_structure\_type\_pi)

I am creating a drill down system using reference option limit.

So in a second content type, you would select item, then the location taxonomy field would be limited by those designated by that item, then the phases would be limited by those in the locations and the structure by those in the phases.

For this to work I need to have a reference field in each taxonomy that refers to taxonomy that limits it.

***For Example***

An Item is called Pour Cement. This item has 3 possible locations terms tagged: North, South, West. It also has 2 Phases terms tagged: First, Second. Finally it also has two structures terms tagged: sidewalk, wall.

So the Location Taxonomy Terms have an entity reference field (field\_pay\_items\_loc) that references all Items tagged with the terms.

Then the Phase Taxonomy Terms have a term reference field (field\_location\_ref) that references all the Locations they have in common in the Items.

Then the Structure Taxonomy Terms have a term reference field that references all the phases they have in common in the items.

To further extrapolate on the aforementioned example:

Each Location Term: *North* & *South* & *West* have one item referenced: Pour Cement

Each Phase Term: *First* & *Second* have 3 locations referenced: North, South, West

Each Structure Term: *Wall* & *Sidewalk* have 2 Phases referenced: First, Second

Right now I have to set this manually, but I would like to create a rule that automatically selects the correct item(s) in correct reference fields when a pay item is saved or created.

*I can do this when the reference fields are limited to 1* by using the following rule, This rule adds the item to the phase and the phase to the location. I know I need to change the action to adding to a list and it needs to happen within a loop but, for the life of me, I can not get it working when the reference fields are set to unlimited.

I've been slogging my way through the components (I watched this video: https://youtu.be/Bol6kNwVenA on creating multiple back links for a guide) and I can not get it to work with taxonomies. Any advice would be greatly appreciated.

```
{ "rules_add_pi_to_phase" : {
    "LABEL" : "Add item to Phase",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_update--item" : { "bundle" : "item" },
      "node_insert--item" : { "bundle" : "item" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node:field-phases-pi" ], "field" : "field_pay_items_loc" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-phases-pi:field-items-loc" ],
          "value" : [ "node" ]
        }
      },
      { "data_set" : {
          "data" : [ "node:field-phases-pi:field-location-ref" ],
          "value" : [ "node:field-location-pi" ]
        }
      }
    ]
  }
}

```

Here is the rule I have so far to loop through all the phases in the Item. Without the component.

```
{ "rules_add_pi_to_phase" : {
    "LABEL" : "Add PI to Phase",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_update--pay_item" : { "bundle" : "pay_item" },
      "node_insert--pay_item" : { "bundle" : "pay_item" }
    },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "pay_item" : "pay_item" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-phases-pi" ] },
          "ITEM" : { "phase_item" : "Current Phase" },
          "DO" : []
        }
      }
    ]
  }
}

```

I just realized that I wasn't thinking about this the right way. I need to get all the phases terms referenced (field\_phases\_pi) in the item AND all the structure types terms referenced (field\_structure\_type\_pi) in the item too. Then I need to add all the phases terms to the referenced field (field\_phases\_ref) to all the structure types terms referenced. So that would be multiple loops, I guess.

Here is my attempt at the component but I know it's not right because when I try to add it to the rule it doesn't allow me to pick a data selection and it wants Taxonomy term identifiers that I don't know what to do with...

```
{ "rules_add_phase_to_structure_type" : {
    "LABEL" : "Add Phase To Structure Type",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "phase_term" : { "label" : "Phase To Add", "type" : "list\u003Ctaxonomy_term\u003E" },
      "structure_term" : {
        "label" : "Structure Type To Add To",
        "type" : "list\u003Ctaxonomy_term\u003E"
      }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "structure-term" ] },
          "ITEM" : { "structure_item" : "Current Structure item" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "taxonomy_term", "id" : [ "structure-item:tid" ] },
                "PROVIDE" : { "entity_fetched" : { "fetched_structure" : "Fetched structure" } }
              }
            },
            { "list_add" : {
                "list" : [ "phase-term" ],
                "item" : [ "structure-item" ],
                "unique" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
This is to **Add the location reference term to the correct phase terms**.

First: I changed my condition to "entity has field", "node", "field\_phases\_pi"

Then I looped through the phases in the pay item

Then I add the pay item to the Pay Item entity reference field in each of the phases. *(This was more of a test as I already knew how to get this done)*

Then I added a nested loop to get all the locations in the pay item.

And I got stuck here so I set a message to confirm the values I was getting for each loop.

Once I got the loops to return the right value, it was just a matter of targeting the correct reference field in each phase (phase-item:field-location-ref) and adding the loc-ref-item from the loop.

Then I created the same rule (except targeting the different terms) for Adding Phase to Structure Type. So I'll have 3 seperate rules, there is probably a way to combine them, but I'm psyched to get this far!

Here is the export:

```
{ "rules_location_to_phase" : {
"LABEL" : "Add Location To Phase",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : {
  "node_update--pay_item" : { "bundle" : "pay_item" },
  "node_insert--pay_item" : { "bundle" : "pay_item" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_phases_pi" } }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-phases-pi" ] },
      "ITEM" : { "phase_item" : "Phase item" },
      "DO" : [
        { "list_add" : {
            "list" : [ "phase-item:field-pay-items-loc" ],
            "item" : [ "node" ],
            "unique" : "1"
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "node:field-location-pi" ] },
            "ITEM" : { "loc_ref_item" : "Location Ref item" },
            "DO" : [
              { "drupal_message" : { "message" : "Loc-ref-item:name value:[loc-ref-item:name]\r\n\r\nPhase Item Name Value: [phase-item:name]" } },
              { "list_add" : {
                  "list" : [ "phase-item:field-location-ref" ],
                  "item" : [ "loc-ref-item" ],
                  "unique" : "1"
                }
              }
            ]
          }
        }
      ]
    }
   }
  ]
 }
}

```

# Answer
> 1 votes
Looks like you could just use the "Add to list" Rules Action.

For multi value fields you should not use "Set a data value" (which seems to be what you've tried, a common mistake when using Rules for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...

---
Tags: taxonomy-terms, rules
---


title: Restore the body field

text:
# Question
Title: Restore the body field
I am new to Drupal 8. I had a understanding that, Drupal by default provides you a Title and Body field for content type.

I have an ongoing project, and I realized that one of the content types is missing the body field. How can I restore it?

# Answer
You can do it through the UI:

1. Visit /admin/structure/types/manage/CONTENT-TYPE/fields/add-field.
2. Choose the body field from the *Re-use an existing field* select.
3. Click *Save and Continue*.
4. Configure the field for that specific content type and save.
> 6 votes

---
Tags: 8, nodes
---


# Question
Title: Drupal 7 - Internationalization module - some blocks not visibile (i18n)
After adding the Internationalization module for Drupal 7, I am having some trouble with a particular block not showing up when switching languages. I set the block to be translatable (and set full html to be translatable) - the block only contains an image and is displayed in the "slideshow" region of the IV Solutions Theme. The block/image shows up fine when the page is set to English, but when the language is changed, it disappears.

Thanks for any assistance you can give-

# Answer
Translatable means you have to actually translate it to show on the second language. On the block configuration it should give an option to translate it or perhaps check the block's visibility language settings.

Another option if you want the same exact image on both languages you make the block untranslatable.

You need to also enable **i18n\_select** if you have not done so and go to "detection and selection" `admin/config/regional/language/configure` and enable at least URL selection for interface/content

This will allow that when you visit `yoursite.com/page` assumes English and when you visit `yoursite.com/LAN2/page` assumes LAN2

More info on setting up internationalization
> 0 votes

---
Tags: 7, i18n-l10n
---


# Question
Title: Taxonomy term listing of nodes with the term in a paragraph
I found similar questions but not an actual answer... This is my setup In Drupal 8:

> Node
>
> > Paragraph
> >
> > > Taxonomy term reference

I would like to use the default taxonomy term view (taxonomy/term/%) to display a list of node teasers in which the paragraph contains the term. I'm probably passing the wrong contextual filter but I couldn't figure how to fix it.

# Answer
As per you comments you need some thing like the following to change the Title to a taxonomy term.

```
/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  // Get the machine name of your view and replace below.
  if ($view->id() === 'myview_machine_name') {
    $tid = $view->args[0];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
    // overide the title with the term name.
    if (is_object($term)) {
      $view->build_info['title'] = $term->getName();
    }
  }
}

```
> 0 votes

# Answer
I ended up using an alternative solution, with Taxonomy View Integrator: It overrides the display of the regular view selecting any view you want. It's slighlty easier because there is no need to deal with path of the view page, which is useful if you have different displays/behaviours for different vocabularly.
> 0 votes

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


title: cannot update Drupal core with drush

text:
# Question
Title: cannot update Drupal core with drush
Why can't Drush find the Drupal core module?

```
root@hostname:/var/www/html/sites/example.org# drush pm-update core

...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

```

So then I tried:

```
root@hostname:/var/www/html/sites/example.org# drush -r /var/www/html -l example.org pm-update core
...
Wysiwyg (wysiwyg)                        7.x-2.2         7.x-2.2         Up to date
core                                     Unknown         Unknown         Specified project not found

```

I have used both these commands in the past to update other Drupal modules and it has always worked, until I have to update the Drupal core module. Can Drush not handle this or is this a bug?

# Answer
> 3 votes
To update core on its own try

```
drush pm-update drupal

```

A plain

```
drush pm-update

```

will update all modules, and then core.

Note that it doesn't backup .htaccess, robots.txt, or any other files that you may have modified. I have gotten in the habit of doing a full `drush archive-dump` before core updates, and/or using Backup and Migrate in combination with having everything under git control.

# Answer
> 0 votes
I installed drush 9.x Now when I drush up I get: The pm-updatecode command was deprecated. Please see `composer outdated` and `composer update`. For security release notification, see `drush pm:security`.

---
Tags: 7, drush
---


# Question
Title: How can I fetch updated values from user profile edit form?
I want to check image field length from user edit form, I mean that upload image field accepting more than one image, so i want to validate the number of images to be save / upload into database before going to save in database. And also let me know is any hook is available for upload button.

# Answer
You'd want to use hook\_form\_alter https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_alter/7.x

And add your own validate function with something like:

```
$form['#validate'][] = 'my_function_name';

```

Then you can do whatever checks you want in there and then use form\_set\_error if needed to stop the form submission if required and nothing will get saved
> 0 votes

# Answer
In My case iam using presave hook, after click on submit button presave custom module will activates that time it accepts $edit as one of parameter so you can use $edit to access updated form values example: $edit\['field\_full\_name'\]\['und'\]\[0\]\['value'\] , count($edit\['field\_gallery'\]\['und'\]) And it works for me.

Thank you
> 0 votes

---
Tags: forms
---


# Question
Title: How do I define multiple blocks in one module and include different javascript for each?
**In Drupal 8**

I understand that to create a block I create a file in this structure:

```
mymodule/src/Plugin/Block/MyModuleBlock.php

```

If I would like to create another block for this module, or even a dozen blocks in this module, where do I define them so that they render differently and contain different javascript/css?

# Answer
> 1 votes
Use the following folder structure to create multiple custom blocks in drupal 8

```
-mymodule
--src
---Plugin
----Block
-----block1.php
-----block2.php
-----block3.php

```

---
Tags: 8, blocks
---


# Question
Title: Let custom module access private files via file_get_contents
I have a custom module (Drupal 7) where I want to read the contents of a file using file\_get\_contents($file) in the private directory. Theres a access denied error, as the module accesses as anonymous.

I can access the file via browser via the url created with file\_create\_url(), but gain no access from my module.

Is there a way to grant my module the permission to open files? Any other ideas are welcome, too.

Thanks, Marc

# Answer
> 1 votes
"Use the file system path rather than the url" - Thanks @Clive, this is the solution.

---
Tags: files
---


# Question
Title: How do I count the number of products in cart programmatically?
I have created the custom block, here I want to count the number of products which is presented in the cart and tried with `commerce_cart_order_load` function to get the user selected products.

Is there any other methods to count the number of product in cart ?

Please help me how to achieve this !

# Answer
> 3 votes
If you know the store id and order type, then you can count the number of products in the current user's cart with the following code.

```
    $store_id = 1;
    $order_type = 'default';
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_provider = \Drupal::service('commerce_cart.cart_provider');
    $entity_manager = \Drupal::entityManager();
    $store = $entity_manager->getStorage('commerce_store')->load($store_id);
    $cart = $cart_provider->getCart($order_type, $store);
    $total_items = count($cart-> getItems());

```

# Answer
> 6 votes
In Drupal 8, carts are special orders, related to a user (like regular orders). In a custom module, you can fetch the logged in user orders, filter them by a convenient boolean field called 'cart', sort them by creation date to get the last cart for this user. Then you can get the items count for this cart order :

```
in mymodule.module :

use Drupal\commerce_order\Entity\Order;

function mymodule_preprocess_[page|block|something_else](&$variables) {

  // get orders...
  $query = \Drupal::entityQuery('commerce_order')
    // ...for logged in user, could be anonymous (uid = 0)
    ->condition('uid',\Drupal::currentUser()->id())
    // ...which are carts
    ->condition('cart', 1)
    // ...last created first
    ->sort('created', 'DESC')
    // ...get only one
    ->range(0,1);

  // execute this : you get an array of a unique order ids (last cart)
  $cartsOrders = $query->execute();

  // I found one : this user has a cart
  if(count($cartsOrders) > 0) {

    // load the order which is the last cart for logged in user
    /* @var Order $lastCart */
    $lastCart = current(Order::loadMultiple($cartsOrders));
    // send this order items count to the template
    // ({{ cartItemsCount }} in your twig)
    $variables['cartItemsCount'] = count($lastCart->getItems());
  }
}

```

This may contains non optimal or ugly code, this is just a starting point (but quickly tested though, seems to work). Also this need to be tested in rare case scenarios or weird situations (involving anonymous users for example). My strategy (grab the last created cart order) may be wrong too...I would be happy to have a specialist feedback on this.

**EDIT**

I spent more time on this and had to debug a few things, here is some improvments (more Drupal Commerce 2 way) :

```
/* @var CurrentStoreInterface $cs */
$cs = \Drupal::service('commerce_store.current_store');
/* @var CartProviderInterface $cpi */
$cpi = \Drupal::service('commerce_cart.cart_provider');
$cart = $cpi->getCart('default', $cs->getStore());

$nbItemsInCart = $cart ? count($cart->getItems()) : 0;

```

# Answer
> 0 votes
Are you sure this is Drupal 8 and not Drupal 7? That function is from the Drupal 7 version of commerce\_cart.module. If that's the case, you can do what the code does in the title callback for the "Shopping cart (# items)" code to count the number of items in the cart:

```
// Count the number of product line items on the order.
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

```

To make it more performant, we've added a cart\_line\_items\_quantity\_by\_id() function in the dev version (to be included in Commerce 1.14) that avoids using the wrapper. However, you'd have to convert the $order-\>commerce\_line\_items field value into an array of line item IDs yourself first.

---
Tags: 8, commerce
---


title: Get field value

text:
# Question
Title: Get field value
So a basic question. On Drupal 8 I have a views field override using preprocess. I need to get the value of the field but everything I try returns null or an error. I have:

```
function mytheme_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $id = $view->storage->id();
  if ($id == "myfield"){
    $myfieldvalue = $variables['field'];
  }
}

```

I have tried various combinations. I thought **getValue()** might work but no. So far **$variables\['field'\]-\>original\_value** is closest but obviously returns the markup version.

The **$variables** I cannot see the raw value. So question is how do I get it? Do I need to load the node and get it that way?

# Answer
Calling **getValue()** of a views field object should work, but you need to provide the row as parameter:

```
$myFieldValue = $variables['field']->getValue($variables['row']);

```

Reference: https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21field%21FieldPluginBase.php/function/FieldPluginBase%3A%3AgetValue/8.5.x
> 3 votes

# Answer
This is the solution I came up with pass row number and field name

$field\_output = $view-\>style\_plugin-\>getFieldValue(0, 'field\_custom\_text');
> 1 votes

---
Tags: views, entities
---


# Question
Title: How to programmatically disable Global Theme Settings?
I am trying to programmatically disable `logo` and `site name`. I have seen some variables for these set in ***modules/system/system.admin.inc*** but haven't been able to disable them through my profile installer settings.

What is the proper way to disable them? I looked around the internet but found no one has really looked into this issue.

# Answer
See here for a related question.

The theme settings are not individually saved as variables. They are all in a single variable, whose name depends on your theme. For example, if your theme name is `mytheme`, the variable name will be `theme_mytheme_settings`.

You can disable the logo and name like this:

```
$my_settings = variable_get('theme_mytheme_settings', array());
$my_settings['toggle_logo'] = 0;
$my_settings['toggle_name'] = 0;
variable_set('theme_mytheme_settings', $my_settings);

```

You can also disable settings by means of the `features` key in the `.info` file for your theme. The defaults are:

```
features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

```

If you don't specify any of these, all are enabled. If you specify some, only the ones you specify are enabled. So if you wanted to hide logo and site name, you would put this in your `.info` file:

```
; features[] = logo
; features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

```

See the theme settings documentation for more info. You need to be careful with this depending on what theme you are using. If you're overriding a base theme, these are the keys, but a contributed or custom theme might have different keys.
> 1 votes

---
Tags: 7, forms, theming, installation-profiles
---


title: Image style URL from theme path

text:
# Question
Title: Image style URL from theme path
I am trying to generate a URL for an image style, generated from an image in my theme directory:

```
$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';
$banner_file = file_build_uri($image_uri);
$banner_url = image_style_url('my_image_style', $banner_file);

```

The $banner\_url looks to be correct, however when I browse to it directly, I get a general Drupal error.

```
http://www.mysite.local/sites/default/files/styles/my_image_style/public/sites/all/themes/mytheme/images/banners/projects-banner.jpg

```

I had tried to pass $image\_uri into image\_style\_url, but understand this need a URI and not a path. Can someone please point me in the right direction.

# Answer
You're right, the `image_style_*` functions only work with files in the managed file system. You can get round it by using the imagecache\_external module, though, which takes remote images and stores them where we need them.

It might seem a little strange to be requesting local images as if they were remote, but this ensures the integrity of the image\_style system without further hackery.

```
$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';

$absolute_image_url = url($image_uri, array('absolute' => TRUE));
$banner_file = imagecache_external_generate_path($absolute_image_url);

$banner_url = image_style_url('my_image_style', $banner_file);

```
> 2 votes

---
Tags: 7, media
---


# Question
Title: How to update role name progammatically in Drupal 8
I am new to Drupal 8. I want to save & update role programmatically in database. I am using below code

```
    //your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

```

It works fine. Now I want update role name. How to proceed it?

Please anyone suggest to me?

# Answer
> 2 votes
If you already have the role object loaded:

```
$role
  ->set('label', 'New label')
  ->save();

```

If you don't:

```
$role = \Drupal::entityTypeManager()
  ->getStorage('user_role')
  ->load('client')
  ->set('label', 'New label')
  ->save();

```

---
Tags: users
---


# Question
Title: Is there a way with drush or console to delete all active config with a certain prefix?
I'm currently trying to migrate a site with `drush migrate-upgrade --configure-only ...` and copying the export migrate\_plus.migration\_\*.yml into a custom module for tweaking. Now I want to enable that module but I get `PreExistingConfigException.php` and `... provided by MYMODULE already exist in active configuration`.

I'd like to delete all config but it looks like the latest drush has removed `drush config-delete` and `drupal config:delete` is gone too. How do I achieve this?

# Answer
This isn't the greatest solution, but it does work, and also allows you to not have to execute a dozen steps/commands to register your migrations.

In my custom module where I'm creating migration sources/plugins, I added a .install file and implemented hook\_uninstall(). In there I delete the configurations remaining manually.

```
<?php

/**
 * @file
 * Contains my_module_migrate.install.
 */

/**
 * Implements hook_uninstall().
 *
 * Removes stale migration configs during uninstall.
 */
function my_module_migrate_uninstall() {
  $query = db_select('config', 'c')
    ->fields('c', array('name'))
    ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
    ->execute();

  $config_names = $query->fetchAll();

  // Delete each config using configFactory.
  foreach ($config_names as $config_name) {
    \Drupal::configFactory()->getEditable($config_name->name)->delete();
  }
}

```

Note: You may need to clear cache after uninstalling for the changes to show before re-enabling the module.

If you want to remove them before you uninstall you can either run each line from hook\_uninstall() implementation in devel/php, or you can run them via drush: `drush ev "\Drupal:;configFactory()->getEditable('migrate_plus.migration.xxxxxx')->delete();"`
You will probably have to clear cache after removing all of them manually via drush as well.

If you'd like to just run a couple of drush commands to re-register your migrations, you can add this drush plugin file `my_module.drush.inc` to your modules' root directory, clear cache, and run `drush mpc -y && drush mcr my_module`. You may need to also run `drush cache-clear drush` for the commands to be come available.

Here's the code for the `my_module.drush.inc` file:

```
<?php
/**
 * @file
 * Contains my_module_migrate.drush.inc
 */

/**
 * Implements hook_drush_command().
 *
 * Defines drush commands.
 */
function my_module_migrate_drush_command() {
  // Company update Dynamically
  $items['migrate-prune-configs'] = array(
    'description' => dt('Prune migrate configs.'),
    'aliases' => array('mpc'),
    'examples' => array(
      'drush migrate-prune-configs' => 'Removes migrate configuations.',
    ),
    'callback' => 'my_module_migrate_migrate_prune_configs',
  );

  $items['module-config-reset'] = array(
    'description' => dt('Resets default config for a given module.'),
    'arguments' => [
      'module_name' => dt('Module name'),
    ],
    'aliases' => ['mcr'],
    'required-arguments' => 1,
    'callback' => 'my_module_migrate_config_reset',
  );

  return $items;
}

/**
 * Callback for drush command migrate-prune-configs to prune migratin configs.
 */
function my_module_migrate_migrate_prune_configs() {
  //Confirmation will be Y/N when use type “y” the condition will be executed if not it will not
  if (drush_confirm(dt("Are you sure you want to remove migrate configs?"))) {
    drush_print("Removing.....");
    // Get all of the migration config names.
    $query = db_select('config', 'c')
      ->fields('c', array('name'))
      ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
      ->execute();

    $config_names = $query->fetchAll();

    // Delete each config using configFactory.
    foreach ($config_names as $config_name) {
      drush_print("..." . $config_name->name);
      \Drupal::configFactory()->getEditable($config_name->name)->delete();
    }

    drush_print("Removed succesfully");

    return TRUE;
  }
}

/**
 * Reinstall default module's config files
 */
function my_module_migrate_config_reset($module_name) {
  if (!in_array($module_name, array_keys(\Drupal::moduleHandler()->getModuleList()))) {
    return drush_set_error(dt('Module @module_name not found.', ['@module_name' => $module_name]));
  }
  // Initiate config installer for given module.
  \Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

  drush_print('Configuration was successfully reset.');

  return TRUE;
}

```

The code for resetting the module's configs was found in this issue on d.o. I found that it doesn't work unless the configs are already removed, hence the first command to remove them.
> 5 votes

# Answer
config:delete is in core drush 8 and drush9. it is not removed. make sure your site is bootstrapping properly for drush requests.
> 0 votes

---
Tags: 8, migrations, configuration
---


# Question
Title: How do I print the local task bar in different places depending on the base route?
I want to print the local task bar used when users register/login/reset password at another part of the page, than the other local task bars.

The base route for these menu links is *user.page*.

https://github.com/drupal/drupal/blob/8d0135d52be12024d70036420f271677ab6aa7d9/core/modules/user/user.links.task.yml#L11-L26

Can I use twig to achieve this? Or do I need to use some preprocessing?

# Answer
Local tasks is just a block, meaning you can use all the tools that blocks give you. Create two blocks, put them in both locations where you want to see it. On one block, configure path visibility to only show on user/*, on the other one, configure it to show everywhere except on user/*.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to sql-sync database between two remotes which share the same host?
I've two remotes: `@source` and `@destination`.

I'm trying to transfer the database from dev to test environment by using `sql-sync`:

```
$ drush -vy sql-sync @source @destination

```

But at the end drush complains that:

> The source and destination cannot both be remote.
>
> rsync error: syntax or usage error (code 1) at main.c(1166) \[Receiver=3.0.9\]

Both remotes are on the same machine, but they're using different path.

I'm using latest drush 7.0-dev.

Is there any workaround?

# Answer
Here is how drush sql-sync works between two remotes:

1. Logs into remote `@destination` via SSH and creates destination database if needed via `sql-create`.
2. Backs up database on `@source`by performing `sql-dump` on source unless told otherwise and saves it into `drush-backups` folder.
3. Logs into `@destination` remote via SSH and executes `rsync` to transfer database from Source to Destination.

Example: `rsync @source:drush-backups/db.sql.gz @destination:/tmp/db.sql.gz`

To make this work, you have to make sure that:

* both local and remote drush have the same version (either 6.x or 7.x),
* on Destination the `@source` alias should be accessible for drush,
* `rsync` tool doesn't support two remotes, so only one may be remote.

Based on above it seems you can't use `sql-sync` drush command to transfer the database between two remotes in drush 7.x (see: #161).

As for workaround, first dump the database from your source onto your local and transfer back to the destination, in example:

```
drush @source sql-dump | drush @destination sql-cli

```

This should transfer the database between two remotes without `sql-sync` limitation.
> 5 votes

# Answer
Another option I use is to use drush ssh command to execute drush on the source :

```
drush @source ssh "drush sql-sync @self @destination"

```
> 2 votes

---
Tags: deployment, drush
---


# Question
Title: Trying to make a filter taxonomy menu with multiple vocabularies
I'm currently having trouble getting a taxonomy menu to act as a product display filter. Actually I think I may need multiple menus as my products need to be filtered by: category, price, and color. I can do the filters separate, but they need to stay active together such as a filter with a category of 'all' and a price of 0 to 99 and color of red. I am hoping to get this working somehow with views rather than recoding, but that is an option as well. I'm still a little new to Drupal, and this is my first Drupal commerce kickstart site. Using Drupal 7 and commerce kickstart 1.

# Answer
I think that you mean "taxonomy vocabularies" when you say "taxonomy menu". Because actual menus like the navigation are not really suitable for this task.

Scince you are using Commerce Kickstart, you can simply use multiple Search Blocks as Filters and join their results. The View "Display Products" that comes with Commerce Kickstart by default actually has already a Block with the "Price" Filter on it.

I am assuming that your product display already has fields for the Term references to your taxonomy vocabulary. Also assuming you have not changed these settings yet, go to `Administration » Configuration » Search and metadata » Search API » Product display » Fields` and select the fields of your product that you want to filter for. Then reindex them and go to `Administration » Configuration » Search and metadata » Search API » Product display » Facets`, select your new fields and edit their display (e.g. checkboxes for color and ranges for price). Make sure you select "AND" as an operator if you want to have the products that match every filter.

Once you have that, go to `Administration » Structure » Blocks` and put the newly created blocks on the sites you need them on (e.g. /products)
> 1 votes

---
Tags: 7, commerce, taxonomy-terms
---


# Question
Title: Tax rate select missing from product price in commerce 8
I installed `drupal commerce 8 rc2` and created a tax type of "European Union VAT". When I create a new product, near the price field, I can't find the tax rate select.

How can I associate 10% or 22% vat rate to the price of product?

# Answer
> 1 votes
Try these 3 references:

1) Need to modify tax type based on user field in Drupal 8 Commerce 2

Here you can see an example of creating your own service in a custom module to interact with the default TaxOrderProcessor or writing a simple module to override the tax order processor service at all.

2) https://www.flocondetoile.fr/blog/apply-vat-rate-product-drupal-commerce-2

Here you can see how "to vary an applicable VAT rate according to a product, or a product type, we just need to implement a service that will declare the trade\_tax.tax\_rate\_resolver tag with a priority at least higher than the default TaxResolver provided by Drupal Commerce."

3) https://www.rapiddg.com/blog/modifying-product-prices-drupal-commerce-2-drupal-8

Here you can see another example of application of "resolvers", the concept that do the work done bu Rules at Commerce 1, which is the key of the previous comment (link 2).

Ps: At the moment, poor documentation about this stuff, and no UI to manage this BASIC feature :-(

---
Tags: 8, commerce
---


# Question
Title: Change Views Display Title Programatically
I had a similar question recently, related to changing the path on a Views Display. Following this reasoning (as well as other examples I've seen), I assumed I could follow a similar approach. Unfortunately, that doesn't seem to be the case.

Related question for reference: Change Views Path Programatically

What I currently have:

```
$view = \Drupal\views\Entity\View::load('custom_view');
$display =& $view->getDisplay('page_1');
$display['display_options']['title'] = 'My Custom Title';
$view->save();

```

However, this does not seem to alter the title of the Display. I've attempted a method of changing the Display title in a Views hook, at that works correctly, but I'd like to be able to change the title without relying on actually viewing the View to utilize its hooks. In addition, I believe this would set the title for all Displays, which I don't want. Working example:

```
function my_moudule_views_post_render(ViewExecutable $view) {
    $view->setTitle('My Custom Title');
}

```

Following this approach, I attempted to utilize the `\Drupal\views\Views::getView()` method, but was unsuccessful.

# Answer
> 1 votes
Your code is working I believe, but it could be that "page\_1" is not the correct page variant name...I had to use 'default', that was what I ran into when creating a test View and attempting to try your code out... in my case to verify, I enable kint, do a `ksm($view)` and check the 'display' array to verify the variants. You may need to alter 'default' to see the intended results. Also make sure to cache rebuild just in case `drush cr` afterwards, you may want to programmatically empty the cache bin for this View depending on the use case.

Also, you mentioned the hook affecting all the Views. That is true, but you could add some more granular logic to the hook to make it only affect specific View, by specifically drilling down to the ID (the 'machine name" in the Views GUI) and performing logic only if the machine name matches, e.g. if my View machine name is "foobar\_view\_custom", then you can do:

```
/**
 * Implements hook_views_post_render().
 */
function mymodule_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache)
{
  $display = $view->getDisplay();
  $id = $display->display['id'];
  if ($id === "foobar_view_custom") {
    $view->setTitle("PROGRAMMATICALLY CHANGED");
  }

}

```

The difference here is you are altering the actual data in the database for the title of the View entity in your first implementation, versus in the hook, it would only change it during rendering, so really depends on use case (if the title was dynamic based on date or something, the hook might be better. Long term alteration, like in an update hook or something, probably would want to alter the actual data with the entity method) Both implementations should cache just fine.

---
Tags: views, 8
---


# Question
Title: Can we use math expression in Field collection
I have two fields in field collection i.e total\_amount and installment\_value. I want to divide total\_amount with installment\_value and display result in Result field. Can somebody resolve this issue for me as I tried with computed and math expression but unable to resolve the issue. Thanks

# Answer
First off, would this be for D7 or D8? I'm assuming you're using the node entity. I would think a good approach is to have the result field as a field on your node, make the calculation, and set the value in a hook\_node\_presave() (for D7, hook\_entity\_presave() for D8). At this point, the values are about to be stored to your DB, so you'd have access to your total\_amount and installment\_value values, and you can set your third "result" field to this computed value. You'd probably want to set the "result" field to not be visible to the end user, by setting it's `#access` to false in a `hook_form_alter()`, since anything they input would be overridden by your calculation anyway. I could provide you a more detailed answer if you can clarify which version you're on, or hopefully this can get you going in the right direction!
> 0 votes

---
Tags: entities
---


# Question
Title: How to import a display mode configuration from a custom module
I have a custom module with the file **config/install/core.entity\_view\_display.node.event.featured.yml** which contains config for a display mode called 'featured' for the content type 'event'.

The problem is, Drupal won't import these settings because the view mode 'featured' already exists.

I'm aware it already exists. I don't want to create the view mode. I want to simply import the settings for that view mode. I.e. populate the settings for each of the fields in that display mode.

Is there a way to do this without deleting the view mode before installing my module?

# Answer
Features may help you solve this problem - https://www.drupal.org/project/features . If you have Features enabled, and the module include a `mymodule.features.yml` file in it, it can gracefully handle updating existing configuration like this without throwing the nasty error. You can do a `drush fr mymodule` and it will import the new configuration without having to delete existing. As 4x4 was mentioning, this wouldn't be ideal for configuration site owners are changing, but if it's something you're updating and maintaining as the developer, it's an ideal route to go.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: How to use the value of a field in a filter criterion?
I created a comment view.

The parent content can be flagged and I want to display the comments posted since the date of the flag.

I added a hidden field "Date of creation of the flag".

I added a filter criterion (is greater than or equal to) "Date the comment was posted".

How to use the value of the flag in the filter criterion "Date of publication of the comment" ? there is no token and I have not found a module that can do that.

# Answer
You could write a custom Views filter plugin to handle your use case, I have found WebOmelette's tutorials invaluable over the years, and he has a great one for D8 Views filters: https://www.webomelette.com/creating-custom-views-filter-drupal-8. This will allow you to fine tune the query to your needs and do any kind of filtering that isn't available out of the box.
> 0 votes

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


# Question
Title: How to replace all Add To Cart buttons with alternative text in Ubercart for anonymous users?
I need to display the standard Add to Cart button for all logged in users, but anonymous users should instead see text and a link asking them to create an account or login in order to be able to add to cart. The code below works great, but it is applicable to individually-specific products only; I need it to apply to all products site-wide. How would I modify this code to accomplish this, given the fact that all Ubercart add to cart buttons contain the node ID and are thus all unique? the example shows the code applying to the product with node ID "3".

```
function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'uc_product_add_to_cart_form_3':
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            drupal_set_message('Please <a href="/user/login">login</a> or <a href="/user/register">create a free Member account</a> in order to proceed.');
            $form['html_markup'] = array('#markup' => t('<div class="login-to-buy">Please <a href="/user/login">login</a> or <a href="/user/register">create a free Member account</a> in order to proceed.</div>'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '<div id="form-button-wrapper">';
            $form['actions']['submit']['#suffix'] = '</div>';
        }
        break;
    }
}

```

Thanks!

# Answer
I think I've got the solution. Any feedback would be greatly appreciated.

```
<?php
function uc_disable_cart_button_for_anonymous_form_alter(&$form, &$form_state, $form_id) {
    /* Overrides the Add to Cart form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_product_add_to_cart_form_'.$node)):
        // hide add to cart button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('<div class="login-to-buy">Please login or apply for a Member account in order to proceed.<br><br><a href="/user/login" class="btn">Log In</a>   <a href="/user/register" class="btn">Apply for Member account</a></div>'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '<div id="form-button-wrapper">';
            $form['actions']['submit']['#suffix'] = '</div>';
        }
        break;
    }

    /* Overrides the Buy It Now form text*/
    if ( !empty($form['nid']) ) {
      $node = $form['nid']['#value'];
    }
    else {
      $node = 0;
    }
    switch ($form_id) {
        case (($form_id == 'uc_catalog_buy_it_now_form_'.$node)):
        // hide buy it now button for anonymous users and show text
        if(!user_is_logged_in()) {
            unset($form['actions']['submit']);
            $form['html_markup'] = array('#markup' => t('<div class="login-to-buy">Please login or apply for a Member account in order to proceed.<br><br><a href="/user/login" class="btn">Log In</a>   <a href="/user/register" class="btn">Apply for Member account</a></div>'));
        }
        if(user_is_logged_in()) {
            $form['actions']['submit']['#value'] = 'Add to Order';
            $form['actions']['submit']['#prefix'] = '<div id="form-button-wrapper">';
            $form['actions']['submit']['#suffix'] = '</div>';
        }
        break;
    }
}

```

The main drawback that I see is that the quantity and attribute fields are still displayed, but that could be good or bad based on use-case. I'd prefer to hide them, so I may try to figure that out.
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Path field not available in Search API View
Why is the "Path" field not available in a Search API view? Is there another way to get the path for each row in this type of view?

# Answer
`\/organize$`

`\/`: forward slash escaped

`organize`: letters "organize" matches the characters "organize" case sensitive.

`$`: Must be the end of the string.

Regex101
> 0 votes

---
Tags: search
---


title: Generate meta in controller

text:
# Question
Title: Generate meta in controller
I'm creating a custom module. This module displays public custom content without node and views . For this content custom page , I would like to add dynamic meta keyword and meta description .

I have read this excellent answer How do I add a meta tag in \<head\>...\</head\> section? and it said we can use

```
mymodulename_page_attachments(&$page)

```

and update variable

```
$page

```

But the meta contents are getting in a controller's method. For this raison, I would like to pass the meta contents to `mymodulename_page_attachments` hook.

How can I call and update `$page` in my controller module to do this ? Or how can I generate meta in my controller ?

# Answer
Service was the key to my problem .

After i understood Drupal services https://www.drupal.org/docs/8/api/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8

and

http://valuebound.com/resources/blog/how-to-define-your-own-services-drupal-8

It's easy to define dynamic keyword and meta to one page

```
function mymodulename_page_attachments(array &$page) {
    $currentUrl = Drupal::request()->get(Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_NAME);
    switch($currentUrl){
        case 'path_url':
        //call my service
          $description = array(
                '#tag' => 'meta',
                '#attributes' => array(
                    'property' => 'description',
                    'content' => /* value to my service return */,
                ),
            );

            $page['#attached']['html_head'][] = [$description, 'description'];
        break;

    }
}

```
> 0 votes

# Answer
hook\_page\_attachments() is only needed so you can attach it to any possible route/url. You should be to just add it directly to the response that you re returning, and it should bubble up and be added.
> 1 votes

---
Tags: 8, meta-tags, page-controller
---


# Question
Title: Using regex path pattern on Themekey module
Currently on the themekey config page for regex instructions it shows:

> regular expression, including delimiters and modifiers (see PHP Manual)

But is there an example of how to setup a url pattern whre I want to only match paths that end with **/organize**?

# Answer
This should do it:

```
node-alias ~ /\/organize$/

```
> 0 votes

---
Tags: 7
---


# Question
Title: How can I switch my already installed project to drupal-project?
I am trying to make my already installed drupal site to use drupal-project.

# Answer
> 1 votes
Drupal project just helps you setup a project. But you can just take a look at the project on Github and copy/paste files/folders to your project.

Or you could initiate a new drupal-project and move over your custom modules/themes and make your new project use the database of the old one.

---
Tags: composer
---


title: Change ckeditor table dialogue defaults

text:
# Question
Title: Change ckeditor table dialogue defaults
Quite simply the ckeditor table dialogue defaults to a table width of 500, yes the client should be told to delete that value, but I would like to alter the default table width value programmatically to 100%.

I have found other posts like this but in Drupal 8 land where do I do this?

# Answer
You can achieve this in several ways with a script we can call, for example, ckeditor\_settings\_modifier.js containing:

```
CKEDITOR.on('dialogDefinition', function(ev) {
  var dialogName = ev.data.name;
  var dialogDefinition = ev.data.definition;

  if(dialogName == 'table') {
    var info = dialogDefinition.getContents('info');
    info.get('txtWidth')['default'] = '100%';
  }
});

```

This script should be added in one of these places through libraries:

* only in the theme of your website (if you use it also for editing)
* in your administration theme in order it works in normal node edit mode, and in your website theme in order it works in quick edit mode
* in a custom module in which you can use for example some conditional rules that control the loading of the script.

In any choosen settings it is important to declare the dependency on the core/ckeditor.

This is the case of a module (my\_module containing a js folder with ckeditor\_settings\_modifier.js), in my\_module.libraries.yml:

```
ckeditor_settings_modifier:
  version: 1.x
  js:
    js/ckeditor_settings_modifier.js: {}
  dependencies:
    - core/ckeditor

```

in my\_module.module:

```
/**
 * Implements hook_preprocess_page().
 */
function my_module_preprocess_page(&$variables) {
  // add ckeditor_modifier in case the user has the role of administrator
  $roles = Drupal::currentUser()->getRoles();
  if(in_array('administrator', $roles)) {
    $variables['#attached']['library'][] = 'my_module/ckeditor_settings_modifier';
  }
}

```

It works on Drupal 8.4.4 and CKEditor 4.8
> 5 votes

# Answer
You really need to modify this `width=""` property value? In HTML5 this property is deprecated, anyway you can use it, and override it behavior via CSS (any value declared for the table through CSS will override the property value without need of use `!important` or something like that).
> -2 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Why is the old version of the module being used?
I am creating a module, and I tried to update its files. I disabled the module, uninstalled it, deleted its files and then I put the new files in the sites/all/modules/mymodule. Then, I enabled my module.

The problem is that Drupal somehow is using the old version of my module rather than the new files I added. I cleared all the caches, from Drupal and manual from MySQL, but nothing changed.

Anyone ever had the same issue? Any ideas?

# Answer
> 0 votes
When this has happened to me, it's because I have had the module in two locations and forgotten about it. Just search for the module's info file (using for example find - on Linux):

```
find /path/to/drupal_root -name mymodule.info

```

# Answer
> 0 votes
I had the same issue once. The problem was that by mistake, I had the routing file with the name of other controller or some naming problem like that. Also I'd suggest to increase your module version number.

---
Tags: 7
---


# Question
Title: How to propely add views grouped filters with exposed filter in one of them
I have a views with grouped filters like this

Group 1 field\_1\_condition AND field\_2\_condition (exposed)

OR

Group 2 field\_3\_condition field\_4\_condition

I am expecting it to work like this: Filtering is done based on the first group and input comes from user to the exposed filter field. Then I want the query to check the second group and add all the matching things from there.

The initial query seems to be correct but as soon as I give input to exxposed filter the query is wrong. Views tries to combine similar fields for some reason

Initial query with those groups:

```
SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, og_membership.gid AS og_membership_gid, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type
FROM
{node} node
LEFT JOIN {og_membership} og_membership ON node.nid = og_membership.etid AND og_membership.entity_type = 'node'
WHERE (( (node.type IN  ('birthday_event')) AND (og_membership.gid IS NULL ) AND (node.status = '1') )OR( (node.status = '1') AND (node.type IN  ('event')) ))
ORDER BY node_created DESC

```

The query when exposed filter gets input

```
SELECT DISTINCT node.title AS node_title, node.nid AS nid, node.language AS node_language, og_membership.gid AS og_membership_gid, node.created AS node_created, 'node' AS field_data_field_event_date_node_entity_type
FROM
{node} node
LEFT JOIN {og_membership} og_membership ON node.nid = og_membership.etid AND og_membership.entity_type = 'node'
WHERE (( (node.status = '1') AND (node.type IN  ('event', 'birthday_event')) AND (og_membership.gid = '1') ))
ORDER BY node_created DESC

```

This is the image of my views filter settings

# Answer
> 1 votes
I am still waiting for a response to do this more elegantly but since I am in a hurry I wrote a query alter to accomplish what I need. Maybe it's helpful to someone

```
function custom_views_query_alter(&$view, &$query) {
  if ($view->name == 'ts_group_events' && $view->current_display == 'calendar') {
    if (empty($query->where[2]['conditions'])) {
      foreach ($query->where[1]['conditions'] as &$condition) {
        if ($condition['field'] == 'node.type' && $key = array_search('birthday_event', $condition['value'])) {
          unset($condition['value'][$key]);
        }
      }
      $query->where[2]['conditions'][] = array(
        'field' => 'node.status',
        'value' => 1,
        'operator' => '='
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'node.type',
        'value' => array('birthday_event'),
        'operator' => 'in'
      );

      $query->where[2]['conditions'][] = array(
        'field' => 'og_membership.gid',
        'value' => NULL,
        'operator' => 'IS NULL'
      );
    }
  }
}

```

# Answer
> 0 votes
I have the same issue in Drupal 8. You are able to configure the grouped conditions but they aren't filtering as they are supposed to. I believe this is an already documented issue: https://www.drupal.org/project/drupal/issues/2168893#comment-11791770

---
Tags: views
---


# Question
Title: Drupal 8 hide meta tag fields in node form
I am just wandering is there a way to hide some of the input fields in MetaData while creating/editing a node.

For example, I want to hide,

Geographical place name and Geographical position,

that is in MetaData-\>Advanced, in node form, so that user doesnt have access to it while creating a node.

Anything like hook form alter?

# Answer
I'll make the assumption you're using the Metatag module (https://www.drupal.org/project/metatag).

Unfortunately, this module doesn't allow fine-grain control of fields through its UI, so the only way I've found to hide these fields is through a form alter.

In this case, I'm modifying all node forms (use whatever hook fits your scenario here). Example, hiding the "advanced" fieldset entirely by disabling access to it, so it's not rendered:

```
function MY_MODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['field_metadata']['widget']['0']['advanced']['#access'] = FALSE;
}

```

I'm sure this can be modified to target more specific nested groups/fields, but should give you a start at least!
> 2 votes

---
Tags: 8, forms, meta-tags
---


# Question
Title: How to alter standard.front_page in module links YML file?
I have a menu with a "Home" link which was "provided by the Standard module. The title and path cannot be edited."

I am trying to alter the text/link using my module's links.yml file like so:

```
standard.front_page:
  title: 'Home Test'
  route_name: '<front>'
  menu_name: main

```

However this has no affect on the menu link. Other entries in this file work just fine.

Is it possible to alter the link in this way, or is the only option to use one of the menu hooks such as hook\_menu\_links\_discovered\_alter

# Answer
> 4 votes
I usually use this the hook\_menu\_links\_discovered\_alter() in this way:

```
/**
 * Implements hook_menu_links_discovered_alter().
 */
function YOUR-MODULE-NAME_menu_links_discovered_alter(&$links) {
   // Changing the title.
   $links['standard.front_page']['title'] = 'Hi';
   // Changing the route.
   $links['standard.front_page']['route_name'] = 'block.admin_display';
}

```

But it seems that there are another ways in How to update a menu link created with MenuLinkContent::create()? and How do I programmatically update or delete menu items?

---
Tags: 8, navigation
---


# Question
Title: Programmatically Render a Node Edit form with a custom Form Display Mode
I'm attempting to make a page for users to edit data for a specific content type, but I only want them to have access to some of the fields not all. To do so I created a custom form display mode for content. I have a custom controller that is meant to display this form with a custom display mode. Here is the code meant to render it.

```
    public function showCustomForm() {
        $node = \Drupal::entityTypeManager()->getStorage('node')->load('123');
        $edit_form = \Drupal::entityTypeManager()->getFormObject('node', 'my_custom_form_display_mode_id')->setEntity($node);
        return \Drupal::formBuilder()->getForm($edit_form);
    }

```

And I get the error

> Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "node" entity type did not specify a "my\_custom\_form\_display\_mode\_id" form class. in Drupal\Core\Entity\EntityTypeManager-\>getFormObject() (line 184 of /var/www/mydomain/http/web/core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I was using this How do I load a form with a specific form display (form mode)? as an example. But still had no luck.

How would I programmatically load a node edit form with a custom form display mode?

# Answer
> 8 votes
The error message says you did not specify a form class, but what it really wants to say is, that you did not specify a form operation with the name of the form mode:

*mymodule.module:*

```
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['node']->setFormClass('my_custom_form_display_mode_id', 'Drupal\node\NodeForm');
}

```

The form operation needs a form class. This can be the same as for default, which you find in the handlers section of the annotations in the Node class.

---
Tags: 8, nodes
---


# Question
Title: What are some reasons unpublished content is visible to anonymous users?
The anonymous user role has no permissions to view/edit unpublished content. I'm wondering what kind of tests I can use to locate the bug, there is one module calling hook\_node\_access, but it returns `AccessResult::allowed();` on update operations `$op == 'update'` so it should not be affecting view operations. I'm stumped.

# Answer
The issue was a bug in node\_view\_permissions, updating to 8.x-1.2 solved the problem.
> 0 votes

---
Tags: users
---


title: How do I embed a view inside a node?

text:
# Question
Title: How do I embed a view inside a node?
In Drupal 6 a view can be embedded into a node as follows:

```
$viewName = 'LatestNews';
print views_embed_view($viewName);

```

This does not work for drupal 7. What is the function to embed views in drupal 7?

# Answer
In Drupal 7 you can use this code.

* For a view page

```
print views_embed_view('name_of_view','page_1', $node->nid);

```
* For a view block

```
print views_embed_view('faculty_core','block_1', $node->nid);

```
> 9 votes

# Answer
The EVA module can also attach views to nodes.
> 5 votes

# Answer
To display a view in a node template, you use the following code.

```
// Load the view.
$view = views_get_view('machine_name_of_view');
// Set the active display.
$view->set_display('your_view_display_name');
// Set any needed argument.
$view->set_arguments(array(arg(0), arg(1)));
// Execute the view.
$view->execute();
// Render the view.
print $view->render();

```
> 5 votes

# Answer
Why not:

```
print views_embed_view($view_machine_name, $view_display_name, $arg1, $arg2);

```

where $arg, $arg2, etc are optional.

Or use Viewfield module to embed a view as a field.
> 4 votes

# Answer
One solution is to use Panelizer to override the content of the respective node.

Lets say for example you have a handfull of one-off pages that need a view attached.

1) You could use the Page content type or maybe create a new content type that will specifically be panelized.

2) Enable Panelizer for that content type, make sure to set it up to "Allow per-record display choice" that way you can setup multiple panelizer displays that will be tailored to each one off page. (each panelizer display can have it's own set of views attached)

3) From here you simply create a view (I like to use Content Panes for this) and add it to the Panelizer content display of choice.

This allows you to re-use a single content type that doesn't really need it's own set of fields, but might potentially be used for either referencing other entities (as a field) or referencing views.

Throw in the Paragraphs module and you have a Swiss Army Knife content type. Speaking of, that would make a perfect name for the custom content type used for this purpose... Hmm....
> 1 votes

# Answer
Let's just mention that first parameter is view name, second display name and after that you can pass contextual filter parameters.

So that "$node-nid", the third parameter depends on you view...what it expects for first contextual filter - id doesn't have to be node id. Of course, you are not limited to one parameter - pass as many as you have in view...or pass none if your view doesn't have contextual filters.
> 0 votes

# Answer
A very configurable Drupal 7 and 8 module is views\_field\_formatter which allows you to embed a view as a fields formatter
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to add a contextual action link to a View?
I want to replace the default EntityListBuilder from a custom entity with a View, as it is much quicker to build that list interface with it.

However I want to retain the action button from the EntityListBuilder on the View itself, which is in the `links.action.yml`:

```
entity.room.add_form:
  route_name: entity.room.add_form
  title: 'Add Room'
  appears_on:
    - entity.room.collection

```

Would I just add the view identifier under `appears_on`? What would the format be for that string?

# Answer
> 6 votes
Figured it out not long after posting. The format is view.(view\_id).(display\_id):

```
entity.room.add_form:
  route_name: entity.room.add_form
  title: 'Add Room'
  appears_on:
    - entity.room.collection
    - view.rooms.rooms_admin

```

---
Tags: views, 8, navigation
---


# Question
Title: How to expose an entity reference field as a filter on a custom entity in Views?
I have a field on a custom entity that is an entity reference to a node. However when I select this field as a filter and expose it, it just acts like a numeric field instead of a reference field (only option is less than, greater than, equal to... etc).

How can I make this field act properly? I just want a drop down of options (only 32 nodes ever) to make filtering easy.

# Answer
> 0 votes
I think there are many solutions but I resolved the same problem in the hook hook\_form\_alter() altering the form element type from textfield to select and populate the #option attribute:

```
  $options = _getOptions();
  $form['your_field'] = [
    '#type' => 'select',
    '#options' => $options,
  ];

```

Other solutions are appreciated.

---
Tags: views, 8
---


# Question
Title: Locked out of the site, and new users can't get in
I have an odd problem. My new Drupal 8 site is a distro, purchased from ThemeForest. After installing it, I thought I created a new user correctly but maybe the name had disallowed characters. In any case, after logging out for the first time, I can't get back in, even when using the browser-stored un/pw or my stored record. I then created a new user in Drush, elevated it to admin, and still can't get in, saying it doesn't recognize the user. I tried applying for new password, but when I try the link, I get this:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

So then I thought, maybe I should have set my trusted domains to fix the error in the Status Report. I then edited my settings php to set my domain as trusted, similar to what I did for another Drupal 8 site that is side-by-side in the same public\_html folder.

However, one difference is that the site I'm now locked out of is being redirected by htaccess. I had to do this because my hosting service by default wants to put my primary-domain site in the root of public\_html, and I wanted it in a subfolder, just like the other sites. So I created this htaccess rule to point the main domain to a particular folder:

```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.mydomain.com$
RewriteCond %{REQUEST_URI} !folderitresidesin/
RewriteRule (.*) /folderwhereitresides/$1 [L]

```

Those are the most relevant facts I can think of. Now the question is: does this htaccess redirect affect login? Do I need to do anything to make sure Drupal understands this htaccess redirect? Or is it something else?

I've looked into the "Drupal\Core\Routing\TrustedRedirectResponse" message but that seems to b aimed at redirecting to external urls. I don't see how that applies to me.

Thanks in advance to any good samaritan who can help!

# Answer
> 0 votes
For a while it seemed that adding localhost to the Trusted Host settings in settings php did some good, then I realized it didn't so I removed it, leaving just the lines below:

```
$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';
$settings['trusted_host_patterns'] = array(
'^mydomain\.com$',
'^.+\.mydomain\.com$',
);

```

I think the Trusted Host settings is critical for several reasons. But then out of the blue I somehow found I can enter the site by logging into

mysite/user/login

Even though it throws the error page with this message:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

However I'm actually logged in. All I have to do is append the site folder name to the path then I'm in.

http://www.mysiteurl/sitefolder/

In fact, I can just log in by going to

http://www.mysiteurl/sitefolder/user/login

The sitefolder added to the URL seems to be an alternate url for the entire site. I don't know if that will cause a problem but at least most of my problems are solved for now.

I hope this helps somebody. It seems to result from shared hosting not letting me install my primary site to a subfolder in public\_html without making a fancy adjustment in htaccess.

---
Tags: 8, redirection, .htaccess
---


# Question
Title: Theming paragraph fields from entity reference in view
I have a `view` (Drupal 8) where I load my `entity reference` field (display hidden), with three fields from a `Paragraph type` and a certain custom display).

The HTML markup looks like this now:

```
<div class="paragraph paragraph--type--par-organization-employee paragraph--view-mode--relationship-details-org-view">
  <div class="field field--name-field-par-organization-reference field--type-entity-reference field--label-hidden field__item">
    <a href="/node/9" hreflang="nl">Sogeti</a></div>
  <div class="field field--name-field-par-phone-number field--type-telephone field--label-hidden field__items">
    <div class="field__item">020-55883366</div>
  </div>
  <div class="field field--name-field-par-email field--type-email field--label-hidden field__item">
    <a href="mailto:test@sogeti.nl">test@sogeti.nl</a>
  </div>
</div>

```

I can't find a way how to theme the fields. I don't get any template suggestions.

# Answer
> 0 votes
I had a situation where i had to theme entity reference fields that were used in a view. Have you tried any of these?

1. Setup a view mode for the Paragraph type, set view Format to Show Content where the view mode was set to the one you needed, and then i themed the view mode
2. Use a hook\_preprocess\_hook to get all the results from a View and then store them in the $variables\['fields'\] and then you modify the twig template for the view

This relies on Views Template Files and Debugging Twig templates

---
Tags: views, 8, entities
---


# Question
Title: Drupal Commerce Product SKU pane not showing after upgrade
After performing an upgrade of a Drupal 7 site (core and modules), including Drupal Commerce, the Product SKU pane is not showing up on my panels page. I'm able to add it to my panels page and there are SKU's for the product.

Why is this happening?

# Answer
SOLUTION: I've found setting the View Mode to "Product List" makes this appear correctly.
> 0 votes

---
Tags: commerce, panels
---


# Question
Title: How to reference existing taxonomy terms in a migration
I'm trying to migrate nodes with a term reference field. The terms are not migrated and already exist in the destination site. There is a method in the migration class which is confirmed to already select the correct term ID on the new site.

When the migration is run an error appears:

```
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'migration_db.taxonomy_index' doesn't exist:    [error]
SELECT 1 AS expression
FROM
{taxonomy_index} taxonomy_index
WHERE ( (nid = :db_condition_placeholder_0) AND (tid = :db_condition_placeholder_1) AND (status =
:db_condition_placeholder_2) ); Array
(
    [:db_condition_placeholder_0] => 2290
    [:db_condition_placeholder_1] => 4
    [:db_condition_placeholder_2] => 1
)
 (/home/vagrant/docroot/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:770)

```

The migration appears to be trying to get the term data from the migration database instead of the destination (default) database.

migrate plus yml:

```
...
process:
  field_section: Section
...

```

migration class:

```
class MyNodeMigration extends SqlBase {
  public function query() {
    return $this->select('TableA', 'ta')
      ->fields('ta', ['Id', 'Body', 'OriginalId']);
  }
 ...
  public function prepareRow(Row $row) {
    $row->setSourceProperty('Section', $this->convertToTermId($row->getSourceProperty('OriginalId'));
  }

  public function convertToTermId($original_id) {
    return $this->getDatabase()->select('TableB', 'tb')
      ->fields('tb', ['DrupalTermId'])
      ->condition('OldId', $original_id)
      ->execute()
      ->fetchField();
  }
}

```

-------------UPDATE-------------

I've also tried using a custom plugin. The same error occurs. Plugin class:

```
/**
 *
 * @MigrateProcessPlugin(
 *   id = "existing_term"
 * )
 */
class MigrateProcessExistingTerm extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $term = Term::load($value);
    return [
      'target_id' => $term->id(),
    ];
  }

}

```

Updated yml:

```
...
process:
  field_section:
    plugin: existing_term
    source: Section
...

```

# Answer
> 0 votes
I was able to solve the issue by moving the queries for the term ID to the process plugin.

```
/**
 *
 * @MigrateProcessPlugin(
 *   id = "existing_term"
 * )
 */
class MigrateProcessExistingTerm extends ProcessPluginBase {
  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    db_set_active('my_migration');

    $sub_task_id = db_select('TableA', 'ta')
      ->fields('ta', ['OriginalId'])
      ->condition('Id', $value)
      ->execute()
      ->fetchField();

    $term_id = db_select('TableB', 'tb')
      ->fields('tb', ['DrupalTermId'])
      ->condition('OriginalId', $original_id)
      ->execute()
      ->fetchField();

      db_set_active('default');

    $term = Term::load($term_id);

    return [
      'target_id' => $term->id(),
    ];
  }

}

```

It seems like having the queries in the main class were confusing the migration into thinking the term data was in the migration source database.

# Answer
> 0 votes
I was able to simply do this with the migration\_lookup plugin:

```
 tid:
   plugin: migration_lookup
   migration: categories
   source: id

```

---
Tags: 8, taxonomy-terms, entities, migrations
---


# Question
Title: Drupal 8 Custom Composite Entity Select Field
Does anyone have an example of how I add an Entity Select (Specifically a term reference) to a custom composite?

Here's the code I've tired. The field with the title shows up but no select.

```
$elements['test_tax'] = [
  '#type' => 'entity_select',
  '#title' => t('Test Taxonomy'),
  '#target_type' => 'taxonomy_term',
  '#selection_handler' => 'default:taxonomy_term',
  '#selection_settings' => [
    'target_bundles' => [
      'my_terms' => 'my_terms'
    ],
    'sort' => [
      'field' => 'name',
      'direction' => 'ASC'
    ]
  ]
];

```

I'm a front-end guy so I'm a bit out of my element in php...

# Answer
I think you just need to change...

```
'#type' => 'entity_select',

```

...to...

```
'#type' => 'webform_entity_select',

```

In the Webform YAML source editor we are hiding the 'webform\_\*' prefixes, within custom code they have to included.

@see https://cgit.drupalcode.org/webform/tree/src/Element/WebformEntitySelect.php
> 4 votes

---
Tags: webforms
---


# Question
Title: Is it possible to use a condition set component as a parameter for another component?
Some of my Rules (say they are part of a collection *S*) execute in their actions Rules components of the following form: If *conditions A* and *conditions B*, then do *actions*. Now, *conditions A* and *actions* are always the same; only *conditions B* changes according to the particular Rule in *S*.

It is frustrating to add the same conditions and actions to the Rules components every time. Therefore, my idea is to enclose every *conditions B* in a Rules conditions component, and then use those components as a variable in 1 "abstract" Rules component that captures the above pattern. Is that possible?

# Answer
This answer provides a way to capture the following common pattern for Rules: "If *conditions A* and *conditions B*, then do *actions*" for fixed *conditions A* and *actions*. Instead of creating a separate condition set component for every *conditions B* (and then use those components inside some kind of "abstract" Rules component as a variable), the following approach is way easier:

1. Create a condition set component for *conditions A*, say *My component for conditions A*.
2. Create an action set component for *actions*, say *My component for actions*.
3. For every *conditions B*, create a new Rule.
4. For every new Rule, add *My component for conditions A* to the conditions, and *My component for actions* to the actions. Then, complement the conditions with *conditions B*.

Result: we fixed the never-changing *conditions A* and *actions* in 2 Rules components. That saves us a lot of redundant repetitive work. If we want to implement 10 cases of the general pattern, then we end up with 10 Rules + 2 Rules components = 12 Rules in total.

Let's compare this approach with the initial idea. We would have to create 10 Rules components for the *conditions B* \+ 1 "abstract" Rules component + 10 Rules that contain this "abstract" Rules component in their actions = 21 Rules in total.

The advantage of the proposed alternative approach is less Rules in total. The disadvantage is that every Rule needs to include the same action set and condition set components. But to be honest, adding those 2 components to the Rules takes much less clicks and time than creating new Rules... I think this problem nicely illustrates the power of action sets and condition sets in the Rules module (a feature that might seem somewhat obscure for beginners).
> 0 votes

---
Tags: 7, rules
---


# Question
Title: View for Entity Reference reverse, backwards forwards
The need is to present in a landing page a view of all pages that do reference to this landing page. So, this view will search in other content type, to find in a reference field that contain same id.

Landing page content type have several nodes children.

Page content type have a Entity reference field\_back\_parent for a node parent

Content types Landing page (1) parent, Page (2) child, Page (3) child,

I would like to this using UI in admin. So, no entityQuery in this opportunity.

# Answer
> 7 votes
* No additional module need to be installed.
* No coding needed. Just site building for Drupal 8.
* First we need to check if our content types are ready.

Landing page content type, don't need any change. Page content type need a field of type **Entity reference**.

* **Add field** -\> Add a new field = Reference Content

Then in Edit tab chose your kind of content type (parent)

After Save you will get...

Now go to admin/structure/views and + **Add view**

In this case we are going to check the option to **create a block**

In ADVANCED

**Add Relationship** for our field\_back\_parent in Page content type. *This important to connect the two content types.*

You need to tick **Require this relationship**.

In ADVANCED

Then **Add Contextual** filter for our current content type Landing Page. *In this way, we will get our actual node id to be used in the view. So, now we can find only the pages that have same node id in field\_back\_parent.*

So find by ID (Content)

Select the relationship name.

Check **Provide default value** -\> **Content ID from URL**

Then you will get something like this:

In Relationship you must to have the word **Content** in the rightside

This is the result of our settings

If you click in **Update preview** you will corroborate that it doesn't display anything.

You must to add the node id from parent. In our case is the node 2 from Landing page.

Other way for reference https://mushtaqtahir.com/blog/4/drupal-8-reverse-entity-reference-in-view

I hope that this info help you.

---
Tags: 8, entities, views
---


# Question
Title: Function build() only render first array with for loop
Currently working on a custom module and I'm trying to render a set of arrays that are created through a *blockForm* and a *blockSubmit* this ones are working correctly. *blockForm* is creating the fields of the form correctly and *blockSubmit* is saving the data of the fields correctly. I tested this several times with positive results. And this two are working with a *FOR* loop.

Now i'm trying to render the data of this *blockForm* with `public function build()` and a FOR loop. But is only rendering the first array and as it is configurated at the moment is should be four arrays.

This is the code:

**FssContentBlock.php**

```
<?php

namespace Drupal\fss_content\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Fussion Content Block' Block.
 *
 * @Block(
 *   id = "fss_content",
 *   admin_label = @Translation("Fussion Content Block"),
 *   category = @Translation("Fussion Content Block"),
 * )
 */

class FssContentBlock extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {//ONLY RENDER FIRST ARRAY...
    $config = $this->getConfiguration();
  $config2 = \Drupal::config('fss_content.settings');
  $config2->get('fss_content.paragraphs');
  $qtty = $config2->get('fss_content.paragraphs');

   for ($i = 0; $i < $qtty; $i ++) {
     $i = $config['fss_content_paragraph'][$i];
     $block1 = array
       (
        $i => array
         (
          '#prefix' => '<p>',
          '#suffix' => '</p>',
          '#markup' => t('@i', array('@i' => $i,)),
         ),
       );
   }

    $block2 = array
      (
        'test' => array
        (
          '#markup' => $qtty . '<p>' . $i . '</p>', //TESTING $qqty VALUE. IT IS CORRECT... BUT WEIRD $i VALUE...
        )
      );
    $allblocks = array_merge($block1, $block2);
  return $allblocks;

/* //THIS CODE WORK... BUT NEED IT TO WORK WITH (FOR - LOOPS)
    $p0 = $config['fss_content_paragraph']['0'];
    $p1 = $config['fss_content_paragraph']['1'];
    $p2 = $config['fss_content_paragraph']['2'];
    $p3 = $config['fss_content_paragraph']['3'];

    $block = array
        (

      'p0' => array
            (
       '#prefix' => '<p>',
       '#suffix' => '</p>',
             '#markup' => t('@p0', array('@p0' => $p0,)),
            ),
      'p1' => array
            (
       '#prefix' => '<p>',
       '#suffix' => '</p>',
             '#markup' => t('@p1', array('@p1' => $p1,)),
            ),
      'p2' => array
            (
       '#prefix' => '<p>',
       '#suffix' => '</p>',
             '#markup' => t('@p2', array('@p2' => $p2,)),
            ),
      'p3' => array
            (
       '#prefix' => '<p>',
       '#suffix' => '</p>',
             '#markup' => t('@p3', array('@p3' => $p3,)),
            )

    );
    return $block;  */
  }//End build

  /**
  * {@inheritdoc}
  */
  public function blockForm($form, FormStateInterface $form_state) { //THIS WORK...
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $config2 = \Drupal::config('fss_content.settings');
    $config2->get('fss_content.paragraphs');
    $qtty = $config2->get('fss_content.paragraphs');

    $form['fss_content_paragraph'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
    );

    for ($i = 0; $i < $qtty; $i ++) {
      $num = $i + 1;
      $form['fss_content_paragraph'][$i] = array(
        '#type' => 'textarea',
        '#title' => 'Parrafo N°' . $num,
        '#default_value' => isset($config['fss_content_paragraph'][$i]) ? $config['fss_content_paragraph'][$i] : '',
      );
    }

  return $form;

  }
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) { //THIS WORK...
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();

    $config2 = \Drupal::config('fss_content.settings');
    $config2->get('fss_content.paragraphs');
    $qtty = $config2->get('fss_content.paragraphs');

    for ($i = 0; $i < $qtty; $i ++) {
      $this->configuration['fss_content_paragraph'] = $form_state->getValue('fss_content_paragraph',$i);
    }
  }//End blockSubmit

}//End Class

```

**Explanation of how the module work:**

* The module has a configuration option that sets the amount of fields the Administrator user needs.

* Then the form with the amount of fields is created:

* And this is what my code is rendering at this moment:

As you can see is rendering the first array but nothing else.

Now, if you take a look at the test i'm making the `$qtty` value is correct witch is the value of the amount of fields i need.

But the last value of `$i` is weird *(last\_value\_$i = "ABCE")*. Because is taking the first three characters of the first array *(First\_array = "ABCD")* and the first character of my second array *(Second\_array= "EFGH")*

Any ideas how can i solve this problem? Thank you!

# Answer
After hours and hours... i finally found the correct way to implement this for loop at `function build()`

This is the final code:

```
<?php

namespace Drupal\fss_content\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Fussion Content Block' Block.
 *
 * @Block(
 *   id = "fss_content",
 *   admin_label = @Translation("Fussion Content Block"),
 *   category = @Translation("Fussion Content Block"),
 * )
 */

class FssContentBlock extends BlockBase implements BlockPluginInterface {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
  $config2 = \Drupal::config('fss_content.settings');
  $config2->get('fss_content.paragraphs');
  $qtty = $config2->get('fss_content.paragraphs');

  for ($i = 0; $i < $qtty; $i++) {
    ${'p' . $i} = $config['fss_content_paragraph'][$i];
    $block1['p' . $i]['#prefix'] = '<p>';
    $block1['p' . $i]['#suffix'] = '</p>';
    $block1['p' . $i]['#markup'] = ${'p' . $i};
  }

  return $block1;

  }//End build
  /**
  * {@inheritdoc}
  */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $config2 = \Drupal::config('fss_content.settings');
    $config2->get('fss_content.paragraphs');
    $qtty = $config2->get('fss_content.paragraphs');

    $form['fss_content_paragraph'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
    );

    for ($i = 0; $i < $qtty; $i ++) {
      $num = $i + 1;
      $form['fss_content_paragraph'][$i] = array(
        '#type' => 'textarea',
        '#title' => 'Parrafo N°' . $num,
        '#default_value' => isset($config['fss_content_paragraph'][$i]) ? $config['fss_content_paragraph'][$i] : '',
      );
    }

  return $form;

  }//End blockForm
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();

    $config2 = \Drupal::config('fss_content.settings');
    $config2->get('fss_content.paragraphs');
    $qtty = $config2->get('fss_content.paragraphs');

    for ($i = 0; $i < $qtty; $i ++) {
      $this->configuration['fss_content_paragraph'] = $form_state->getValue('fss_content_paragraph',$i);
    }
  }//End blockSubmit

}//End Class

```

Hopefully some day this will help someone else...
> 0 votes

---
Tags: 8, entities, blocks
---


# Question
Title: Is there a way to automatically cancel an account after 14 days?
I'm working on a website where we are offering trial access and I want a way to automatically cancel an account after the account is more than 14 days old EXCEPT if they have submitted a feedback form in which case they get an additional 7 days (for a total of 21 days).

I think there ought to be a way to do this using Rules or cron but right now I'm stuck.

# Answer
> 0 votes
Sure you can do this, using the Rules module (and the Webform module for your form). Here is a blueprint about how to do so:

### 1. Rules Component to block a user

Create a (rather basic) Rules Component to "block" a user, whereas you use a "User" entity as parameter for it.

### 2. Rule to cancel an account

Create a (rather basic) rule like so:

* Rules Event: Before saving a user account
* Rules Conditions: None (feel free to add whatever fits)
* Rules Action: Schedule the execution of the Rules Component (from step 1), to be executed after 14 days. For this you need to have the "Rules Scheduler" (a sub-module of Rules) enabled. Make sure to use an "id" for this scheduled task that includes the user's uid (you'll need it in Step 3).

Refer to my answer to "How to send an email notification reminder based on a user's date of entry field?" for a sample of a rule that is pretty close to what your rule should look like (especially Step 3 of it).

### 3. Rule to delete the scheduled rule

Use the Webform Rules module to create a rule like so:

* Rules Event: After a webform has been submitted
* Rules Conditions: Check the webform Id (to ensure it's the form you want to consider).
* Rules Action: Delete the Scheduled rule from Step 2, and Reschedule it to be executed 21 days after there account activation date. For this you'll need the id of the Scheduled task, but if you used the user's uid for that, this should be no problem.

PS: I'm assuming this is about D7 ...

# Answer
> 0 votes
You can do this using hook cron or rules also
contrib module available for your requirement https://www.drupal.org/project/user\_expire

---
Tags: 7, users
---


# Question
Title: How to create a view of all recent activity on a site?
I want to create either a view or a module (preferably view) to display all recent activity on the site such as a new user joined in, a user read some article or blog, a user gained some points and so on...the display should be as:

```
User x just joined in
User y just got 30 points for creating a blog
User Z just read Some Article

```

I tried doing so using the Message, Views and Rules modules, but I was able to do so (only for one specific event such as User x created a blog ...).

**Note**: I want to create new events in Rules. I wonder how to use a message type to get different messages to be displayed. I am following this tutorial, but I wonder how to add more messages such as "*\[user\] gained \[user-points\]*", etc and be sure that it is displayed when that event triggers. Also what data selector should I choose in Rules?

# Answer
The Message module is great, really! But still poorly documented. However, have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module, together with the Rules module. What follows is a summary of what's included in this tutorial.

> You can use the Message module in combination with the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).
>
> Here is a blueprint of what you'd need:
>
> 1. Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
> 2. Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in '*Which user related token(s) can be used to create a Rule for setting up a message type?*' for some examples.
> 3. Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as *Replacement tokens* that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
> 4. Use Views to display the created messages in the format you prefer.

Some more details specific to your question here:

* For each of the 3 activities you want to record, define an appropriate (corresponding) Message Type (using the Message module). Let's name those message types like M1, M2, ... for now.
* For each of the activities you want to record, there is an appropriate Rules Event you can take advantage of. If you'd just create a custom rules (1 for each activity to record, let's name those rules like R1, R2, ... for now), it's a matter of combining each rule with a Rules Action to "Create an entity" (i.e. of type "Message"). E.g. Rule R3 should have a Rules Action to create a message of type M3.
* I bet sooner or later you're going to run into the issue that you want to create a message using a token which is NOT made available by only the Message module. E.g.: Assume that for recording an activity like "*User X just commented on ...*") you want the message to also include the actual comment body (text) that was posted. But the Message module doesn't offer any relevant token related to that comment body. In that case, you can use the approach/solution as documented in 'What's the purpose of "Replacement tokens" of a Message type?', which is basically a technique to create your custom tokens (the comment body in the example here) and make them available to the Message module (so that you can include them in the message to be created).
* Obviously, creating appropriate views of these messages (which are just entities) should be straight forward.

### More info about the Message module

There is *not a lot of documentation* available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:
> 2 votes

# Answer
You should take a look at the Heartbeat module.

> Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.
> 1 votes

# Answer
If you enable views module you will see a default view called **Tracker** that lists all new activity in the system. Enable it. You can change the view setting to suite your needs.
> 0 votes

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


# Question
Title: Can show the recently viewed content based on the User?
I have used the statistics module for showing the most recently viewed content in a view. But the content will be added only by the administrator.

In Relationship, I can get only the content:author. so the user who have created the content they can only view the content. If the user are not authored any content, the result will not be shown.

How could I pass the current user in the contextual filter without the content:authored.

Or how could I customise the statistics most recently viewed view based on the user id instead of using flag+rules modules and recently viewed module.?

# Answer
You can user recently\_read Module for show history of the recent viewed nodes. Hope this will help.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: User profile image's alt text shows special characters
The user profile image's alt text shows HTML entities instead of quote characters in usernames like *Derek O'Rourke*, for which the alt text is shown as *`Derek O'Rourke's picture`*.

How can I avoid that happens?

# Answer
> 1 votes
Assuming Drupal 7, in the template.php of your theme, add this function:

```
function themename_preprocess_user_picture(&$variables) {
  $variables['user_picture'] = htmlspecialchars_decode($variables['user_picture'], ENT_QUOTES);
}

```

The problem arises from the `template_preprocess_user_picture()` function in `user.module.` It passes the alt text through the `t` function, which in turn calls `htmlspecialchars()` and it is here the apostrophe is encoded as `'`

In your theme function, the HTML code of the user picture tag will be available in `$variables['user_picture']`. Passing the HTML code through `htmlspecialchars_decode()` will convert `'` back to an apostrophe.

---
Tags: media
---


title: How to add html tags in drupal 7 menu?

text:
# Question
Title: How to add html tags in drupal 7 menu?
I would like to add `<br>` tag or ` ` character to html menu, but when I type `Home <br> Page`, it does display as plain text, but I want to break that words by two lines.

How can I modify my template.php file with hooks, to allow html tags in menu titles?

# Answer
> 4 votes
Maybe your problem can be solved using the Menu HTML module. It seems to have been designed to solve issues such as the one you describe.

> This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. The idea is to use this for external links for which you want to display a logo of the visited site or simply to add strong on some words.

# Answer
> 1 votes
Actually it depends on which menus you want to change, but for main and secondary menus you should be able to add this to your theme\_preprocess\_page function :

```
function yourtheme_preprocess_page(&$variables, $hook) {
    foreach ($variables['main_menu'] as &$link) {
        $link['html'] = TRUE;
    }
}

```

for secondary menu replace `['main_menu']` by `['secondary_menu']`

# Answer
> 0 votes
Other method in template.php, for main\_menu in the example below:

```
function THEMENAME_links__system_main_menu($vars) {
  foreach ($vars['links'] as &$link) {
    $link['html'] = TRUE;
  }
  return theme_links($vars);
}

```

# Answer
> 0 votes
In template.php of your theme. This allows html in all menu links.

```
function THEMENAME_menu_link(array $variables) {
  foreach($variables as &$variable) {
    $variable['#localized_options']['html'] = TRUE;
  }
  return theme_menu_link($variables);
}

```

# Answer
> 0 votes
I found this to work perfectly when added to your (sub-)theme's `template.php`, with `YOURTHEMENAME` replaced by your (sub-)theme's name:

```
function YOURTHEMENAME_link($variables) {
  $variables['options']['html'] = TRUE;
  return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
}

```

It is an override of the `theme_link()` function defined in `drupal/includes/theme.inc`; only the `$variables['options']['html'] = TRUE;` line was added.

Source: https://www.drupal.org/node/112352#comment-5890386

# Answer
> 0 votes
Did not want to use the Menu HTML as you need to check mark each menu link.

Here is how I did it programmatically:

```
function THEMENAME_preprocess_menu_link(array &$variables) {
  $element = &$variables['element'];
  foreach ($element as $value) {
    if (strpos($element['#title'], '<div class="test">') === false) {
      $element['#title'] = '<div class="test">' . $element['#title'] . '</div>';
      $element['#localized_options']['html'] = TRUE;
    }
  }
}

```

---
Tags: 7, routes
---