# Question
Title: Date Time field machine name/view mode for theming using paragraphs
I am using Drupal 8 core DateTime Range module and Date module in core to list date start and end date.

I have set various criteria and allowed content editors to set date/time under certain ranges with paragraphs module for events.

1. Event only has date. Created a date field using paragraphs module.
2. Event has date with start and end time. Created a date field and datetime range field with only time ranges using paragraphs module.
3. Event has start and end date. Created a datetime range fields using paragraphs with date ranges using paragraphs m.
4. Event has start and end date with time. Created two datetime field one with date ranges and another with time ranges using paragraphs.

Now for theming I need to target each field separately as each field represents different format and style. However while using paragraphs inside node and adding any one of datetime field to node using paragraphs does not allow me to determine which field it is or what view mode that datetime field is using.

This makes it difficult to theme those fields individually/seperately.

Also, while using views pages and rendering those datetime field on a pager based page view, same, it does not show what machine name/view mode its using for paragraphs.

I implemented *hook\_theme\_suggestions\_time\_alter* function to determine the machine name and view mode, but no information was available for said field.

I would like to each part of field in datetime field separately and differently while rendering using views and differently while rendering in full view mode of node.

# Answer
The best way to Debug this is to enable twig debug open up or create sites/default/services.yml

change

```
 http.response.debug_cacheability_headers: true
 twig.config:
   auto_reload: true
   cache: true
   debug: true

```

once done run drush cr or clear your cache

then go to the page with the paragraphs on them and inspect the element in chrome you will see ... some thing like

```
<!-- FILE NAME SUGGESTIONS:
  * field--paragraph--field-range--event.html.twig
  * field--paragraph--field-range.html.twig
  * field--paragraph--event.html.twig
  * field--field-range.html.twig
  * field--daterange.html.twig
  x field.html.twig
  -->

```

then theme the new field templates to your liking
> 1 votes

---
Tags: views, 8, theming, nodes, datetime
---


# Question
Title: Constraint handling for @DataType (Typed Data API)
I am creating a new data type, 'duration'. The value will be a duration string that is used by a DateIntervale object.

The value is a string, but with a specified format. I'm assuming that due to it being a string, for my @DataType I should either extend StringData, or PrimitiveData. And I would like to add required validation to this data to ensure that the value contained is in the correct format.

I've been reading through documentation, and reverse engineering other @DataType objects, but I've not been able to find what I'm looking for. So what I want to specifically ask:

1. Should I extend StringData, or is it better to extend PrimitiveData?
2. How/where can I add a constraint onto this data. By this I mean, what method should I use to ensure that when someone calls setValue() using this data, the string can be validated using a regex to ensure it's the proper format.
3. If the value is not the proper format, how is this handled? Is there a way to call an error? Should I throw an Exception? Or should I set a default value instead of the value that was supposed to be submitted?
4. Am I looking at this the right way?

Thank you.

# Answer
> 1 votes
In abstract class PrimitiveBase that uses PrimitiveInterface... which StringData entends you can see the PrimitiveInterface use of PrimitiveInterface methods:

getValue(); , setValue($value);, getCastedValue();

so you can safely do ether however ... Personally as your data is realy a string I would go with the extend StringData option

and call parent functions like

```
 public function getValue() {
   return parent::getValue();
   or
   $this->parent->getValue();
 }

 public function setValue($value) {
    // CRAZY REGX HERE
   $new_value = $this->getREGXCRAXY($value);

   return $this->parent->setValue($new_value);
 }

 public function  getREGXCRAXY($value) {
    do the things.
  if value !== valid
 throw new \Exception('Invalid data dude must be in format xyz');
  return $new_formated_value;
 }

```

no i think it is proper to throw the exception because then the person can catch it in an event subscriber .. or learn the right way to set the data.

---
Tags: 8
---


# Question
Title: Comment template for specific comment type
How can I have a comment template (`comment.html.twig`) per comment type?

The Twig Template naming conventions documentation explains how I can get a comment template per node content type (`comment--node-[type].html.twig`), but it doesn’t mention comment types.

I have a node content type with multiple comment fields (one for each comment type), so filtering by node content type doesn’t help me.

# Answer
Enable Twig Debugging, then you'll get template suggestions printed as HTML comments directly into the markup.

I did that and got the following output:

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'comment__field_my_comment_field__article' -->
<!-- FILE NAME SUGGESTIONS:
   * comment--field-my-comment-field--article.html.twig
   * comment--field-my-comment-field.html.twig
   x comment.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/content/comment.html.twig' -->

```

So, the templates are supposed to be named like the following pattern:

```
comment--field-name-of-the-comment-field-in-the-content-type--content-type.html.twig
comment--field-name-of-the-comment-field-in-the-content-type.html.twig

```
> 1 votes

# Answer
The best way to Debug this is to enable twig debug open up or create sites/default/services.yml

change

```
 http.response.debug_cacheability_headers: true
 twig.config:
   auto_reload: true
   cache: true
   debug: true

```

once done run drush cr or clear your cache

then go to the page with the comment on them and inspect the element in chrome you will see ... some thing like

```
<!-- FILE NAME SUGGESTIONS:
 XXXXXX
  -->

```

then theme the new comment template file to your liking
> 0 votes

---
Tags: 8, theming, comments
---


# Question
Title: How can I make changes to "people" page?
Drupal have a list of users with following link - `my_site/admin/people` I have some boolean field for every user and I want to show on this page users, who have `true` value of this field. How can I manipulate the content of `people` page.

# Answer
Easiest way to do this: enable Administration Views, this would provide you with a view for "/people" page.

> Replaces administrative overview/listing pages with actual views for superior usability. Filter users by name, ban/blocked status, or user roles.

Use a filter setting boolean field to "true" or expose this filter to allow admins to filter people by "true" or "false"
> 0 votes

# Answer
In drupal7 site /admin/config/people/accounts/fields option is there, you have to add boolean filed and choose type then it will reflect to peoples page.
> 0 votes

# Answer
On url my\_site/admin/config/people/accounts/fields you have the possibility to add extra fields to the user account. If you add the field there it will appear on the people page.
> -1 votes

---
Tags: 7
---


# Question
Title: How to get the list of nodes edited by an specific user?
I need to be able to see all the nodes that have been edited by an user and be able to download that info, I've been searching for a module but I can't find one.

On the log messages report I can see that info but I can't download it and also it only shows the data for the last month.

# Answer
You can also use Views to export that data for you, here are the rough steps,

1. Create a Page view which shows content.
2. Select the fields you want to see for the node like nid, title, author, etc.
3. Add Author as a filter and expose this field so that you can provide user id or username via the exposed filter form.
4. Save the view.
5. The page view should now work on the URL you provided in step 1. Here once you provide a username or user id (depending on which field you exposed) the content should get filtered.
6. Add a module like views\_data\_export, which allows you to export the list in a file.

These are very rough steps but you can play around with it to get it working, let me know if you need exact steps.
> 1 votes

# Answer
This is how i ll get all nid of revision of an user :

> All node revision are store in the node\_revision table.

```
  $connection = \Drupal::database();
  $query = $connection->query("SELECT DISTINCT(nid) FROM node_revision where revision_uid = 1");
  $result = $query->fetchAll();
  //devel module
  kint($result);

```

node\_revision aren't entity so the only way you have is to do a manuel query.

> And if you need to filter by content type :

```
      $connection = \Drupal::database();
      $query = $connection->query("
      SELECT DISTINCT(node_revision.nid)
      FROM node_revision
      LEFT JOIN node ON node_revision.nid = node.nid
      WHERE node_revision.revision_uid = 1 and node.type='page'"

);
      $result = $query->fetchAll();
      //devel module
      kint($result);

```

In this table you can get the revision\_log field too.

Then you can use entityManager for load all your node :

```
 \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

```

you need to build your $nids array with the query result.

You can load all revision too by node id.
> 0 votes

# Answer
For Drupal 8 with the following code you can get the nids that have been edited by the user:

```
// List of modified nodes.
$modified_nodes = [];
// The user id.
$uid = 5;
//Load all the nodes.
$nodes = \Drupal\node\Entity\Node::loadMultiple();
foreach($nodes as $node) {
// Getting the revisions for each node.
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);
foreach ($vids as $vid) {
  // Loading revision.
  if ($revision = node_revision_load($vid)) {
    // Checking the uid and the owner.
    if($revision->getRevisionAuthor()->id() == $uid) {
      $modified_nodes[] = $node->id();
      break;
       }
    }
  }
}
// To use dpm you need the devel module.
dpm($modified_nodes);

```
> -1 votes

---
Tags: 8, nodes
---


title: Show sql queries when load content

text:
# Question
Title: Show sql queries when load content
I'm working with the data from a Drupal 7 site that I have and I need to extract the data from a table with a relation to another table. The problem is that one of the tables is **Node** table and the other is **field\_data\_field...** that has a **target\_id**.

The queries I have tried are not connecting the data correctly between this tables. I know this because when I go to the content page (http://example.com/ca/content/aalto-erick) the data is not the same.

Is there a way to display the SQL queries that executes the server when displays this content page?

PD: I put the url to show that the info is displaying in a content page.

# Answer
Yes. The Devel module has a submodule called Web Profiler. Once the Web Profiler module is enabled, there will be toolbar in the footer. The toolbar contains a DB inspection button signified by a DB "stack" with the number of queries performed and the time to perform them. Click the button will show you a profile of the DB queries made in the last request.
> 2 votes

# Answer
Yes. The Devel module has "Display query log” settings, You can this or have another way to get this through by hook\_query\_alter or hook\_query\_TAG\_alter hooks. You can use this reference link.

How To Print SQL String Using Devel Module
> 0 votes

---
Tags: nodes, database
---


# Question
Title: Form elements removed during custom page render
In a table, I keep a collection of nodes, text and forms that should be rendered on particular generated pages. I run through a loop that builds an output variable based on the the tables type and values. Worked fine in D7 and the text and node pieces are working fine in D8, after some adjustments. The piece I'm having trouble with is adding a form to the output variable.

In D7:

```
$output = "a variety of html";
$formname = "triagezipform"; //would be filled in by field value
$form = drupal_get_form($formname);
$output .= render($form);

```

In D8:

```
$output = "a variety of html";
$formname = "triagezipform"; //would be filled in by field value
$form = \Drupal::formBuilder()->getForm('Drupal\triage\Form\'.$formname);
$output .= render($form);

```

I see the form properly at the end of the function that builds the output, but as it goes through Drupal page rendering the Form elements are removed.

Pre-page rendering:

```
<div class='triage-action-form ta-contrast-background noprint '>
  <form class="triagezipform" data-drupal-selector="triagezipform"               action="form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM" method="post" id="triagezipform"
                  accept-charset="UTF-8">
<div class="form-item js-form-item form-type-textfield js-form-type-textfield form-item-triage-zip js-form-item-triage-zip form-group">
  <label for="edit-triage-zip" class="control-label">Enter zipcode where your legal issue is</label>
  <input data-drupal-selector="edit-triage-zip" class="form-text form-control" type="text"id="edit-triage-zip" name="triage_zip" value="04643" size="20" maxlength="5"/>
</div>
</form>

```

Post-page rendering:

```
<div class="form-item js-form-item form-type-textfield js-form-type-textfield form-item-triage-zip js-form-item-triage-zip form-group">
          Enter zipcode where your legal issue is
</div>

```

Any ideas of how I get forms to show properly when being built this way?

# Answer
How are you then using $output? Are you putting it into \['#markup'\] in your build array?

If so markup content will strip all sorts out. So either you can put $form as a separate item in your build array and there's no need to run it through render()

Or you can use drupal's "inline\_template" rather than #markup in the build array
> 0 votes

---
Tags: theming, forms
---


# Question
Title: How to translate custom content block title?
How do I properly translate custom content block titles?

Problem:
I've got a custom content block with just one CKeditor text field. I want to show the custom block title and the text field. When I place that block, the PLACED block title is copied from (but not referencing) the custom content block.

When a content translator later translates that custom content block, the PLACED block title is wrong/untranslated. Is there a way to reference the correctly translated, custom content block title in block placement? E.g. using tokens?

NOT allowed solution:
Giving translators access to block placement to translate the block placement is an absolute no-go. They are only allowed to use custom block library.

Unwanted workaround:
I know I could create an additional fake-title field and disable "Show title" in block placement. But I really hope I can avoid this, or I would have to modify all my existing block templates.

# Answer
> 5 votes
To use the title from the custom content block entity (not the title from the block placement config):

```
function mymodule_preprocess_block (&$variables) {
  if ($variables ['elements'] ['#base_plugin_id'] == 'block_content') {
    $variables ['label'] = $variables ['content'] ['#block_content'] ->label ();
  }
}

```

This also respects translations and does not require access to block placement for translators.

---
Tags: 8, blocks
---


title: Installation error with Composer

text:
# Question
Title: Installation error with Composer
I'm trying to install Drupal 8 with Composer. Drupal Console is already installed (in case that's relevant), so I go to my localhost folder (working locally) and type:

```
composer create-project drupal-composer/drupal-project:8.x-dev cmpsprjct --stability dev --no-interaction

```

Everything runs well with the composer installation in the terminal. When I try to proceed with the installation in the browser I get following error:

```
Additional uncaught exception thrown while handling exception.
Original

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 806)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 272)
Drupal\Core\Form\FormBuilder->buildForm('install_select_language_form', Object) (Line: 898)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1324)
install_select_language(Array) (Line: 670)
install_run_task(Array, Array) (Line: 548)
install_run_tasks(Array) (Line: 117)
install_drupal(Object) (Line: 44)

Additional

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('html') (Line: 298)
Drupal\Core\Render\Renderer->doRender(Array, 1) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, 1) (Line: 139)
Drupal\Core\Render\Renderer->Drupal\Core\Render\{closure}() (Line: 576)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 140)
Drupal\Core\Render\Renderer->renderRoot(Array) (Line: 66)
Drupal\Core\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 76)
Drupal\Core\ProxyClass\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 1004)
install_display_output(Array, Array, Array) (Line: 264)
_drupal_log_error(Array, 1) (Line: 584)
_drupal_exception_handler(Object)

```

I have searched in Google and found that a composer update could solve the problem, but it didn't. Any hints about how to proceed?

Working with Ubuntu 17.04 and php 7.1

# Answer
> 16 votes
Please make sure your webserver (nginx/apache) is using the same PHP version as your cli one. For example, you may encounter this issue if your cli PHP version is PHP 7.1 and your webserver is using PHP 7.0.

# Answer
> 7 votes
For Ubuntu 16.04 I had to run the following commands to adjust the PHP version used by Apache:

```
sudo a2dismod php7.0
sudo a2enmod php7.2
sudo service apache2 restart

```

# Answer
> 3 votes
I removed all php dependencies:

```
sudo apt-get remove php*

```

I installed php again:

```
sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached

```

Restarted Apache

```
sudo service apache2 restart

```

There is the installation screen!

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


# Question
Title: How to redirect custom ajax form to external url
When setting the form with ajax handler like this

```
  public function buildForm(array $form, FormStateInterface $form_state) {
    //...

    $form['actions']['submit'] = array(
      //...
      '#ajax' => [
        'wrapper' => 'custom_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    );
  }

```

and trying to set the redirect on `submitForm`

```
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = 'https://example.com';
    $form_state->setResponse(new \Drupal\Core\Routing\TrustedRedirectResponse($url, 302));
  }

```

nothing happens and no error message appears but the form seems like it has finished processing.

When the ajax part is taken out the action:submit array the form redirects properly on submit. What should be done differently ?

# Answer
You can't return a redirect response, because the ajax script in the browser expects a json array with jquery commands, so you need to return a RedirectCommand from the ajax callback:

```
  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $command = new RedirectCommand('https://example.com');

    return $response->addCommand($command);
  }

```

which then assigns window.location to redirect client-side.
> 4 votes

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


# Question
Title: Placing Drupal core/modules code outside public_html
I've been trying to improve my sites security as I build a Drupal 8 update for my page. One thing I've seen recently is keeping your core code outside the web accessible docroot folder. I've also heard about keeping a copy of the code setup on git so you can easily bring down a clean copy if somehow someone changes something.

What is the current best practice for such a thing? On my server I have an account for the page, within which is public\_html where anything actually being sent out to the world is kept. Is it possible to have the Drupal code one level down and then have things run from public\_html?

# Answer
> 1 votes
There is some work being done to move as much of core out of DOCROOT, but this is complicated by assets that need to be web accessible, mainly JS, CSS, and images. So, moving core/modules outside DOCROOT is tough because many of those have all three.

Current thinking is to place the vendor directory outside of DOCROOT to help reduce attack surface area. Since using composer for all site building is also essentially a best practice now, the drupal-composer/drupal-project template does this, and also will place modules, themes, libraries, and other Drupal stuff in the proper place, while keeping vendor non-web accessible, as it contains the non-Drupal specific dependencies.

# Answer
> -2 votes
You just move your code into under public\_html folder with the same permissions.

---
Tags: security
---


# Question
Title: Rule fetches only single taxonomy term from multiselect values
I have created a Rule which is supposed to fetch all the selected term from a taxonomy term field (a field that holds a list of taxonomy terms). But when the rule is executed, it fetches only one taxonomy term instead of all. The field is set to hold "unlimited" values.

**Rule is:**

```
Entity type = taxonomy term
Condition => content-type = course
Data selector => node:field-autodealer:name

```

The rule is supposed to add all users from selected groups into a course.

# Answer
What you included n your question (with "Rule is"), does nto really look like a rule to me, rather something that is part of your rule. However, since you're trying to process a multi value field, a crucial part of a working rule is a Rules Action to perform a **Loop**. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should (at least) have a Rules Action to create a loop related to your field *that holds the list of taxonomy terms*. After you do, you should iterate over each item in that list. And for each iteration you should then perform the desired Rules Actions.

***Done***

PS: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.
> 1 votes

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


# Question
Title: How can I programmaticaly submit the user edit form in Drupal 8?
I need to create a logout button in my app, and I do not know how to revoke simple\_oauth tokens programmatically, but I have noticed if the user saves their profile form (form\_id: "user\_form") in Drupal, it revokes the user's access token.

So I'm wondering if there is a way to programmatically submit the form so I can do so in a logout endpoint for my app.

That is, unless someone can point me to the specific code that revokes a user's access token when the user edit form is saved, so I can fire that hook more directly.

Because the oauth2\_token table does not reference the associated user (auth\_user\_id is always zero), I don't know how to look up a token by UID for the purpose of revoking the token. Thus, even though it seems like a hack, the only thing I can think to do is to try to submit the user edit form programmatically.

UPDATE: I was wrong about "auth\_user\_id is always zero". See my answer below.

# Answer
I was mistaken when I said "auth\_user\_id" is always zero. It isn't. It contains the user's ID, as you would expect. That makes this task fairly simple. Here is the function for my logout endpoint:

```
public function logout($name = NULL) {

    if ($name) {
      $user = user_load_by_name($name);
      if ($user) {
        $uid = $user->id();

        $msg = 'User ' . $name . ' (uid: ' . $uid . ') logged out of app.';
        \Drupal::logger('orb_common')->notice($msg);

        // Not sure if it would be a better practice to set the status to zero, or delete.  In this example I delete the row.
        $query = \Drupal::database()->delete('oauth2_token');
        $query->condition('auth_user_id', $uid);
        $query->execute();
      }
    }

    $response['data'] = [];
    $response['method'] = 'POST';

    return new JsonResponse($response);
  }

```

In my routing file I have...

```
orb_common.orb_common_logout:
  path: '/orb_common/logout/{name}'
  defaults:
    _controller: '\Drupal\orb_common\Controller\CommonController::logout'
    _title: 'Logout'
  requirements:
    _permission: 'edit activity entities'

```

The JsonResponse at the end of my logout function presumably isn't important in this case. The main thing is to pass a UID or username to Drupal in the URL of the endpoint, and then delete/update the relevant row in the oauth2\_token table. At least, that is working in my app.
> 1 votes

# Answer
Logging the user out through Drupal itself should revoke the user's access token.

Try invoking `UserController::logout`.
> 0 votes

# Answer
You dont need to submit the form programmatically, all you need to do is to call user\_logout() in your logout API endpoint. This should invalidate all the session tokens.

FYI you should check the Drupal 8 REST API docs, there is a core endpoint for logging out current user. Check this URL below,

https://www.drupal.org/docs/8/core/modules/rest/javascript-and-drupal-8-restful-web-services
> 0 votes

---
Tags: 8, forms, authentication-authorization
---


# Question
Title: javascript hack added to every body field - how can I global search and replace?
In the last week it seems that all my drupal sites were hacked. One problem I have is that a javascript was inserted at the beginning of every content body field. Attached is an image.

I have literally hundreds of nodes with the script maliciously added. Does anyone have a simple suggestion for how I can remove this script from all the nodes?

Note: I'm not php savvy. Just a drupal user who has built a few web sites.

Thanks

# Answer
> 0 votes
For other newbies like me, here's what I did to fix the problem. In phpMyAdmin select the drupal database.

Just to be safe, you might want to Export the database in case anything goes wrong.

Once you've backed up, select the SQL tab.

Then check that you can find the string with the

```
SELECT * FROM `field_data_body` WHERE `body_value` LIKE "%<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>%";

```

If the command above works, then you can use

```
UPDATE `field_data_body` SET `body_value` = REPLACE(`body_value`,"<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>","")

```

to delete the string with the script.

---
Tags: nodes, javascript, search
---


# Question
Title: How to Add Existing File to file_managed. File is Blank
I have manually added some files to the Private Files directory on my Drupal 7 site and wish to add them to the `file_managed` table in the database.

**This is what I have attempted:**

1. Load the existing file with the file\_get\_contents($PATH\_TO\_FILE) function.
2. Used the file\_save\_data($loaded\_file, $destination, FILE\_EXISTING\_REPLACE) function save the file and add it to the Database.

**The Result:**

1. *The expected file is in the File System but is 0 bytes and blank*
2. File is added to Database

The main issue is that the existing file isn't getting uploaded properly and is being displayed blank. How can I fix this?

# Answer
Make sure that your $loaded\_file is a file object enter link description here not just a file content.
> 2 votes

---
Tags: 7, files
---


# Question
Title: Drupal change the number of items in view PHP
I have a view page that show 10 elements. The idea is to make three buttons for the user to select if he wants to display 10 elements, 20 elements or 30 elements in the view page. Is there any way to do in PHP? I have search in Google but I can't find anything.

I know I can change in the View config -\> Pager:

# Answer
insert HTML markup on the View header and make three buttons with HTML markup and then link each of the button like

```
<ul>
  <li><a href="/search?items_per_page=10">10 elements</a></li>
  <li><a href="/search?items_per_page=20">20 elements</a></li>
  <li><a href="/search?items_per_page=30">30 elements</a></li>
</ul>

```

After this you can style the button however you want.
> 1 votes

---
Tags: views
---


# Question
Title: Why does 1 webform look different to another on the same drupal 7 site
I inherited a D7 website which has an existing `webform` that has a professional look. I am able to access this webform for editing purposes. When I add a 2nd `webform` to the site and use similar fields it doesn't inherit the same style with options not aligning correctly with their tick box, the tick box being smaller and using a different color.

The only thing that’s different is there was an “Application Form” of content type `Application` which has a url alias that when viewed shows the original `webform` but besides that I can’t see how it connects to 1 particular webform either from the webform to the page or from the page to the webform.

Can anyone point me to where I start looking to understand why 1 `webform` is styling differently to another on the same site?

# Answer
Inspect the html tag and check CSS class and ID of all the element of the form. Looks like its easy to make fix in css.
> 0 votes

---
Tags: webforms
---


title: Restore role visibility in blocks

text:
# Question
Title: Restore role visibility in blocks
I upgraded my Drupal 8 site from 8.4.5 to 8.5 and I noticed the role visibility in blocks disappears. I did a clean install and it's in Drupal Core, so the problem is not with my upgrade. I am thinking it's in the database but I have no idea how to track it. Does anyone know how?

# Answer
> -1 votes
I had the same problem. Solved it by editing the content of the block. (we logged in as admin you see a button in the right upper corner, click it and select Edit). It appeared the the translated content was not published.

# Answer
> -1 votes
1. Go to /admin/people
2. Edit your admin account
3. Ensure the "admin" checkbox is checked under the Roles section.

---
Tags: 8, blocks
---


# Question
Title: Subscribe all users to Simplenews Newsletter
We just installed Simplenews module. Is there a way to subscribe all our current users to one of the newsletters we created. This will be used to send important website updates. Therefore we don't want to skip users that have been registred to date.

We have a few thousands users, so a manual process will not work. Can this be done in the mysql database?

# Answer
Figured it out.

1. Go to Mysql and output the user\_field-data table as a csv. Delete all the columns except the user emails.
2. Copy all the user emails to the clipboard.
3. Go to Admin People Simplenews

You will see options to Mass Subscribe.
4. Paste the emails on the form. Select the newsletter and wait for a while.

If you have a long email list break it down in 500 or 1000 records at a time or the server may time out.
> 0 votes

---
Tags: 8
---


# Question
Title: Does page.tpl.php get overwritten on updates?
Does page.tpl.php get overwritten on Drupal updates or are edits safe because it's in the theme folder? For some reason the developer put the footer HTML in here instead of creating a block for it... why I don't know.

# Answer
For an drupal core update, you transfert every files/ folder except the **sites** folder for drupal 7.

Because in this folder, you have the setting.php and all your modules (custom or contrib) and your theme.

For module update, you can use the drupal ui or transfert the module update in the sites/all/modules folder.

So normaly, your theme and your page.tpl.php cannot be overide by an drupal core update.
> 0 votes

---
Tags: theming
---


# Question
Title: Anchor links to views grouping field titles
I want to make a table of content block where I link to the grouping field titles on a view. The problem is that the grouping field is only a h3 without any class or id. Is there a way to nest the h3 in a div with an unique ID so I can create an anchor link for it?

# Answer
I think this may be a template modification task.

This is the current views-view-unformatted.html.twig file:

```
{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

```

Switch:

```
<h3>{{ title }}</h3>

```

With:

```
<h3 id="{{ title | clean_class }}">{{ title }}</h3>

```

This would require your titles to all be unique to ensure unique ID's. There may be something better to use than "title" for the ID as well in this case.

Also, I would wonder if using an "attachment" in the view might give better options and control over a block for the table of contents...
> 0 votes

---
Tags: views, 8
---


title: AJAX dropbutton link

text:
# Question
Title: AJAX dropbutton link
I have a dropbutton in an admin view. It's currently got links built using URL::fromRoute

I want one of these links/buttons to work asynchronously.

This is what I currently have:

```
$dropdownButtons = [
    '#type' => 'dropbutton',
    '#links' => [
      'a' => [
        'title' => $send_verification_link_text,
        'url' => $send_verification_email_url,
      ],
      'b' => [
        'title' => $this->t('Remove person'),
        'url' => $remove_person_url,
      ],
    ],
  ];

```

# Answer
> 1 votes
I assume these are links to Ajax enabled route yes ?? i hope so lol any way heres is how ... see this example from a list builder:

```
$parent['operations']['data']['#links']['clone'] = [
  'title' => $this->t('AJAX!!!'),
  'weight' => 2,
  'url' => Url::fromRoute('someroute_name', ['id' => $entity->id]),
  'attributes'=> [
    'class' => 'use-ajax'
  ]
];

```

all you need to do is add 'attributes'=\> \['class' =\> 'use-ajax'\] more info see my old comment ... https://api.drupal.org/comment/62725#comment-62725

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


title: Merging numbers into one field in YAML

text:
# Question
Title: Merging numbers into one field in YAML
I'm trying to use a Webforms to create a team registration form, but I was thinking to automatically generate a participants ID number in the Webform based on certain fields in the form and based on user attributes.

The ID number is composed of 5 different fields.

1. A group code, this is independent on the form that is being submitted
2. A organization code, this is a multi-organization team registration, so each organization is given a specific code embedded into a participants ID number
3. Team code, each group of people (or team) is also given a specific code
4. Person Code, each individual person is given a number so we can distinguish persons in a team.

All of these codes are already set on the form (either through the registering user's attributes) or via the form itself. The user will not have to enter any of these attributes.

I understand in Microsoft Excel that you can combine 4 different fields by the following

=A1&&A2&&A3&&A4

But is there something similar in YAML code for Webforms?

Thanks!

# Answer
The Webform module for Drupal 8 supports a Computed Twig element which can be used to combine and calculate a dynamic value using Twig based on multiple elements.
> 0 votes

---
Tags: webforms, 8
---


# Question
Title: Overwrite field description in an image widget
I have an image field (multiple).

In the node form, the ImageWiget has a `process` method that adds previews and form fields for images that have already been uploaded.

The description for the title tag is hard-coded on line 278: `'#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.')`. We are actually showing the title as a caption and not a tooltip.

How can I override the description?

# Answer
Using hook\_field\_widget\_form\_alter You can do this:

```
function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($context['field']['field_name'] == 'field_image_top') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element

      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state, $form) {
  // Change the title field label and description

 $element['title']['#description'] = 'SOME NEW DESCRIPTION HERE.';
 return $element;
}

```
> 0 votes

# Answer
Using a hook\_form\_alter() you will be able to change that '#description' inside the structured $form array.
> -1 votes

---
Tags: 8
---


# Question
Title: Likeit module count for an entity refrence field in drupal 8
I have Enabled the Like it! module for a content type called "**recipe**" on my website. I am able to get the value of like count for the recipe in node--recipe.html.twig. Now, in the same content type, I have an entity reference field for recommended recipes. I need to render the value of count for recommended recipes in my node--recipe.html.twig file. what changes are required and in which files please if anyone knows then help? I have very little idea about modules.

Using Drupal 8.5

> content\['\_field\_layout'\]\['content'\]\['likeit'\]\['#count'\]

gives me the value of count for recipe.

# Answer
> 0 votes
Just use hook\_preprocess\_hook() and get the referenced entities values.

```
function YOURTHEME_preprocess_node__recipe(&$variables){
  kint($variables);
}

```

For **kint()** you need to enable **devel kint** module.

Pass each entity like below:

```
$like_count = likeit_get_count($entity);

```

This will provide the likes of the entity that you have passed. Once you get the count pass it in your **node--recipe.html.twig**

---
Tags: 8
---


# Question
Title: Set custom cache expiration time for a block
When returning info for a custom block we can specify what kind of caching that will be used for the block according to the values in: `hook_block_info()`. Notice that if the block is cached the `hook_block_view()` will not be called at all. In a module I'm developing I would like the user to be able to set the expiration time for the block cache, so I have tried something like this:

```
/**
 * Implements hook_block_info().
 **/
function CUSTOM_MODULE_block_info() {
  return array(
    'custom_block' => array(
      'info' => t('Custom Block'),
      'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

/**
 * Implements hook_block_configure().
 **/
function CUSTOM_MODULE_block_configure($delta = '') {
  $form = array();
  $form['custom_module_cache_expire'] = array(
    '#type' => 'textfield',
    '#title' => t('Cache expire'),
    '#default_value' => variable_get('custom_module_cache_expire', 0),
  );
  return $form;
}

/**
 * Implements hook_block_view().
 **/
function CUSTOM_MODULE_block_view($delta = '') {
  $block = array();
  if ($delta == 'custom_block') {
    $cache = &drupal_static(__FUNCTION__);
    if (empty($cache)) {
      // Try to get data from cache.
      $cache = cache_get('custom_module');
      if (!empty($cache->data)) {
        // Check the expiration time.
        if (time() > $cache->expire) {
          // Remove the cache.
          cache_clear_all('custom_module');
        }
        $block = $cache->data;
      }
      else {
        // Build the renderable array and cache the result for 5 minutes.
        // The 'custom_module_get_items()' is a long running task and
        // the reason why we want to cache this block at a certain interval.
        $block['content'] = array(
          '#items' => custom_module_get_items(),
        );
        cache_set('custom_block', $block, 'cache', time() + (60 * 5));
      }
    }
    else {
      $block = $cache->data;
    }
  }
  return $block;
}

```

The above almost works as expected, but I was wondering if there some better way of doing this.

In Drupal 8 we can use the `cache max-age` to achieve this behavior.

I also tried to set the `cache` in the renderable array for the block, but I'm not sure what this does actually:

```
$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
    'expire' => time() + (5 * 60),
  ),
);

```

Perhaps the best way would be to simply set the caching to `DRUPAL_NO_CACHE` for the block and then in `custom_module_get_items()` use `cache_set()` and `cache_get()`?

I was also thinking that another way of doing this might be to just remove the default block cache from the database at a specific interval?

# Answer
Here is a possible answer which is two-fold:

1. Make use of Drupal's render cache through the `#cache` property: This seems the more 'appropriate' and 'elegant' way for caching for your case since you want to cache on the presentation layer.
2. Purge the cache object manually (instead of periodically) by using a global timestamp variable that holds the last time the cache object was purged: This will allow you to clear only the relevant cache that interests you, instead of affecting multiple other caches.

**Regarding the 1. part:**

Using the render cache would mean producing a render array that looks like this:

```
$block['content'] = array(
  '#pre_render' => array('custom_module_prerender_items'),
  '#cache' => array(
    'expire' => DRUPAL_CACHE_CUSTOM,
    'cid' => 'custom_module_cid',
    'bin' => 'custom_module_bin',
  ),
);

```

This implies the existence of a `custom_module_prerender_items()` that is called whenever the (render) cache object is not available. **That function should wrap all expensive function calls.**

**Regarding the 2. part:**

Your `CUSTOM_MODULE_block_view()` function can now perform a cache clearing when needed and returns - consistently - a render array as described above. For example:

```
/**
 * Implements hook_block_view().
 */
function CUSTOM_MODULE_block_view($delta = '') {
  $block = &drupal_static(__FUNCTION__, array());
  if ($delta == 'custom_block' && empty($block)) {
    // Check if it's time to clear the caches.
    $custom_module_cache_expire_cache_cleared_timestamp = variable_get('custom_module_cache_expire_cache_cleared_timestamp', -1);
    $custom_module_cache_expire_minutes_interval = variable_get('custom_module_cache_expire_minutes_interval', 0);
    if (time() - $custom_module_cache_expire_minutes_interval*60 > $custom_module_cache_expire_cache_cleared_timestamp) {
      // Remove the specific cache.
      cache_clear_all('custom_module_cid', 'custom_module_bin');
    }
    // Assemble render array.
    $block['content'] = array(
      '#pre_render' => array('custom_module_prerender_items'),
      '#cache' => array(
        'expire' => DRUPAL_CACHE_CUSTOM,
        'cid' => 'custom_module_cid',
        'bin' => 'custom_module_bin',
      ),
    );
  }
  return $block;
}

```

Finally, the `#pre_render` callback, which wraps the expensive function, could look sth like this:

```
function custom_module_prerender_items($elements) {
  // Expensive function call.
  $items = custom_module_get_items();
  // Further processing...
  $processed_items = _custom_module_render_items($items);

  // Constructing the render array.
  $elements['custom_content'] = array(
    '#items' => $processed_items,
  );
  return $elements;
}

```

N.B.: Better use `DRUPAL_CACHE_CUSTOM` in your block definition, similar to `forum_block_info()`: Semantically meaning, "We will handle caching on our own"; practically meaning, no caching applied from the block module.

Refs:
> 3 votes

# Answer
There is a real live example of custom cache for drupal 7 in forums:

Asis in Core forum module:

```
    /**
     * Implements hook_block_view().
     *
     * Generates a block containing the currently active forum topics and the most
     * recently added forum topics.
     */

function forum_block_view($delta = '') {
  $query = db_select('forum_index', 'f')
    ->fields('f')
    ->addTag('node_access');
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
        ->orderBy('f.last_comment_timestamp', 'DESC')
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
        ->orderBy('f.created', 'DESC')
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }

  $block['subject'] = $title;
  // Cache based on the altered query. Enables us to cache with node access enabled.
  $block['content'] = drupal_render_cache_by_query($query, 'forum_block_view');
  $block['content']['#access'] = user_access('access content');
  return $block;
}

```

Here *drupal\_render\_cache\_by\_query* does caching based on query result.

> Prepares an element for caching based on a query.
>
> This smart caching strategy saves Drupal from querying and rendering to HTML \>when the underlying query is unchanged.
>
> Expensive queries should use the query builder to create the query and then \>call this function. Executing the query and formatting results should happen in \>a #pre\_render callback.

As in quote query executing and rendering happens in hook\_block\_pre\_render() as in forum.

Another Example:

```
$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
   'cid' => 'custom_module',
   'bin' => 'cache',
    'expire' => time() + (5 * 60),
  ),
);

```

The above code is similar to what you did with cache\_get, cache\_set methods in much similar terms with less code, as *drupal\_render()* function handles this for you setting up cache using *drupal\_render\_cache\_set()*.

You can read more from here: ADVANCED CACHING WITH RENDERABLE CONTENT

As for cache policy when you are caching stuff with custom code in hook\_block\_info *DRUPAL\_CACHE\_CUSTOM* and *DRUPAL\_NO\_CACHE* has no difference. However, using *DRUPAL\_CACHE\_CUSTOM* for custom caching is better standard.

Check out Block Caching for drupal 7.
> 3 votes

# Answer
I think you have to use this for the cache:

```
$expire = time() + 3600;
$block['#cache'] = array(
        'cid' => 'custom_data',
        'bin' => 'cache',
        'expire' => $expire
      );
cache_set(' custom_data', $navigation, 'cache', $expire);

```

Hope this helps you.
> 0 votes

---
Tags: 7, blocks, caching
---


# Question
Title: Repeated elements in translations of a block view
I have a small problem when translating taxonomy terms inside of a block view.

View configuration:

Output:

The translation is correct but the element quantity is incorrect. The idea is to have one of each term in each block regardless of translation.

# Answer
> 2 votes
You have to add a filter:

**FILTER CRITERIA**

```
Taxonomy Term: Translation language (= Content language selected for page)

```

or if the content language is not available when configuring the filter:

```
Taxonomy Term: Translation language (= Interface text language selected for page)

```

Otherwise you get a row for each translation, which are then all rendered in the same language, the one of the page, because you have configured this in the section **Language** in the middle column of the View.

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


title: Relationship with webform submission

text:
# Question
Title: Relationship with webform submission
I have a view displaying a list of nodes. Each node has a webform submission related, and the sid is stored in one field "field\_sid".

I'd like to be able to access the submission data in the node view, using a relationship thanks to the sid field.

Is there a good and efficient way to do this?

# Answer
You have to use `hook_views_data_alter()`.

```
function mymodule_views_data_alter(&$data) {
  if (isset($data['webform_submitted_data']['data_numeric'])) {
    if (!isset($data['webform_submitted_data']['data_numeric']['relationship'])) {
      $data['webform_submitted_data']['data_numeric']['relationship'] = array (
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'nid',
        'label' => t('Referred node'),
      );
    }
  }
}

```
> 0 votes

---
Tags: 7, webforms, views
---


# Question
Title: unable to set CONTEXTUAL FILTERS according to Raw Value from Url
In my project having two type of Content Type 1) Artist and 2) Work

I have added the content for the Artist and now also i have added the content for the Work according to Artist Name having field name `(Artist field_artist Entity reference)`

On view Page i want to show the result according to the artist

```
http://localhost/drupal8/artists-works/robert

```

According to name `robert` i have set the `CONTEXTUAL FILTERS` and `Relationship`.but its not showing any result when removed the filter its showing all the work content type type How can I set CONTEXTUAL FILTERS and Relationship according to this

# Answer
> 1 votes
You need to add a relationship to the content, and use the title (or whatever field contains "robert") as the contextual filter instead.

Currently the query that's getting built is trying to find content with an ID of "robert", which won't work as `nid` is numeric.

---
Tags: nodes, views, blocks
---


# Question
Title: Address module PHP error due to missing interface
I've installed the Address module and run Composer. I've checked the CommerceGuys/Addressing dependency is present. This was working fine, until a recent update (I'm not sure whether it was Drupal 8.2 or Address beta 4), but now the site is giving the following error.

```
PHP Fatal error:  Interface 'CommerceGuys\\Addressing\\Model\\AddressFormatInterface' not found in /var/www/drupal/sites8/all/modules/address/src/Entity/AddressFormatInterface.php on line 16, referer: https://www.google.com/

```

Can anyone halp?

James

# Answer
The command Bojan offered above did the trick:

```
composer update drupal/address --with-dependencies

```

This gave the following message:

```
Nothing to install or update
Generating autoload files

```

However, the site now displays correctly and doesn't log the message posted above.

Since it didn't seem to install anything, I presume it was the Autoload files that were the problem.

Thanks!
> 2 votes

# Answer
If you update Drupal 8 with `drush`, and not composer, this will re-install the required address libraries:

```
composer require drupal/address

```

run in the Drupal root directory.
> 2 votes

---
Tags: 8, commerce
---


# Question
Title: UTMs stopped being caught on webform submission
Forms has `hidden` inputs in the components to **collect UTM values** from the URL.

Once the form was filled in, the submission appeares correctly in the results table, both the public fields like the name, surname, etc ... as the content of the utm.

Recently, the new forms created do not store utm values, not even the cloned forms of a functional form.

Identical forms, in some takes the UTMs (forms with some time), in others not (created / cloned recently). Even shown in the same view.

I have tried to see with the devel module if there was a failure when interpreting the forms or the `hidden` fields ... without result.

Any idea or direction where the problem could go?

Thanks for your time.

# Answer
> 1 votes
The answer here provides the method you can use to pass URL query variables into hidden fields in webform.

What you need to do is assign a default value to each field which uses a token representing the query variable. So, for example, the field for "utm\_unidad" should have a default value of:

```
[current_page:query:utm_unidad]

```

And so on for the other fields.

---
Tags: webforms
---


title: Time field for form API

text:
# Question
Title: Time field for form API
When I use datetime field without date I get the message below. I want to provide a field for time only.

This code is correct but still has the problem of the time field.

```
<?php

namespace Drupal\ets\Form\Sejours_sportifs;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
use Drupal\file\Entity\File;

/**
 * Class SejourSportif.
 */
class SejourSportif extends FormBase {
  public $liste = array();

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'sejour_sportif';
  }

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

    $form['#cache'] = ['max-age' => 0];

    $this->connection = Database::getConnection();
    $connection = Database::getConnection();
    $req = "SELECT id, name FROM details_types_sejours_field_data;";
    $reponse = $connection->query($req);
    $results = $reponse->fetchAll();
    $this->liste += [
          '0' => t('Choose'),
    ];
    foreach ($results as $result){
      $this->liste += [
          $result->id => $result->name,
      ];
    }
    $header = array();
    $header['journee'] = $this->t('Stays days');
    $header['matin'] = $this->t('Morning');
    $header['soir'] = $this->t('Evening');
    $header['observations'] = $this->t('Comments');
    $header['operation'] = $this->t('Action');

    $promoted_items = array();
    $number_promoted = $form_state->getValue('number_promoted', count($promoted_items));
    $removed = $form_state->getValue('removed_promoted', []);

    $form['number_promoted'] = [
      '#type' => 'value',
      '#value' => $number_promoted,
    ];
    $form['removed'] = [
      '#type' => 'value',
      '#value' => $removed,
    ];
    $form['promoted'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#title' => t("Days number"),
      '#tree' => TRUE,
    );
    for ($i = 1; $i <= $number_promoted; $i++) {
      $form['#cache'] = ['max-age' => 0];
      $item = array_shift($promoted_items);
      if (in_array($i, $removed)) {continue;}
      $form['promoted-container'] = [
        '#type' => 'container',
        '#title' => t("Day number #@i", ['@i' => $i]),
      ];

      // Journée

      $form['promoted'][$i] = [
        'journee' => array(
          '#type' => 'date',
          '#title' => $this->t('Stays'),
          //'#default_value' => $item['title'],
        ),

        // Matin

        'matin' => array(
          array(
            '#type' => 'datetime',
            '#title' => $this->t("Start hour"),
            '#date_date_element' => 'none', // hide date element
            '#date_time_element' => 'time', // you can use text element here as well
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'datetime',
            '#title' => $this->t("End hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element
            '#date_time_element' => 'time', // you can use text element here as well
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'select',
            '#default_value' => 'Choose',
            '#options' => $this->liste,
            '#title' => $this->t('Requested service:'),
          )
        ),

        // Soir

        'soir'=>array(
          array(
            '#type' => 'datetime',
            '#title' => $this->t("Start hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element
            '#date_time_element' => 'time', // you can use text element here as well
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'datetime',
            '#title' => $this->t("End hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element
            '#date_time_element' => 'time', // you can use text element here as well
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'select',
            '#default_value' => 'Choose',
            '#options' => $this->liste,
            '#title' => $this->t('Requested service:'),
          )
        ),

        // Observations

        'observations' => array(
          '#type' => 'textarea',
          '#title' => $this->t('Comments:'),
          '#cols' => '20',
          '#rows' => '5',
        ),
      ];

      // Boutons

      $form['promoted'][$i]['remove_' . $i] = [
        '#type' => 'submit',
        '#value' => t("Delete stays #@i", ['@i' => $i]),
        '#submit' => ['::removeItem'],
        '#attributes' => [
          'class' => ['button--danger'],
          'data-toRemove' => $i,
        ],
      ];
    }

    $form['#cache'] = ['max-age' => 0];
    $form['promoted-container'] = [
      '#type' => 'submit',
      '#value' => t('Add new stays'),
      '#submit' => ['::addPromotedItem'],
    ];

    return $form;
  }

  public function addPromotedItem(array &$form, FormStateInterface $form_state) {
    $form['#cache'] = ['max-age' => 0];

    $form_state->setValue('number_promoted', $form_state->getValue('number_promoted') + 1);
    $form_state->setRebuild();
  }

  public function removeItem(array &$form, FormStateInterface $form_state) {
    //$form['#cache'] = ['max-age' => 0];

    /*$removed[] = $form_state->getTriggeringElement()['#attributes']['data-toRemove'];

    if(count($promoted)>1){
      // Find the key of the item we need to remove
      $removed = array_search($data-toRemove, 'promoted');

      // Remove our triggered element
      unset($[$key_to_remove]);

      // Rebuild the field deltas values
      $form_state->set('field_froid_ferme', $field_livraisons_array);

      // Rebuild the form
      $form_state->setRebuild();
    }else{
    */

    $removed = $form_state->getValue('removed_promoted');
    $removed[] = $form_state->getTriggeringElement()['#attributes']['data-toRemove'];
    $form_state->setValue('removed_promoted', $removed);
    unset($removed[count($removed)-1]);
    $form_state->setValue('number_promoted', $form_state->getValue('number_promoted') - 1);
    //$form_state->setValue('removed_promoted', $removed);
    $form_state->setRebuild();
    $form_state->setValue('removed_promoted', $removed);
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    //parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    /*foreach ($form_state->getValues() as $key => $value) {
      //drupal_set_message($key . ': ' . $value);
    }
    */
  }

}

```

# Answer
It looks like your #default\_value is undefined. I suggest you add the default value for the field too. Like this -

```
$form['time_container']['time'] = [
  '#type' => 'datetime',
  '#title' => $this->t('Time'),
  '#size' => 20,
  '#date_date_element' => 'none', // hide date element
  '#date_time_element' => 'time', // you can use text element here as well
  '#date_time_format' => 'H:i',
  '#default_value' => '00:00',
 ];

```
> 5 votes

---
Tags: 8, forms
---


title: use PHP library in Custom Controller

text:
# Question
Title: use PHP library in Custom Controller
I have a custom module and in its controller i am using 'namespace + classname' format to included QRCode library (which is in root/vendor/).

I have used composer to install library

Now I am trying to use this library in custom controller

```
namespace Drupal\product_display\Controller;
use Endroid\QrCode\QrCode;

```

But I am getting 'class not found error'

```
Error: Class 'Endroid\QrCode\QrCode' not found

```

Class doesn't autoload.

# Answer
Did you tried dump-autoload command too -

```
composer dump-autoload

```

Ref: https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload-
> 2 votes

---
Tags: composer
---


# Question
Title: Reaction rule throws exception when previewing node
I have very simple reaction rule condition 'Node is Type' in Drupal 8 (8.5.3) Rules module (8.x-3.0-alpha3):

```
Data selector: @node.node_route_context:node

```

(*Note*: the mentioned issue occurs also for simple value `node` in the data selector.)

```
Content types: page

```

It works well when a node is **viewed**, but the rule causes crash with the error message `The website encountered an unexpected error. Please try again later.` when a node is **previewed** (button 'Preview' is clicked on the node form).

*Note*: To replicate the issue you should clear the cache on node form before hitting the 'Preview' button to ensure the node isn't served from the Drupal cache in which case Rules aren't fired.

The logged Error Message is:

```
Drupal\rules\Exception\EvaluationException: The context for node is NULL,
but the context node in rules_node_is_of_type requires a value.

```

Any hints on better Rules condition to catch the node type, or a patch for Rules?

Thank you!

# Answer
> 2 votes
I have found a workaround.

It seems that this is indeed a bug in the Rules module. The working solution is from here (although it was originally written for different situation, it fits this case as well): https://www.drupal.org/project/rules/issues/2929588#comment-12385257, and basically suggests to use a different condition:

```
Rule condition: 'Condition: Data comparison'
Data to compare (switched to data selection): node.type.target_id (Content type ID)
Operator (switched to Direct Input mode): ==
Value (switched to Direct Input mode): your_node_type

```

I hope this helps somebody.

---
Tags: 8, nodes, rules
---


# Question
Title: Array $field_instance is occassionally empty
I am trying to determine why, on certain nodes, my address fields are not geocoded to my geofield. I think I have it tracked down to this part of geocoder.widget.inc (line 347).

```
function geocoder_widget_get_entity_field_value($entity_type, $field_instance, $entity) {
    $field_name = is_array($field_instance['widget']['settings']['geocoder_field']) ? reset($field_instance['widget']['settings']['geocoder_field']) : $field_instance['widget']['settings']['geocoder_field'];

```

If I add `dpm($field_instance)`, on one node update, it will show me that array. On a different node update, there is no devel message (i.e. no array). Both nodes have addresses.

The problem is, I cannot figure out why one would be blank while the other would not be.

# Answer
Apparently this was an issue with the manual lat/lon override. I didn't have it checked to allow it, but when I did check it and edited the problem nodes, the override box was already checked. Unchecking it then allowed my address field to be geocoded.
> 0 votes

---
Tags: entities
---


# Question
Title: Send order notifications when user is anonymous
I find that when anonymous users are ordering something from my site I cannot send order notification messages using the "out of the box" Commerce rules. The error message that I get says that Rules is unable to create the message entity, and the apparent reason that it cannot is that the parameter that the Commerce rule provides \[commerce-order:owner\] does not work \[???\] for anonymous users.

I can and have fixed this by changing the parameter to \[site:current-user\], but am wondering if there is some other way to get this to work. \[Like, for example, setting an order property?\]

# Answer
Since the user account for anonymous orders is created upon checkout completion, it may be that you just need to assign your custom rule a higher weight. It would need to execute after the other rule that creates and assigns the order owner user account to the newly completed order.
> 0 votes

---
Tags: commerce
---


# Question
Title: how do i modify the paypal order details?
My client logs into Paypal to review the orders that have been processed and would like to see the actual product name rather than the order number. How do I accomplish this?

# Answer
> 0 votes
There is a patch in the queue that supports sending itemized information to PayPal, but it was never completed / integrated as far as I know. It gets tricky when you itemize, because any rounding errors in taxes, discounts, etc. triggers a failure to accept payment at PayPal.

In order to do this yourself even without the code being part of the module, you'd need to alter the form used to redirect to PayPal or the API request used to process the payment. Either of these would be possible in a custom module using hook\_form\_alter() or the relevant alter hook from the PayPal module for the payment method you're actually using.

---
Tags: commerce, payment-gateways
---


# Question
Title: How do I disable digest subscription notices for all users?
I expect to do this in the database rather than through the UI. I thought I'd done it already, but it seems they are still going out. Any help would be much appreciated.

# Answer
I'm not sure you'll really be able to force everyone out of getting Digests, but if you look in

/admin/config/system/subscriptions/userdefaults

In the **Settings** Fieldset, above **Type of links to send** field, there's a checkbox for Digest mode. If that's checked, it may be causing you problems. I'm looking at this in D7.

My main thought is that user preferences for a digest may override the defaults you've set up, so I'm not sure you'll really be able to completely shut down this feature. I'm also not sure why you'd want to. Getting pinged about a new comment every time it happens can overwhelm someone's inbox if even a moderate conversation is going on. My team likes giving a digest every 3 hours as the default because it will give users about 2 updates a day, but won't overwhelm them unless they change the settings themselves.
> 0 votes

---
Tags: notifications
---


title: Are persistent connections used?

text:
# Question
Title: Are persistent connections used?
How can I find out whether my Drupal 7 site using persistent connection or not? And it's possible to turn it on if it's not?

# Answer
> 1 votes
If the persistent connections is not enabled you can enable it by adding this to settings.php:

```
ini_set('mysql.allow_persistent', TRUE);

```

And you just do like this to turn it off:

```
ini_set('mysql.allow_persistent', TRUE);

```

To check is persistent connections is enabled go to `/admin/reports/status/php`, and search for `allow_persistent`.

---
Tags: 7, database
---


# Question
Title: How to anonymize IP logging by google analytics?
I'm trying to achieve the implementation of:

```
gtag('config', 'UA-xxxxxxx-x');

```

to

```
gtag('config', 'UA-xxxxxxx-x', { 'anonymize_ip': true });

```

How to do this in D7?

I tried to add it to advance options in the google. Looked in some technical documents in ga but do not see how to fill in this field in drupal. Any suggestion?

# Answer
> 1 votes
You can do that using the google analytics module. Enable the module and go to `/admin/config/system/googleanalytics`, there put your ga id in the textfield then there is a Privacy vertical tab. In that tab there is this checkbox which says `Anonymize visitors IP address`

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


# Question
Title: JS/CSS aggregation not creating css folder
I am creating a Drupal 8 website with a custom theme. When css and js aggregation checkboxes are checked, js directory is created in sites/default/files/, however css folder does not get created.

Also all js and css is not working.

When I ran this command in terminal **ls -l sites/default/** I get the following line for files folder

**drwxrwxrwx 7 admin staff 224 May 10 10:30 files**

Would there be any reason the site does not create css folder in sites/default/files?

Thanks in advance.

# Answer
I believe this issue is due to incorrect permission. Can you check the permission on the folders. It will also be helpful if you print the related error/warning/notice logs with the question.

Thanks
> 2 votes

---
Tags: 8, css-js-aggregation
---


# Question
Title: How can I disable parent menu link to be non-clickable?
Nolink,None,Separator and other things does not work when added to URL path. Have also Installed menu module but that did not help. Its Drupal 7.

Thank you for your co-operation!

# Answer
Install the Special Menu Items module. You can add menu items that are placeholders or separators but aren't clickable. It is found on the drupal module site: https://www.drupal.org/project/special\_menu\_items
> 1 votes

# Answer
you can also use simplify menu module and then in your menuname.html.twig you can only print the menu name and skip link for parent
> 0 votes

---
Tags: navigation
---


# Question
Title: How to map a taxonomy term into Feeds Importer?
I have several Blank sources in a Feed and I'm mapping a value to these blank sources in my custom code.

I have a working example to set a value of a field of type 'TEXT FIELD':

```
function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['value'] = $mapping['profile'];
        }
    }
}

```

My question is, how to do the same if the field is a term reference?

Thanks!

# Answer
It was simpler than what I thought.

The code is exactly the same, but instead of 'value', we have to use 'tid':

```
function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['tid'] = $mapping['profile'];
        }
    }
}

```
> 0 votes

---
Tags: feeds
---


# Question
Title: Language switcher using get language variable instead of prefix in Drupal 8
In Drupal 8 setting url with path prefix for language detection, works fine. But when I include the language switcher block included with Drupal, the links instead of using the language prefix, show links using the variable language in the url.

How can I make the language switcher make use of the language prefix instead?

# Answer
The plugins you enable in the language detection configuration also contain the methods to build outbound paths and the language switcher links. The plugin for *Url* adds prefixes, not query strings. Others do, for example *Session* for anonymous users, so you probably have enabled a second detection method.
> 3 votes

---
Tags: 8, blocks, i18n-l10n
---


# Question
Title: How can I load a default image from a node field in page.html.twig
I want to print the default image of a node field into the page.html.twig template file in Drupal 8. On doing my research the easiest approach I could find was

```
{% if node.field_image.entity %}
   <img src="{{ file_url(node.field_image.entity.uri.value) }}"
        alt="{{ node.field_image.alt  }}"
        {% if node.field_image.title %}
        title="{{ node.field_image.title }}"
        {% endif %}
   />
{% endif %}

```

This works if I load an image in the field but not otherwise with the default image of the image field. I want to use the above code to print the default image that I pick for this image field. Currently the above method gives `<img src="http://example.com/" alt="">` for the default image

How can I access the uri value of the default image in the src of the image tag above. Is there any other way to print the default image of a node in the page.htm.twig preferably from within the template layer as I don't have any experience with preprocess functions etc.? My objective is to have a static image which is the same throughout the content type.

# Answer
> 10 votes
Here's one approach, using a helper method. It assumes you have access to the loaded node entity ($entity), and would like to get either the set, or default image for a given image field. I've also left comments and links that explain why Drupal::service('entity.repository') is being used, and how I discovered the way in which the Image module loads the default image settings.

```
    /**
 * Get the set or default image uri for a file image field (if either
 * exist).
 * @param $entity
 * @param $fieldName
 * @return null|string
 */
function get_image_uri($entity, $fieldName) {
  $image_uri = NULL;
  if( $entity->hasField($fieldName) ) {
    try {
      $field = $entity->{$fieldName}; //Try loading from field values first.
      if ($field && $field->target_id) {
        $file = File::load($field->target_id);
        if ($file) {
          $image_uri = $file->getFileUri();
        }
      }
    } catch (\Exception $e) {
      \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
    }

    // If a set value above wasn't found, try the default image.
    if (is_null($image_uri)) {
      try {
        $field = $entity->get($fieldName); // Loading from field definition
        if ($field) {
          // From the image module /core/modules/image/ImageFormatterBase.php
          // $default_image = $test->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
          $default_image = $field->getSetting('default_image');
          if ($default_image && $default_image['uuid']) {
            // $defaultImageFile = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']));
            // See https://www.drupal.org/node/2549139  entityManager is deprecated.
            // Use entity.repository instead.
            $entityrepository = Drupal::service('entity.repository');
            $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
            if($defaultImageFile) {
              $image_uri = $defaultImageFile->getFileUri();
            }
          }
        }
      } catch (\Exception $e) {
        \Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
      }
    }
  }

  return $image_uri;
}

```

# Answer
> 2 votes
Thanks @Blue Waters for the code snippet. I have used it in a preprocess function to integrate with the theme. Sharing my code here, so it helps someone else save some time.

I have a field names `field_images`, which I'm rendering in the template page.html.twig. The default image properties uui, height & width are readily available in the field settings, so I thought adding the fileuri there would be the simplest approach.

My function in mytheme.theme

```
function theme_preprocess_page(&$variables) {
  if (array_key_exists('node', $variables)) {
    $node = $variables['node'];

    if (isset($node) && !is_string($node)) {
      if ($node->hasField('field_images')) {
        $images = $node->get('field_images');

        if (sizeof($images) === 0) {
          $image = $images->getFieldDefinition();
          $defaultImage = $image->getSetting('default_image');

          $entityrepository = Drupal::service('entity.repository');
          $defaultImageFile = $entityrepository->loadEntityByUuid('file', $defaultImage['uuid']);

          if($defaultImageFile) {
            $defaultImageUri = $defaultImageFile->getFileUri();
            $defaultImage['fileuri'] = $defaultImageUri;
            $image->setSetting('default_image', $defaultImage);
          }
        }
      }
    }
  }
}

```

Then in page.html.twig I have the following:

```
{% if node.field_images is not empty %}
  {% for image in node.field_images %}
    <img src="{{ file_url(image.entity.fileuri) }}" width="{{ image.width }}" height="{{ image.height }}" alt="{{ image.alt }}">
  {% endfor %}
{% else %}
  {% set image = node.field_images.setting('default_image') %}
  <img src="{{ file_url(image.fileuri) }}" width="{{ image.width }}" height="{{ image.height }}" alt="{{ image.alt }}">
{% endif %}

```

# Answer
> -1 votes
Worked around it by using static images instead of default images with the code `{{ base_path ~ directory }}` to get path to image (src) without any preprocessing.

---
Tags: 8, theming, media
---


# Question
Title: How to install drush on a shared hosting without SSH and without composer?
I would like to install Drush on my shared hosting account in order to let a cronjob call a specific module to this installation.

I have NO SSH access and NO Composer access on this shared hosting account and will not get it neither. I can setup a crontab job and run a call.

I looked extensivly to install drush but cannot find it.

Please do not answer that I should use SSH or composer. These answers will not be helpfull :-)

# Answer
> 1 votes
Rather than using drush, consider writing a custom script you can call instead.

In Drupal 7 you can bootstrap Drupal from the command line like this:

```
<?php
chdir('/var/www/YOUR SITE ROOT');

// no time limit!
set_time_limit(0);

// set some server variables so Drupal doesn't freak out
$_SERVER['SCRIPT_NAME'] = '/importer.php';
$_SERVER['SCRIPT_FILENAME'] = '/importer.php';
$_SERVER['HTTP_HOST'] = 'somewhere.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';

// change to the Drupal directory
define('DRUPAL_ROOT', getcwd());

 // Drupal bootstrap throws some errors when run via command line
 //  so we tone down error reporting temporarily
error_reporting(E_ERROR | E_PARSE);

// run the initial Drupal bootstrap process
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// act as the first user
global $user;
$user = user_load(1);
// add your custom code here

```

You will need to tweak this to your specific needs. Place it outside your site root for security reasons.

# Answer
> 1 votes
Upload `drush.phar` to your web host and then you can execute the phar file in php:

```
php ~/path_to_the_drush_binary/drush.phar

```

You'll find the drush.phar file on https://github.com/drush-ops/drush/releases, the latest drush 8 version is https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar.

---
Tags: drush
---


title: Prevent Cross-site scripting

text:
# Question
Title: Prevent Cross-site scripting
One of the security principles is sanitizing strings and variables passed from client to server. In plain PHP there are some functions to prevent XSS (Cross-site Scripting) vulnerabilities:

What is Drupal 8 strategy to prevent XSS attacks? How can I clean up client data post to protect my site from XSS attacks?

I remember Drupal 7 has `filter_xss()` to prevent XSS vulnerabilities, but what is Drupal 8 strategy against XSS vulnerabilities?

# Answer
> 13 votes
> ### Sanitizing on output to avoid Cross Site Scripting (XSS) attacks
>
> **Use Twig templates** The Twig theme engine now auto escapes everything by default. That means that every string printed from a Twig template (e.g. anything between `{{ }}`) **gets automatically sanitized *if no filters are used.***
>
> See Filters - Modifying Variables In Twig Templates for the Twig filters available in Drupal.
>
> In order to take advantage of Twig’s automatic escaping (and avoid safe markup being escaped) ideally all HTML should be outputted from Twig templates.
>
> API functions Use t() and `\Drupal::translation()->formatPlural()` with `@` or `%` placeholders to construct safe, translatable strings. See Code text translation API in Drupal 8 for more details.
>
> **Strings sanitized by t(), Html::escape(), Xss::filter() or Xss::filterAdmin() are automatically marked safe, as are markup strings created from render arrays via Renderer.**
>
> While it can also sanitize text, it's almost never correct to use check\_markup in a theme or module except in the context of something like a text area with an associated text format.

Source: **Drupal 8: Writing secure code** by: Rade, Shyamala, Robert Castelo, and Pere Orga.

# Answer
> 1 votes
Drupal generally takes the approach of filtering on output, not on input.

A module which accepts a person's input as not part of the field system must filter it when it outputs it (even from privileged, administrator users). Output is usually a render array. So a simple way to do this is to limit allowed tags on render. To take an example from taxonomy module's output of a term label:

```
use Drupal\Component\Utility\Xss;

```

...

```
  public function termTitle(TermInterface $taxonomy_term) {
    return [
      '#markup' => $taxonomy_term->getName(),
      '#allowed_tags' => Xss::getHtmlTagList(),
    ];
  }

```

# Answer
> 1 votes
Twig templates did not sanitize output in my application. A script string or XSS attack entered into a comment field and saved was executed when the page loaded. Instead, I solved the problem by sanitizing each string input field in `hook_ENTITY_TYPE_load`.

```
 if(isset($entity->$fieldName)) {
        $value = $entity->get($fieldName)->value;
        $value =  htmlspecialchars($value);
        $entity->set($fieldName, $value);
 }

```

---
Tags: 8, security
---


# Question
Title: Brightcove Connects breaks site after core upgrade to 8.5.x in Acquia Cloud
After upgrading core to 8.5.2, and eploying to Acqui Cloud, Brightcove causes a fatal error. Note, the code works as expected in my local DevDesktop environment, and I am unable to recreate the error locally.

Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveCmsEntity' not found in /mnt/www/html/xxx/docroot/modules/contrib/brightcove/src/Entity/BrightcovePlayer.php on line 30

The error is thrown via http and drush commands

# Answer
I discovered the issue. Case-sensitivity of the class names. Class "brightcove/src/Entity/BrightcovePlayer.php" extends "BrightcoveCmsEntity", while class "brightcove/src/Entity/BrightcoveCMSEntity.php" is named as "BrightcoveCMSEntity".

I replaced all instances of "BrightcoveCmsEntity" with "BrightcoveCMSEntity", and the issue was resolved, it exposed the same issue with "BrightcoveVideoPlaylistCmsEntity".

Fatal error: Class 'Drupal\brightcove\Entity\BrightcoveVideoPlaylistCmsEntity' not found in /mnt/www/html/nhradev/docroot/modules/contrib/brightcove/src/Entity/BrightcoveVideo.php on line 75

Replacing all instances of "BrightcoveVideoPlaylistCmsEntity" with "BrightcoveVideoPlaylistCMSEntity" resolved all issues.

The plugin now works as expected in Acquia Cloud.

NOTE, the code worked locally because I am developing on Windows.

Files touched: brightcove/src/Entity/BrightcoveCMSEntity.php brightcove/src/Entity/BrightcoveCustomField.php brightcove/src/Entity/BrightcovePlayer.php brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php

brightcove/src/Entity/BrightcovePlaylist.php brightcove/src/Entity/BrightcoveVideo.php brightcove/src/Entity/BrightcoveVideoPlaylistCMSEntity.php brightcove/src/Form/BrightcoveVideoPlaylistForm.php

Reference: https://www.drupal.org/project/brightcove/issues/2969674
> 0 votes

---
Tags: upgrading, acquia-cloud
---


# Question
Title: Create a Rule that assigns a specific role to a user after they have completed a form
Ok, I have a customer that is wanting to have an applicant complete a specific webform and then have their user account be assigned to a specific role automatically.

My thought was to go the following route using rules:

1. Applicant creates their user account
2. They are then automatically taken to the specific webform
3. Once the webform is completed, then they are automatically assigned a specific role *(this is the part where I'm lost as to the best option or if it's even possible)*

Is this something that would even be possible using rules? Or are there other options that may work? Any assistance would be greatly appreciated!

I hope I've explained the situation enough :) Let me know if you need any further info.

Thank You!!

Nicole

# Answer
Sure you can! This is a way of doing it with the Rules module.

This also requires the Webform Rules Module.

Download that, enable it, and be sure that the Rules UI module within it is enabled as well.

## Step 1 - Create Rule

Start by creating a new Rule under Admin\>Config\>Workflow\>Rules.

Name it whatever you'd like, but have it react on "After a webform has been submitted"

---

## Step 2 - Find Webform's NID

In another tab, view your Webforms in Content\>Webforms. Hover your mouse over the Edit link next to the Webform you were talking about to find its Node ID (NID). You will need this in a second.

---

## Step 3 - Only Apply Rule to that Particular Webform

Return to the Rule you created a bit ago and click the "Add condition" link under "Conditions".

Select "Data Comparison" as your condition.

Here, you are going to select "node:nid". This is because you only want this rule to fire up when the Webform you mentioned earlier is submitted.

Below that, enter in the Node ID for the Webform

---

## Step 4 - Add Action for Adding Role

Return to your Rule and click on the "Add Action" link in the "Actions" settings.

For your Action, you are going to select "Add user role"

Under the Data selector, you are going to choose "user"

Below that, select the Role(s) that you want the submitter to gain.

Hope this helps!
> 1 votes

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


# Question
Title: Create a related content block which sorts the nodes of related content by how many tags they share?
The options in a views Advanced tab seem to only allow:

```
Multiple-value handling
Filter to items that share all terms
Filter to items that share any term

```

and I'd like to show items that share any term but sort by showing the items sharing the most terms at the top. Sort of like a "relevant" sort filter?

# Answer
> 0 votes
You can do this with Aggregation, but you have to be careful about some details.

The first thing to do is to create a block listing your desired content, with contextual filters that will restrict the results to only nodes that are tagged with the same terms.

A very popular method of doing that is through `Has taxonomy term ID` contextual filter set to `Provide default value` of `Taxonomy term ID from URL` (with other options appropriately set).

I haven't been able to achieve the Sorting through Aggregation that way. Perhaps someone will come along and shed some light on this, whether and how it can be done.

I have been able to do it with a different strategy, the one that is usually necessary when dealing with Entity references in general. It relies on Relationships to introduce sibling nodes, and ID as contextual filters. Here are the steps to create it:

## List nodes tagged with the same Taxonomy terms

1. Create a View of type Content, Filter it as usual to Content types, the taxonomy field not empty etc. Show fields Title and the field containing your terms, show Multiple values in the same row although that won't matter later, format as Table simply for readability, you can change it later.
2. Add a Relationship (search for your field name) **Taxonomy term referenced from field\_yourtags**.
3. Add another Relationship **Content using field\_yourtags**,
it will be set by default to use the Relationship from the previous step
4. Add a Contextual filter **ID** (from `Content` Category) and set it to use the second Relationship (the one from the previous step, it will actually be the only choice next to "Do not use a Relationship") with other options:
**When the filter value is NOT available:**
**Provide default value**
**Content ID from URL**
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
\[your appropriate types\]
5. Add another Contextual filter **ID** but this time **Do not use a Relationship**:
**When the filter value is NOT available:**
**Provide default value**
**Content ID from URL**
**More: Exclude**

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter `14/14`.

Don't worry about the multiplicates, we'll turn them to the best use with Aggregation ;) They are listed the number of times that the tags match between them and the current node!

---

## Aggregate results according to common terms count
6. Turn Aggregation on (`Use aggregation` option in the third column set to **Aggregate**), don't worry about the red message in Preview. All fields and filters now have Aggregation settings. You only need to change the one on your taxonomy field:
7. Click on **Aggregation settings** for the "Content: Yourtags" field and change it to **Count DISTINCT**. Notice how your tags are now replaced by numbers indicating how many common terms those nodes have with the current node!
8. Now we just have to sort the View using this data: **Add a Sort criteria**:
**Content: Yourtags**
**Do not use a Relationship**
**Sort descending**
**Aggregation settings**: **Count DISTINCT**

Now you can Place your block in a Region and check the count on nodes.

Additional perk of this approach is that it won't list anything if the current node isn't tagged with any terms, while with the "Has taxonomy term ID" method you get all results.

---
Tags: views, 8
---


# Question
Title: Uncaught TypeError: jQuery(...).appear is not a function
I've got the error 'Uncaught TypeError: jQuery(...).appear is not a function drupal' when trying to use the script below:

content of script.js:

```
Drupal.behaviors.basic = {
   attach: function (context, settings) {
     (function ($) {
          jQuery('.hero').each(function() {
            jQuery(this).appear(function() {
              var $endNum = parseInt(jQuery(this).find('.number').text());
              jQuery(this).find('.number').countTo({
                from: 0,
                to: $endNum,
                speed: 4000,
                refreshInterval: 60,
                formatter: function (value, options) {
                  value = value.toFixed(options.decimals);
                  value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                  return value;
                }
              });
            },{accX: 0, accY: 0});
          });
})(jQuery);
}
};

```

the html:

```
<div class="hero">
  <div class="number">1,234</div>
</div

```

# Answer
> 0 votes
Here is how I would debug this issue.

1. Check if your jQuery object is attached to the global window object. You can do this by typing window.jQuery on your browser console. If this returns 'Undefined' then the issue is with the reference to the jquery library.
2. Make sure that the jQuery library is loading properly. Inspect your Network tab in your browser to find this out.
3. Make sure your js has - core/jquery as a dependency i.e.

```
  global-js:
   js:
    js/myjs.js: {}
   dependencies:
     - core/jquery

```

Also, you do not need to use jQuery after you pass 'jQuery' object from the global scope into your IIFE. You should just use '$'. Look at this article for more info.

https://en.wikipedia.org/wiki/Immediately-invoked\_function\_expression

---
Tags: 8, javascript
---


# Question
Title: Views field that links to fragment URL of comment on /node/ instead of /comment/
With Views, I want to output a list that links to each comment of the current node. But instead of linking to

```
/comment/42#comment-42

```

I want to link to

```
/node/23#comment-42

```

I tried these fields, but they all link to the URL in the `/comment/` space:

* Comment: Title (Formatter: Plain text)

```
/comment/42

```
* Comment: Title (Formatter: Comment Permalink)

```
/comment/42#comment-42

```
* Comment: Link to Comment

```
/comment/42

```

**Is there a way to output anchors in the `/node/` space?** The solution doesn’t need to support comment pagination (a node will never reach the limit).

# Answer
An ugly workaround (which will **not** work for paginated comments):

1. Add the field "**Content: Link to Content**"

1. Use the relationship "Content" (should be default when creating a comments view)
    2. Enable "Exclude from display"
    3. Enable "Output the URL as text"
2. Add the field "**Comment: Comment ID**"

1. Set "Formatter" to "Unformatted"
    2. Enable "Exclude from display"
3. Add the field "**Comment: Title**"

1. Set "Formatter" to "Plain text"
    2. Disable "Link to the Comment"
    3. Enable "Output this field as a custom link" (under "Rewrite results")
    4. Link path: `{{ view_node }}#comment-{{ cid }}`
    (field names might differ, use what’s listed under "Replacement patterns")
> 1 votes

---
Tags: views, 8, uri, comments
---


title: Add a span/class to a field

text:
# Question
Title: Add a span/class to a field
I've found a way to add a style to a region. The link is /admin/structure/ds/styles.

I've found a way to specify a style for my Title. We can choose the "class" attribute of title property.

Howe can I add a specific class/span to my "publish date" field?

How can I do that with Display Suite?

# Answer
> 0 votes
1. Enable the module display suite extras
2. Define a display suite layout. Once the layout is specified you get the 'custom classes tab'.
3. Enable Field Templates in the display suite configuration screen admin \> structure \> Display Suite. Then select "Field Templates". Check "Enable Field Templates. URL is admin/structure/ds/list/extras
4. Define some classes. Using the "CSS classes" tab in the display suite settings define some "CSS classes for fields". URL is admin/structure/ds/classes
5. Ensure that the view mode that you are using is managed by display suite. Under "Manage display" accessed either via the node editing screen or admin \> structure \> content types check the box next to the view mode being used. In the format column the 'Field template' text should now be shown.
6. Using the cog icon on the right, edit the field template setting. Select the CSS style chosen in #4

With images the process is 1. enable display suite extras 2. Define a display suite layout

3. Enable field templates
4. Define classes
5. Manage the view mode

6. Select the classes

---
Tags: theming, display-suite
---