# Question
Title: How to install multiple modules with composer at once?
Let's say we need to install these 2 modules :

```
composer require 'drupal/redirect:^1.4'
composer require 'drupal/pathauto:^1.4'

```

I couldn't find the correct syntax so I've tried this but it doesn't work :

```
composer require 'drupal/redirect:^1.4'; 'drupal/pathauto:^1.4'
composer require 'drupal/redirect:^1.4', 'drupal/pathauto:^1.4'
composer require 'drupal/redirect:^1.4'/'drupal/pathauto:^1.4'

```

Actually I install 1st module "redirect " and after installation is completed, I install the 2nd one "pathauto".

I would like to create a script that will install all the necessary modules I need.

# Answer
> 16 votes
You can write the names of multiple packages separated by spaces. For example:

```
composer require drupal/adminimal_theme:^1.5 drupal/adminimal_admin_toolbar:^1.9

```

---
Tags: 8, composer
---


# Question
Title: Using Drupal console, can I gitignore console folder?
I'm working on a Drupal 8 project, and installed Drupal console globally on my system.

The command `drupal init` created a `console` folder at the root of Drupal.

It seems to be used as a cache directory. Well it's a guess from what I see inside it.

Can I safely add this directory to my `.gitignore` file? Or should I commit it?

# Answer
Yes, you can add the console directory to your `.gitignore` like so:

```
/console

```

However, similar to drush, you may want to carry around project-specific configurations in your repository. This allows changing the behavior of Drupal Console on a per-repository basis.

If you do want to have per-repository Drupal Console configurations then do not gitignore the console directory and instead commit it to the project.

See https://hechoendrupal.gitbooks.io/drupal-console/en/commands/init.html for details on how to initialize configurations.
> 0 votes

---
Tags: version-control
---


# Question
Title: Setup a view to show most recent post or a post promoted to front page
I setup a view that displays published articles from a specific content type. I want to guarantee an article always displays, so I'd like to order the results to show the most recent post. That is easy enough to do using Filter Criteria and Sort Criteria in the View Block.

What I also want to do is if my authors decide to promote an article to the homepage, I'd like that article to get priority over the date sort criteria so that the article marked promote to homepage is the one that displays.

In the event that two or more articles are marked promoted to front page, I'd like the most recent article marked as promote to front page to be the one that appears.

I tried to create a new block in the same view that displays the most recent post and I tried to add that block entity to the No Results Behavior, but I am not sure if I was doing that right because it always showed blank. Was I on the right track by doing it that way?

Is there a way to do this in a view block in Drupal 8?

# Answer
You are on the right track but, you don't have to create another view block. You can easily add more sort criteria on your existing view block and rearrange the sorting criteria. Also, just a suggestion it is better to use `Sticky at top of lists` than `Promoted to front page`. For more, you can refer to `Frontpage` views.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Access table form field's data from submitForm
I'm building a custom form and it display well. My form has a table type field which I can't manage to access from the submitForm method.

```
public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
        '#required' => true,
    ];

    $form['template_components_list'] = [
        '#type' => 'table',
        '#caption' => $this
        ->t('My table.'),
        '#tree' => TRUE,
        '#header' => array(
            $this
            ->t('row_name'),
            $this
            ->t('description'),
            $this
            ->t('actions'),
        ),
    ];

    $form['template_components_list'][0]['row_name'] = array(
        '#plain_text' => 'Test1',
    );

    $form['template_components_list'][1]['row_name'] = array(
        '#plain_text' => 'Test2',
    );

    $form['actions'] = [
                '#type' => 'actions',
            ];
    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
            ];

    return $form;
}

```

I'm then trying to access the values in submitForm from multiple ways (some creating errors but I want to show I tried them)

```
public function submitForm(array &$form, FormStateInterface $form_state)
{
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r('START', TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->getValue('row_name'), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->get('row_name'), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->get('row_name')->getValue(), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->getValue('template_components_list'), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->get('template_components_list'), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($form_state->get('template_components_list')->getValue(), TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r('END', TRUE) . '</code></pre>');
}

```

}

I got only empty messages or errors in my logs

> Error: Call to a member function getValue() on null

What is the good way to access my table rows values from submitForm ?

# Answer
> 0 votes
Sorry, I must have overlooked the way you built the form. Unless you make your values in the table row part of the form, you cannot submit them. I changed the row '#type' to a text field and added a default value, in that way you can now pass that along with your form. Try this:

```
public function buildForm(array $form, FormStateInterface $form_state)
{
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Name'),
        '#required' => true,
    ];

    $form['template_components_list'] = [
        '#type' => 'table',
        '#caption' => $this
        ->t('My table.'),
        '#tree' => TRUE,
        '#header' => array(
            $this
            ->t('row_name'),
            $this
            ->t('description'),
            $this
            ->t('actions'),
        ),
    ];

    $form['template_components_list'][0]['row_name'] = array(
        '#type' => 'textfield',
         '#default_value' => 'Test1'

    );

    $form['template_components_list'][1]['row_name'] = array(
              '#type' => 'textfield',
         '#default_value' => 'Test2'

    );

    $form['actions'] = [
                '#type' => 'actions',
            ];
    // Add a submit button that handles the submission of the form.
    $form['actions']['submit'] = [
                '#type' => 'submit',
                '#value' => $this->t('Submit'),
            ];

    return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state)
{

   $SubmittedValues = $form_state->getValues();
   print_r($SubmittedValues);
   //Now you can access the form values as an associative array
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r('START', TRUE) . '</code></pre>');
    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($SubmittedValues['row_name'], TRUE) . '</code></pre>');

    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r($SubmittedValues['template_components_list'], TRUE) . '</code></pre>');

    \Drupal::logger('some_channel_name')->warning('<pre><code>' . print_r('END', TRUE) . '</code></pre>');
}

```

---
Tags: 8, forms
---


# Question
Title: Views exposed filter, filter on multiple fields with dropdown and one textbox
I'm working on a views integration where the table and its fields are exposed to views. I want to give users the ability to filter on results of this view based on 1 of 3 fields.

I want each of the three fields in a drop down, and one text field where the user can input search terms.

Then once submitted, views will filter on the specific field and terms entered.

Is this possible? I found this discussion which has no resolution: https://drupal.org/node/732458

I'm thinking I may need to just create exposed filters for each of the three fields, and then alter the form a bit to get it how I need it.

To clarify further:

I want to expose three filters, each one searches a field by the text a user entered. I can do this in Views no problem, and it produces three distinct text fields for each of the three filters. Instead, I want the user to have just one text field, and a drop down to select which one they want to search on.

# Answer
> 1 votes
You have a couple of options to do this:

1. As you suggested just provide the user with drop-down field with the list of the criteria and single text field, then implement `hook_views_query_alter` where you change the where clause based on the dropdown field value. More can be found here
2. Your second option is to use a 'Combine fields filter\` with all the fields you want to search with and let the user know how your search works using a help text.

# Answer
> 0 votes
If I understand correctly: you want to expose 3 dropdown filters, but allow only 1 of them for input.

You can hide or show filters by using views dependent filters: https://drupal.org/project/views\_dependent\_filters, but then you need a filter that sets up 3 values for showing 1 of your 3 independent filters.

But, why don't you use OR instead of AND with those filters? It would give results and you can sort it as you want.

---
Tags: views
---


# Question
Title: Using REST to create user with CAS username
I would like my CAS server to POST an account to my client site when a new user registers. My CAS server is using D7, clients are using D8.

Using the entity/user endpoint I can create a new user, assign roles and complete custom fields. It all works well apart from adding the cas\_username.

When trying to pass the CAS username I get en error:

> "InvalidArgumentException: Field cas\_username is unknown. in Drupal\Core\Entity\ContentEntityBase-\>getTranslatedField() (line 586 of /mysite/html/core/lib/Drupal/Core/Entity/ContentEntityBase.php)."

Is it possible to POST a user with cas\_username field via the create user endpoint?

Do I need to create a custom endpoint that extends the functions of the default entity/user endpoint?

# Answer
Answering with the workaround I used. It is far from ideal, but works. It relies on having access to the DB of the client site. This uses D7 rules with the php-filter module. It would be much more elegant in it's own custom module.

The site sending the POST request uses sql to update the authname table on the site receiving the POST request. The created user then has a cas-username.

Below is the code for the rule action - creates the POST request, then alters the DB.

```
// Generate random password
$bytes = random_bytes(10);
$pass = bin2hex($bytes);

// data for user fields
$data = array(
  'name' => array(
    'value' => '[account:name]'
    ),
 'mail' => array(
   'value' => '[account:mail]'
 ),
 'status' => array(
   'value' => 1
  ),
 'pass' => array(
   'value' => $pass
    )
  );

// POST code
$data_string = json_encode($data);

// POST with cURL
$url = 'https://example.com/restendpoint';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$response = curl_exec($ch);

// Get UID from response
$newuser = json_decode($response, true);
$newuseruid = $newuser['uid'][0]['value'];

// DB update
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO authmap (uid, provider, authname, data)
VALUES ($newuseruid, 'cas', '[account:name]', 'N;')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

curl_close($ch);

```
> 0 votes

---
Tags: 8, users
---


title: Why is the index.php file missing?

text:
# Question
Title: Why is the index.php file missing?
I installed Drupal via the following command.

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

```

As a result I'm getting this structure.

> ../projectfolder/vendor/drupal
>
> ../projectfolder/vendor/bin/drush
>
> ../projectfolder/web/
>
> etc. ...

Perfect structure, but what I'm missing the index.php file. Also, the common files like sites/default/settings.php are not part of my install or perfectly hidden.

How can I get those files? What I'm doing wrong? I tried to use Drush for an standard site-install, but it failed also.

# Answer
That's exactly what drupal-project does. Your index.php should be at projectfolder/web/index.php.

Personally, I like this approach because it provides one directory level above your site root. This makes a good, secure place for files (settings, private file system) that should never be served directly by your web server.

The drupal-project composer template uses this level above your site root to install composer dependencies and tools like Drush and DrupalConsole. That's nice because when you bundle these tools with the project (instead of using a globally installed Drush for instance), you can always be sure that your colleagues are using the exact same version.
> 2 votes

# Answer
After installing just run `composer drupal:scaffold` after running `composer install` would fix it temporarily.
> 1 votes

# Answer
All those missing things should be in your ../projectfolder/web/ folder. Composer installs all the vendor files out of the web root.
> 0 votes

# Answer
In my case I had composer installed via the Ubuntu (15.10) repository version. This seems to work but Drupal was incomplete (without index.php, but complete vendor directory).

The version composer from https://getcomposer.org/download/ worked for me.

Thank you all!
> 0 votes

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


title: Using OAuth2 on non-REST endpoints

text:
# Question
Title: Using OAuth2 on non-REST endpoints
I have a custom module which includes a `ControllerBase`. The controller has a `content()` function that returns a `JsonResponse()`. The code for this function returns a complete list of a certain entity type.

I've tried using REST for this, but the entity structure is decently complicated and contains several field collections. By default, REST will just include the ID of a field collection as part of its presentation of this entity, so I've written a `FieldFormatter` plugin that replaces the field collection ID with a JSON object of its contents. Unfortunately, that requires significant overhead when returning an entire list of the entity type via REST, and takes 40 seconds to load. However, OAuth2 works fine with it.

Alternatively, my existing custom connector takes approximately two to three seconds to load, as it is a single sanitized SQL statement that outputs its results as a JSON. However, I only have Basic Auth working with this, attempting OAuth2 returns a 403 error. I am using the simple\_oauth module.

I'm wondering if there is a way to:

* A) improve the response time on the REST endpoint to be as good as the custom controller

or
* B) use OAuth2 with the custom controller. I've been looking for instructions on this but every OAuth2 resource I've come across so far assumes I'm using a REST endpoint.

edit to update: The REST endpoint is caching, which seems good as it's now loading much faster after the initial fetch, but (as is expected behaviour) the cache is flushed along with all other caches which is something we need to do fairly often, meaning the next person to access the endpoint will see an unusually slow response time. This isn't ideal, and I'd like to still investigate the custom controller I made, however adding `_auth: ['oauth2']` to the YAML file is not fixing the 403 error.

2nd edit to update: This is my YAML for the custom controller, which is also not working:

```
connector.modulename:
  path: '/connector/modulename'
  defaults:
    _controller: \Drupal\connector\Controller\ModuleNameConnectorController::content
  requirements:
    _permission: 'view modulename entity'
  options:
    _auth: ['simple_oauth']

```

It does not work with `_auth: ['simple_oauth']` or `_auth: ['oauth2']` (403 error), but does work with `_auth: ['basic_auth']`. I'm using Postman to connect with a fresh (~30 sec, expiry 5 min) token. The same oauth2 token works for the REST connector. The error message I'm getting in my admin logs states:

```
League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in League\OAuth2\Server\Exception\OAuthServerException::accessDenied() (line 173 of C:\directory_to_my_site\vendor\league\oauth2-server\src\Exception\OAuthServerException.php).

```

and also issues a PHP warning stating that access was denied to `Guest (not verified)`.

# Answer
> A) improve the response time on the REST endpoint to be as good as the custom controller

For the REST endpoint, you can use `$response->addCacheableDependency()` check this block for example: https://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/ https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/

Make sure to add cache context and cache tags, carefully.

> B) use OAuth2 with the custom controller. I've been looking for instructions on this but every OAuth2 resource I've come across so far assumes I'm using a REST endpoint.

Check the example from "simple\_oauth\_extras" sub module of "simple\_oauth" https://git.drupalcode.org/project/simple\_oauth/blob/8.x-3.x/simple\_oauth\_extras/simple\_oauth\_extras.routing.yml#L22

Controller is: https://git.drupalcode.org/project/simple\_oauth/blob/8.x-3.x/simple\_oauth\_extras/src/Controller/DebugController.php#L39
> 1 votes

---
Tags: 8, authentication-authorization, page-controller
---


# Question
Title: How to modify default login page using theme?
Version: Drupal 8.7.x

Currently, I am using a subtheme of the Bootstrap theme and I want to override the default login page because the interface doesn't look good. I was hoping to override the template file in Bootstrap theme responsible for login but there was no file with familiar name in the theme folder. Maybe Bootstrap inherited the login file as well? Then I created a file named page--user--login.html.twig and put that in my subtheme folder but there was no change in the login page. Maybe the file name is supposed to be different or it is something else entirely.

# Answer
> 1 votes
Go to

> web/sites/default/services.yml

and change the debug value from false to true

```
debug: true

```

You will get file name suggestions like shown in the image, u should use the same names.

Also, was your sub-theme succesfully installed? Is the sub-theme under this path ? \`

> themes/custom/myproject\_bootstrap\_subtheme

\`

---
Tags: 8, theming, users
---


title: Looking for a Menu Module on Node Page

text:
# Question
Title: Looking for a Menu Module on Node Page
Out site has many, many nodes included in a number of menus. When creating a node, the Parent Item select box under Menu Settings is quite long.

Is there a module that provides a better, more usable interface to selecting the parent item? I've done some searching and couldn't find anything.

# Answer
> 1 votes
I can recommend you Menu Link Weight together with Client-side hierarchical select. The combination of those two modules allow you to separate each level in an own select field and makes sorting pages within a level very handy.

After installing both of them visit `/admin/config/user-interface/menu-link-weight` and select "**Client-Side hierarchical select**".

This solution works very well for a site where we use a lot of levels and menu items.

---
Tags: 8, navigation
---


# Question
Title: How to unset the title of a custom form field
I'm trying to unset the label of a custom form called email. In which the value is in the #title key.

I've tried `{{ value|without('title', 'description', 'email.#title') }}`

But it is not working

# Answer
> 0 votes
@Fazeela Abu Zohra try to unset the value in **.theme** file. write a form alter and kint $form variable .Find your label value

```
function est_form_alter( &$form, &$form_state, $form_id ) {
  if($form_id == 'your_form_id'){
    kint($form);
  }

```

and then simply unset the variable.

```
unset($form['form_id']['#value']);

```

Here,i assume you find your variable at $form\['form\_id'\]\['#value'\].Hope it will be useful to you.

# Answer
> 0 votes
If it's a custom form you're building from your code then just set the field's title as empty string:

```
$form['email']['#title'] = '';

```

If the form is a node form then implement Drupal's hook\_form\_alter like this:

```
function MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
    $form['field_email']['und']['#title'] = '';
  }
}

```

# Answer
> 0 votes
in **Drupal 8**, you can use hook\_form\_FORM\_ID\_alter hook function in your THEME.theme file.

For exemple with theme named *custom* and FORM\_ID named *contact\_message\_custom\_contact\_form* :

```
/**
 * Implements hook_form_alter().
 */
function custom_form_contact_message_custom_contact_form_alter(&$form, &$form_state, $form_id) {
  unset($form['field_contact_name']['widget'][0]['value']['#title']);
  unset($form['field_contact_message']['widget'][0]['value']['#title']);
  unset($form['field_contact_phone']['widget'][0]['value']['#title']);
  unset($form['field_contact_mail']['widget'][0]['value']['#title']);
}

```

---
Tags: theming, 8
---


# Question
Title: Fatal error: Class 'DrupalDefaultEntityController' not found in comment.module
I'm trying to update the Drupal Core of a website, specifically from 7.65 to 7.67. I've followed the instructions from here. After the process, I've try to access the website without luck, because I'm getting the following error: `Fatal error: Class 'DrupalDefaultEntityController' not found in /var/www/html/modules/comment/comment.module on line 1698`

I've tried to run the `update.php` file and clearing the cache from the db several times, without fixing the error. I've also tried to update from 7.65 to 7.66, but the problem persists.

What am I doing wrong?

**UPDATE 1**
I've tried to follow the instructions written here suggested by the user sivani. Here is the message I am getting:

```
DRUPAL_ROOT is /Users/DamianFox/tests/drupal-website/website.<br/>
Bootstrapping to DRUPAL_BOOTSTRAP_SESSION<br/>
<h1>Additional uncaught exception thrown while handling exception.</h1><h2>Original</h2><p>PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in lock_may_be_available() (line 167 of /Users/DamianFox/tests/drupal-website/website/includes/lock.inc).</p><h2>Additional</h2><p>PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in system_list() (line 165 of /Users/DamianFox/tests/drupal-website/website/includes/module.inc).</p><hr />%

```

# Answer
After a bit of research, I found out that the problem might be generated from `entity.inc` inside the `includes` folder.
Therefore, I tried to put back the previous `entity.inc` (from the 7.65 installation); subsequently, I run the `update.php` script, and after another refresh, the website is finally accessible.
I done few more tests to check if there are warnings or errors, but everything seems to work fine, so somehow I got it sorted.
> 0 votes

# Answer
Try drush rr --fire-bazooka and see if that helps
> -1 votes

---
Tags: updating
---


# Question
Title: Why would a page created by a custom module work in my DEV environment, but produce a 404 on the live server?
I have a custom module that's creating feeds of my content for me. It's been running fine up until now. Existing feeds work, and the new feed I just added works on my development site on my local mac.

The problem I'm having is that after uploading the code changes to create the new feed to the live server, I'm getting a drupal 404 error.

So, for example: feed 1: /rss/yahoo.xml works on both DEV and LIVE

but

feed 2: /rss/amazon.xml works on DEV, but on Live produces a drupal 404 error.

I've cleared the cache, both all at once, and one at a time.

I've downloaded the live database back down to DEV to see if that breaks it, but the feed continues to work on the live site.

I've checked the live server's error logs to see if it's throwing any errors related to the URL at all, but I don't see any.

I've reinstalled the module that's generating the pages, to no effect.

I've confirmed all the files I meant to upload did in fact upload, and didn't get prevented from uploading due to permissions conflicts.

I've viewed the updated files directly on the web server to confirm, they are indeed supposed to be generating the feed.

The feed is programmed nearly identically to other existing, working feeds. The only difference between feed 1 (working) and feed 2 (only working on dev) is that feed 2 pulls a few new custom fields. I've confirmed the custom fields have been created on the live server, as they are on the dev server. Doubally confirmed when I synced the live database down to the dev site.

I'm flat out of ideas as to why the new feed isn't working when the nearly identical old feed is working, and as to why it functions in one environment and not the other.

I know it's an odd question, but has anyone experienced anything like this?

Below are the relevant code excerpts:

(from lmfeed.routing.yml)

```
misc.rss.amazon:
  path: '/rss/amazon.xml'
  defaults:
    _controller: '\Drupal\lmfeed\Controller\LmfeedMiscController::miscAmazonXml'
    _format: xml
  requirements:
    _permission: 'access content'
  options:
    no_cache: TRUE

```

(From LmfeedMiscController.php)

```
  public function miscAmazonXml() {
    $data = (object) [
      'title'       => '<my domain name>',
      'description' => '<my feed description>',
      'nodes'       => [],
    ];
    foreach ($this->dbh->selectVideos(self::RPP) as $nid) {
      $node = $this->entityMgr->getStorage('node')->load($nid);

      if (!empty($node)) {
        $data->nodes[] = [
          'title'    => $this->filterTxt($node->title->value),
          'body'     => $this->filterTxt($node->get('field_paragraph')->value),
      'body2'     => $this->filterTxt($node->get('field_paragraph')->value),
      //'body'   => $node->get('field_teaser')->value,
          'created'  => date('D, d M Y H:i:s', $node->created->value) . ' GMT',
          'guid'     => '<my domain name>' . $node->id(),
          'img'      => $this->getImgUrl($node, self::IMG_FIELD),
          'keywords' => $this->filterTxt($node->get('field_keywords')->value),
          'video'    => $node->get('field_vid_url')->getString(),
          'amazonfeatured'   => $node->get('field_amznfeaturedasin')->getString(),
          'amazonrep' => $node->get('field_amazon_representativ')->getString(),
          'amazdur' => $node->get('field_runtime')->getString(),
        ];
      }
    }
    return $this->render($data, 'lmfeed_misc_amazon_xml');
  }

```

from lmfeed.module amongst the other feed declaration statements

```
    'lmfeed_misc_amazon_xml' => [
      'template'  => 'lmfeed--misc-amazon-xml',
      'variables' => [
        'data' => [],
      ],

```

From lmfeed--misc-amazon.xml.html.twig

```
<?xml version="1.0" ?>
<rss version="2.0" xmlns:media="http://www.rssboard.org/media-rss" xmlns:amzn="https://amazon.com/">
  <channel>
    <title>{{ data.title }}</title>
    <link>https://<my domain name>/rss/amazon.xml</link>
    <description>{{ data.description }}</description>
{% for node in data.nodes %}
    <item>
      <title><![CDATA[{{ node.title|raw }}]]></title>
      <pubDate>{{ node.created }}</pubDate>
      <media:content url="{{ node.video }}" type="video/mp4" medium="video" duration="{{ node.amazdur }}" lang="en"/>
      <media:thumbnail url="{{ node.img }}"/>
      <media:keywords><![CDATA[{{ node.keywords|raw }}]]></media:keywords>
      <media:description type="plain"><![CDATA[{{ node.body|raw }}]]></media:description>
      <guid>{{ node.guid }}</guid>
      {% if node.amazonfeatured %}<amzn:featuredASIN>{{ node.amazonfeatured }}</amzn:featuredASIN>
      {% elseif node.amazonrep %}<amzn:representativeASIN>{{ node.amazonrep }}</amzn:representativeASIN>{% endif %}
    </item>
{% endfor %}
  </channel>
</rss>

```

Again, I don't THINK this is a code issue, since it works properly on my dev environment... I'm just out of ideas.

# Answer
> 0 votes
So here's what happened. Before I updated my module with the new feed, I renamed the module folder from lmfeed to lmfeed\_bak and then uploaded my new version into a new folder called lmfeed, thinking the feeds would break for a microsecond, and then Drupal would keep looking at contents of the same folder name it had been. Drupal however unexpectedly monitored the folder name change and continued using the version of the module now living in the lmfeed\_bak folder. This is why the module continued to function, but didn't reflect any of my recent changes.

I figured this out from asking the server hosting company to run a STRACE on both the working feed and the nonworking feed. I've now removed the duplicate module, renamed the folder back to what it should be, applied my updated code, and it's functioning properly.

---
Tags: 8, plugins
---


# Question
Title: Display plugin entityreference is not available
I'm not sure if this is a Views issue or an Entity reference issue, so I'm cross-posting here to see if I can find an answer.

I'm trying to export a view from my testing & development site, to our production site, but I keep running into issues, and I'm not sure where I'm going wrong.

To the best of my knowledge I've got the exact same setup on both sites - modules are all the same, and all have the same versions for both `Views` and `Entityreference`.

However, when I try to import the view on our production site I get the following errors:

```
Relationship handler node.reverse_field_plan_document_attachment_node is not available.
Display plugin entityreference is not available.
Relationship handler node.reverse_field_plan_document_attachment_node is not available.
Unable to import view.

```

I'm stumped. I have no idea where else to look. I'm assuming it's a simple issue with a setting somewhere, but I can't find it. Everything works perfectly without issue on our testing site, and doing wholesale database swap is not an option.

When I go to create a new view on our production site, I don't even have the option to add an entity reference display:

Initially, I tried to use the features module to move the feature set from the testing site to the production site, but that was an enormous mess. I completely uninstalled the features module, and all the modules I created with it in effort to try to get this stuff working. After uninstalling all that stuff, I'm still left without an option to even create an Entityreference display with Views, and obviously cannot import my view either.

Can you help?

# Answer
> 0 votes
So - after getting another pair of eyes on this the issue is resolved. Somehow, the entityreference module was only partially installed and was missing the views directory (along with a couple other things) but was otherwise *fully functional* outside of the issue as described above.

Not sure how the module would be working for other purposes, not throw any errors *at all* without those directories but that was the case.

Thanks to Matt Glaman for the help tracking down the problem.

---
Tags: 7, views
---


title: Show total search result count

text:
# Question
Title: Show total search result count
I'm trying to display the number of total search results on my search results page, using the core search module. I've tried manipulating `item-list.html.twig` and `item-list--search-results.html.twig` by displaying `items|count` but when there are more than ten results, `items|count` only captures the number of results on that page.

I'm considering installing Search API and working with views, but that seems like overkill for this one little modification.

# Answer
The search queries of Drupal 8 use the global pager. The total results count is available within its global `$pager_total_items` variable.

So the easiest way of showing the amount of total items is using this variable within a hook\_preprocess\_HOOK() of your template in your `*.theme` file.

For example, if you'd like to use the total results count within the `item-list--search-results.html.twig`, `HOOK` needs to be replaced by its theme hook `item_list__search_results`:

```
/**
 * Implements hook_preprocess_HOOK() for item_list__search_results.
 */
function mytheme_preprocess_item_list__search_results(array &$variables) {
  // The $pager_total_items variable is a global
  // array keyed by the pager element increments.
  global $pager_total_items;

  // Assuming you have one paged list on your page only,
  // the element's key should be 0.
  $variables['total_items_count'] = isset($pager_total_items[0]) ? $pager_total_items[0] : 0;
}

```

Then you can access this variable like `{{ total_items_count }}` within the template.
> 4 votes

# Answer
Using {{ total\_items\_count }} varible with twig template not working for me. then I fixed by overriding title of item list itself:

* Go to /code/themes/THEMENAME
* open THEMENAME.theme file and add following Hook

As:

```
function THEMENAME_preprocess_item_list__search_results(array &$variables) {
  // The $pager_total_items variable is a global
  // array keyed by the pager element increments.
  global $pager_total_items;

  // Assuming you have one paged list on your page only,
  // the element's key should be 0.
  $total_items_count = isset($pager_total_items[0]) ? $pager_total_items[0] : 0;

  $variables['title']= array(
        '#markup' =>$total_items_count .'<span class="search-count-text">results found for the search term “Search”</span>',
    );
}

```

\**Please change THEMENAME with you theme name
> 0 votes

---
Tags: 8, search
---


title: How can I create a patch using Git?

text:
# Question
Title: How can I create a patch using Git?
I have found an issue on drupal.org that I would like to submit an solution for. How can I create a patch using git so that I can submit it as a possible fix?

# Answer
> 13 votes
Every Drupal.org project has a tab title 'Version control', click on it and it will take you to a page with Git instructions, including a section titled 'Creating a patch'.

See here for an example: http://drupal.org/project/wysiwyg\_fields/git-instructions

Code below is copied from the D.o. instructions.

```
git checkout -b [description]-[issue-number]

```

Make your changes. Note the change in syntax for issue-related commit messages. See the Commit messages page for details.

```
git add -A
git commit -m "Issue #[issue number] by [comma-separated usernames]: [Short summary of the change]."

```

Roll the patch.

```
git status
git fetch origin
git rebase origin/6.x-1.x
git format-patch origin/6.x-1.x --stdout > [description]-[issue-number]-[comment-number].patch

```

# Answer
> 0 votes
If you use PhpStorm or IntelliJ you can do the following:

* Make sure your branch is up-to-date (commit everything)
* Make the changes (fix the bug)
* Go to VCS \> Create patch
* Follow the steps and save where you prefer it.

# Answer
> 0 votes
I wouldn't overcomplicate things. In the end all you really need is a dev version of the module, init an empty Git repo in it, clean the working tree (commit everything, it's just locally), make your changes and then run the following command.

```
$ git diff > [short_description]-[issue-number]-[comment-number].patch

```

---

In a steb-by-step that maybe boils down to the following.

1. Have a local Drupal running you can mess around with.
2. Download a dev version of the module into your local Drupal's contrib modules folder.
3. Now `cd` into the module's directory and `git init`, then `git add .` and `git commit -m "Clean tree"` to have a clean state to start from.
4. Do your code changes, and use the local Drupal to check if everything's working and in the end run the `git diff` command from above.
5. Upload the patch on drupal.org and set the issue to "Needs review".

---
Tags: version-control, community-official-site
---


# Question
Title: Drupal.behaviors js code executes mutiple times (depends on active modules)
I have two almost similar websites (one was a test project) and second one is more like final version. On both of them i have quite simple custom module with js and on first web site it works fine, but on the second one - problem is that code in js executs many times (6-10 times), it depends on active modules - i uninstaled some modules and amount of times that js is execute drops down... js file is simple like alert("hi"); and it gets printed like 10 times... i gues that one module couse this issue but i dont know whitch one. maybe someone had such issues? or some advice on how to find out whats wrong.

# Answer
`once()` may work in many cases. I've also used a flag like:

```
(function ($, Drupal) {
  let flag = false;

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      if (flag === false) {
        flag = true;
        console.log('This should only display one time.');
      }
    }
  };

})(jQuery, Drupal);

```

Please note that I only wrote this in this comment box from memory and didn't actually test this code.

Also FYI, the `Drupal.behaviors` is correctly running many times, since it is supposed to update every time some kind of state changes that would require it to update (like an AJAX call). So you do have to take extra steps on your side to ensure that certain code only runs once.
> 3 votes

---
Tags: 8, javascript
---


# Question
Title: "File not found error" when installing using composer
I'm running Docker on Ubuntu 18 with a container for MariaDB, Nginx and php-fpm (7.3).
The PHP container has composer installed, and I used it to create a Drupal Commerce project. I can start the Drupal install process using a browser, but after I input the DB settings, the process fails and I get the following error.

> An AJAX HTTP error occurred.
> HTTP Result Code: 404
> Debugging information follows.
> Path: /core/install.php?profile=commerce\_base&langcode=en&id=1&op=do\_nojs&op=do
> StatusText: Not Found
> ResponseText: File not found.

Increasing the execution time, post time, memory limit, post and upload sizes in the *php.ini* file, as recommended by another user, didn't solve the problem.

Nginx error log contains the following message.

> \[error\] 6#6: \*46 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream'.

The database has tables and data in it, so I know the database credentials are correct.

What am I doing wrong?

# Answer
Yes, it turns out it was an Nginx configuration problem. In my docker-compose.yml file i have:

```
web:
  volumes:
    - '/server/path/to/html:/usr/share/nginx/html'

php:
  volumes:
    - '/server/path/to/html:/var/www/html'

```

In my site.conf file, i had:

```
fastcgi_param SCRIPT_FILENAME project/$fastcgi_script_name;

```

Not sure why this worked for the initial php files i tested but then failed during the installation. Changing this line to the full path as follows solved the problem for me:

```
fastcgi_param SCRIPT_FILENAME /var/www/html/project/$fastcgi_script_name;

```
> 0 votes

---
Tags: commerce, installation
---


# Question
Title: There are no entities matching. BaseFieldDefinition entity reference error for taxonomy
My Code looks like this:

```
$fields['color'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Color'))
  ->setDescription(t('The color of the fruit.'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['Color' => 'Color']])
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
    'weight' => -3,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

I have a vocabulary with the name : 'Color'
I have 3 terms in it : 'Red', 'Yellow', 'Green'

The error I'm getting is this :

I'm trying to figure out what went wrong.

# Answer
> 0 votes
Change the **Color** to **color** in `['target_bundles' => ['Color' => 'Color']])` if you create a vocabulary caller **Color** the machine name will be **color** Not **Color** So try with:

```
$fields['color'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Color'))
      ->setDescription(t('The color of the fruit.'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setSetting('handler', 'default:taxonomy_term')
      // Target is color not Color.
      ->setSetting('handler_settings', ['target_bundles' => ['color' => 'Color']])
      ->setDisplayOptions('view', [
        'label'  => 'above',
        'type'   => 'author',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type'     => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator'    => 'CONTAINS',
          'size'              => 60,
          'autocomplete_type' => 'tags',
          'placeholder'       => '',
        ],
        'weight'   => -3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

```

---
Tags: taxonomy-terms
---


# Question
Title: Ajax webform do submit without ajax when it is loaded via ajax
I'm trying to load a node containing an ajax webform and add it to an existing div, this works fine, but when I click to next step, the form is submitted to the webform action path.

Any idea?

Thanks!

```
          $.ajax({
            url: '/path/to/my/node/with/webform'
            success: function (data) {
              // Add html to existing container.
              $(data).appendTo('body');
            }
          });

```

# Answer
Short answer: you need to attach the Drupal behaviors after inserting your new content into the DOM:

```
$.ajax({
  url: '/path/to/my/node/with/webform'
  success: function (data) {
    // Add html to existing container.
    $(data).appendTo('body');
    // Attach the new behaviors to the DOM
    Drupal.attachBehaviors();
  }
});

```

Long answer: Although Drupal has jQuery included with core, it does not use jQuery functions like `$.on()` or `$.delegate()` or `$.live()`, which attach behaviors to elements when they are inserted into the DOM. Instead Drupal uses `behaviors`, which is a Drupal specific method of attaching behaviors to elements.

Behaviors have three parts:

1) Scripts add new behaviors to the Drupal.behaviors object. Example:

```
Drupal.behaviors.someArbitraryKey = {
  attach: function (context, settings) {
    attachHandlerToElement(context, settings);
  }
};

```

Generally people consider this to be an `onload` function, as it is called when the document has loaded and is ready to have JavaScript executed on it. However, it can also be called using `Drupal.attachBehaviors()`, which will be addressed in #3 below. When the DOM is loaded, or `Drupal.attachBehaviors()` is called, the `.attach()` function of the behavior is executed, in this case calling `attachHandlerToElement(context, settings);` whenever this is executed.

2) `$.once()` is used to ensure that handlers are not attached multiple times to an element. Because behaviors can be executed multiple times, event handlers can be attached to elements multiple times, if steps aren't taken to prevent that. The jQuery `$.once()` function, provided by core, ensures that the code it contains is only attached to the element a single time:

```
function attachHandlerToElement(context) {
  $(context).find(".some_selector").once("some-arbitrary-key").each(function () {
    // Note that $(this) is the current iteration
    // of .some_selector
    $(this).click(function () {
      // Do something.
    });
  });
}

```

By calling `$.once()` on elements, the contained code in the `$.each()` loop is only ever attached a single time. This means that the $.click() handler above is only attached a single time to elements with the class `.some_selector`.

3) When new content is inserted into the DOM, whether that be from an AJAX call, or even just new elements inserted using JavaScript, `Drupal.attachBehaviors()` is called. This in turn loops through all behaviors, and executes their `attach()` handler.

A final note on `context`. On initial page load, `context` is the full DOM. `Drupal.attachBehaviors(context)` takes an argument, `context`, which should be an element of the DOM (not a jQuery object containing it). In your case, you are appending your content to the body, so there is no need to pass an argument, as you will need to parse the full DOM. If you were appending your content to some element though, you could do something like this:

```
$(data).appendTo('#some_element');
Drupal.attachBehaviors($(#some_element").eq(0));

```

This would pass it the element of the DOM to which the new content was attached. This element becomes `context` in the `attach()` handler, and is more efficient than passing in the full DOM.
> 2 votes

---
Tags: ajax, webforms
---


# Question
Title: Why would I provide a composer.json for my modules?
I’ve come across several Drupal7 modules that include a composer.json. It seems that this somehow influences how Drupal-CI determines test dependencies. Now I’m trying to find out whether it’s worth providing a `composer.json` at all in Drupal7 modules/themes maintained by me. I couldn’t find any hard facts about what exactly can be achieved by providing a `composer.json`, that’s why I’m looking for pointers to …

* How does the presence of a `composer.json` affect processing in the Drupal-CI?
* What other functionality is enabled by providing a `composer.json` file for Drupal7 modules (or themes)?

Note: There seems to be a lot of documentation about Drupal 8 / composer, but nothing specific for Drupal 7 / composer.

---

Here is a list of some Drupal7 modules with a composer.json:

* currency: Specifies exclusively non-Drupal dependencies.
* raven: Specifies exclusively non-Drupal dependencies
* stringoverrides: Only package metadata, no dependencies.

# Answer
> 2 votes
I wrote a blog that gives some case studies about when and why you would include a composer.json with your module: https://www.morpht.com/blog/drupal-and-composer-part-4-composer-drupal-developers

Basically it comes down to four things:

1. It allows your module to be managed with composer.
2. It allows your module to have it's Drupal module dependencies managed by composer
3. It allows your module to have it's 3rd party library dependencies managed through composer
4. Composer handles autoloading of namespaced classes in libraries it manages, meaning your module can use the 3rd party libraries it depends upon, without having to include any files

If none of the above requirements match your needs, then there is no reason to have a composer.json file in your module.

---
Tags: 7, composer
---


title: Owl carousel doesn't work

text:
# Question
Title: Owl carousel doesn't work
I can't understand how to install Owl Carousel module for Drupal 7.

I installed module from here - https://www.drupal.org/project/owlcarousel And downloaded additional files from here - https://owlcarousel2.github.io/OwlCarousel2/

Put this folder in "sites/all/libraries" and managed fields for my content type. I can see few images on my page, but carousel doesn't work.

Here is the error from chrome console - "Uncaught TypeError: o.owlCarousel is not a function" "GET https://mysite/owl.carousel.min.js?p44xlt net::ERR\_ABORTED"

# Answer
> 1 votes
Bit old, but for module version 1, you have to use OwlCarousel 1 https://github.com/InchoonPark/meteor-owl-carousel-1/

# Answer
> -1 votes
Please check that you have installed jquery\_update module.

---
Tags: 7, javascript
---


title: Live user not found in stage and dev

text:
# Question
Title: Live user not found in stage and dev
I am new to Acquia.

I have got access to the backend of drupal live instance. I cannot login to stage or dev instance.

1. Should a new user be created for every instance separately?
2. What should I do to login to the dev and stage instance?

Currently I am using Acquia Dev Desktop to pull the files locally.

What should I do to get access to the other 2 instances? Please advise.

# Answer
> 2 votes
Acquia works on a three-environment system. When working in such a system, code moves up, from dev -\> stage -\> prod, while databases move down from prod -\> stage -\> dev.

You should always consider content on dev and stage, such as nodes, users, taxonomies etc, as temporary. This is because the way to migrate content is by migrating the entire database from prod -\> stage/dev, or sometimes from stage -\> dev.

In order to get your user on all environments, you would create the user on prod, then migrate that database to stage and dev. You will then be able to log in with your user on those environments.

---
Tags: acquia-cloud
---


# Question
Title: How can I get the parent node of a referenced node?
I have a node called project which contains field building as a referenced item, I used the the hook on building node insert and, having this building id I need to get project id which this building is assigned to. How can I get the project id (the building's parent).

I have found the hostEntity() used in drupal 7 (As Far As I Know), but it seemed this is not applicable anymore in Drupal 8.

Any help?

# Answer
I think hostEntity was specific to FieldCollection in D7 and not to entity reference. Field Collection is tied to one specific host Entity. With entity reference there is no specific host entity, you can possibly reference one entity in multiple host entities.

You can use Entity Query to get all (host) nodes that reference a specific entity within a specific field.

In a very basic form this would return all "Project" nodes that reference a specific building by field building:

```
$query = \Drupal::entityQuery('node')
  ->condition('field_building', $building_nid);
$nids = $query->execute();

```

$building\_nid is the node id of the building. This will return "project" node ids in your case.
> 4 votes

---
Tags: 8, nodes
---


# Question
Title: How can I export the raw body of a node?
I set up a CSV view with `views_data_export`. I'd like to export the raw body of nodes. So I want to keep both the raw markdown and the raw HTML in the CSV.

Is there a way to do this that I have overlooked? Should I add a formatter that does nothing? If so, how can I do that?

---

I thought I had solved it by checking "Rewrite the output of this field" and using `[body-value]`, which is the raw value.

And this gives me the raw markdown but still doesn't give me the raw HTML.

# Answer
> 3 votes
Under **FORMAT**, click on **Settings**, check mark "Keep HTML Tags"

---
Tags: 7, views, importing-exporting
---


# Question
Title: Can I get integers from a dynamic query using fetchAllKeyed?
So basically I want an array of integers from a query using `fetchAllKeyed` for the results. The field is an tinyint in the db so I would expect an indexed array of integers but I am getting an indexed array of strings.

Here is the database call:

```
$query = $this->connection
  ->select('database_name', 'db')
  ->fields('db', ['first_index', 'value'])
  ->condition('db.value', 0, '<>')
  ->condition('second_index', $array, 'IN')
  ->execute();

$indexed_array_of_ints = $query->fetchAllKeyed();

```

I've tried to find other mentions of this issue and I haven't so maybe I'm just doing it wrong, I don't know.

I know that I can convert the values after the call, but I'm looking to make this operation as fast as possible so any help here would be greatly appreciated.

# Answer
The issue here is that PDO returns strings, even for integer columns. Drupal handles this issue by providing the Typed Data API, which provides data typing used within Drupal, rather than PHP-level data typing.

In the Drupal 8 paradigm, database queries are generally made to query entity IDs, which are then used to load entities. Data is then retrieved from the entity. The Entity API on the back end will handle the setting/getting of the fields on the entity. The fields on the entity will all be of a Typed Data API data type, providing a consistent method of dealing with data types on the Drupal level.

The method of retrieving IDs, and loading entities is done for the sake of efficiency, as entities are cached, and may be loaded from backends such as Redis, therefore being much faster than retrieving the entity data from the database. And because fields are typed, it gives a consistent API for dealing with various data types, that can also be extended to provide additional data types through contributed modules.

So the question here becomes about what you are trying to do, and how you are trying to do it. If you are working with data that you've been saving to the database yourself, then you can switch to the Drupal way, and create a custom entity type then use the Entity API to set/get the field data. Or, if you are retrieving data from the DB that Drupal has saved there, it likely belongs to an entity that you should be retrieving, rather than directly retrieving the field data.
> 2 votes

---
Tags: 8, database
---


# Question
Title: How to use hook_webform_submission_presave
In webform 7.x-4.10 I created a module like this:

```
function webform_presave_webform_submission_presave($node, &$submission) {
  if ($webform->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id]['value'][0] = 'Yes';
  }
}

```

My webform with nid 28 has only one field, a texfield with a default value to "No".

When the webform is submitted, the value of the field is not change...

What am I doing wrong?

# Answer
> 0 votes
Notice the value on which you check in the if.

the correct code is:

```
function webform_presave_webform_submission_presave($node, &$submission) {
  if ($submission->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id][0] = 'Yes';
  }
}

```

# Answer
> 1 votes
The reason why *the value of the field does not change* (assuming the name of your module == webform\_presave) is due to the fact that the if statement fails because **$webform** is not defined. Use this instead:

```
function webform_presave_webform_submission_presave($node, &$submission) {
  if ($node->nid == 28) {
    $component_id = 1;
    $submission->data[$component_id]['value'][0] = 'Yes';
  }
}

```

See hook\_webform\_submission\_presave() in webform.api.php.

---
Tags: webforms
---


# Question
Title: How can I filter which entities are available in the admin form for an Entity Reference Field?
I've got a Field which is called "Primary Article" which is an Entity Reference Field. I've configured this field setting the "Reference Type" to be "article", so that only articles show up in the Form when editing this field. I would want to add two customizations to the current autocomplete field: ) 1) only return some articles based on some logic ( like I only want to return articles which are not selected as primary articles for another taxonomy )
2) change the text of the autocomplete field, so in this case, instead of "Primary Article" I would want to return "Primary article - XYZ" where XYZ is a custom field

# Answer
> 0 votes
1.) You can create the limited list of Articles with Views, then use that Views in the Entity reference Field settings as the source.

2.) This should have probably gone into a separate question. Try researching into modules related to autocomplete, like: Search Autocomplete, Autocomplete Search Suggestions.

---
Tags: 8, entities
---


# Question
Title: Drupal 8 Views filer results by logged in user association
Hello Drupal Views Experts

First time Drupal site builder newbie to stack overflow and sounds like this is the smart place to ask a query.

I have a content type "Policies". This content type has a reference field to content type " Client". "Users" also have a reference to content type "Client".

What I am trying to display in views, either through filter criteria or contextual filter, is display a table of "Policies", but only display the results of which the logged in user has reference to.

I.E Logged in user is referenced to "Client A" of content type "Client". There are a few policies of content type "Policy" which also have a reference to "Client A" of content type "Client". I only want logged in user to be able to see content from views with the same reference to "client".

Is filter criteria the way to go, or contextual filters? As I said. I am a newbie site builder and guidance would be amazing if you have the know how.

Here's hoping.

# Answer
You can find answers here with detailed steps about how to do that. Search for "sibling entity reference" or something longer.

Basically, you do do it with a couple of Relationships and a Contextual filter. You need Relationships to get the referenced Content into your Views, because when you create Products views you will only have Products fields available.

So you create a list of Products, add the ER Relationship for the Client info, add another Relationship that is using the first one for the users referencing the Client, then you can add the User ID contextual filter that is using the second Relationship and set it to provide default value from Logged in user.
> 0 votes

---
Tags: views
---


# Question
Title: Link formatter to display link title, image and summary
I know I've seen a module that does this at some point in the past but can't seem to find it right now. In Drupal 8, I have a link field. I want to fetch that link's metadata so I can display the link's title / summary / image via a formatter (think of how facebook displays links). I don't remember if this worked server-side, storing the info in the drupal db or client-side via javascript (and for the prototype I'm putting together, I doesn't matter).

I'd appreciate any help before I decide to go and write it myself.

# Answer
You can do a lot with Custom Formatters and Tokens, also check out Field Formatter if you need to wrap the link around an image field.

For most control create one yourself, there are different tutorials for that, start here: Create a custom field formatter
> 0 votes

---
Tags: meta-tags
---


# Question
Title: Commerce- How can I add a custom field to Account Information on checkout
I am using Commerce but I do not require customers' billing or shipping information. However, I do need them to provide their name.

Since I have a field for the name in the user profile, I want to require anonymous users (only) to provide their name. By default, in Commerce the *Account Information* pane requires users to input their e-mail addresses if anonymous and is hidden if they are authenticated.

This is exactly the behavior I want, so I was hoping to add my name field from the user profile to the **Account Information**, but I can't find a way to do that.

**Approach I tried and rejected**

By adding the name field under *Checkout settings-\> Order-\> Manage display*, I was able to add the field, and using the Commerce Fieldgroup Panes module I could even display it in a custom fieldgroup. However, when taking this approach, authenticated users are prompted for their names and their names aren't prepopulated.

# Answer
I think you are looking for Commerce User Profile Pane module.

> Commerce User Profile Pane is a module that allows you to capture a Drupal Users profile fields directly in the Commerce checkout pages. This is similar to the Commerce Billing Profile or Commerce Shipping Profile panes, but instead of storing extra fields in the Commerce Profile entity, this will allow you to store it directly in the Drupal core User entity. This is useful when you want a quick registration process without the user having to fill a long user registration form, but you still want to retain the option to complete the User profile info in the checkout phase.
> 8 votes

# Answer
I needed to receive an optional phone number during checkout, but I didn't think the phone number field really belonged in the **Billing Information** pane. As you can see in the image below, I wanted the phone number field to show up below the email address in the **Account Information** pane, which I renamed "Contact Information".

Commerce User Profile Pane, Commerce Fieldgroup Panes, and Address Field Phone were all too feature-rich for my needs. I just wanted to simply add one field to the Account Information pane, validate and save it to the order, thereby persisting it through the checkout.

In my case, the simplest solution was to save the phone number in the `$order->data` array by adding a form field to the checkout form using `hook_form_alter`. Before saving it into the `$order->data` array, I do some validation stripping and formatting on future display.

Add phone number field below email address field:

Show phone number input with invalid characters that will be stripped out:

Successfully stripped invalid characters and show the saved phone number formatted for display:

**Here's the code to make this happen:**

```
/**
 * Implements hook_form_alter
 * Alter the checkout and review forms
 */
function example_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'commerce_checkout_form_checkout') {
    //Changing some titles and adding Bootstrap wrapper classes
    $form['account']['#title'] = t('Contact Information');
    $form['account']['login']['mail']['#title'] = t('Email Address');
    $form['account']['login']['mail']['#prefix'] = '<div class="row"><div class="col-xs-12 col-sm-5">';
    $form['account']['login']['mail']['#suffix'] = '</div></div>';
    $form['account']['login']['mail_confirm']['#title'] = t('Confirm Email Address');
    $form['account']['login']['mail_confirm']['#description'] = t('<small>Please re-enter your email address.</small>');
    $form['account']['login']['mail_confirm']['#prefix'] = '<div class="row"><div class="col-xs-12 col-sm-5">';
    $form['account']['login']['mail_confirm']['#suffix'] = '</div></div>';

    //add a phone number textfield to the account login array
    $form['account']['login']['phone_number'] = array(
      '#type' => 'textfield',
      '#title' => t('Phone Number (Optional)'),
      '#size' => 15,
      '#attributes' => array('class' => array('phone-number')),
      '#prefix' => '<div class="row"><div class="col-xs-12 col-sm-5">',
      '#suffix' => '</div></div>',
    );

    //load the order from the form state
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);

      $order = $form_state['order'];

      //prefill the phone number field if it's already been set in the data array
      if (!empty($order->data['phone_number'])) {
        $form['account']['login']['phone_number']['#default_value'] = _format_phone_number($order->data['phone_number']);
      }
    }

    //add a custom submit callback function to save the phone number to the order data array
    array_unshift($form['buttons']['continue']['#submit'], "_example_commerce_order_account_pane_checkout_form_alter_submit");
  }

  //show the phone number in the account info section of the review screen
  if ($form_id == 'commerce_checkout_form_review') {
    //load the order from the form state
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);

      $order = $form_state['order'];

      //append the phone number to the account info html. there's probably a better way to do this...
      if (!empty($order->data['phone_number'])) {
        $form['checkout_review']['review']['#data']['account']['data'] .= '<div class="form-item form-type-item"><label>Phone Number: </label> '._format_phone_number($order->data['phone_number']).'</div>';
      }
    }
  }
}

/**
 * Custom Account pane: checkout form submission callback.
 */
function _example_commerce_order_account_pane_checkout_form_alter_submit($form, &$form_state) {
  if (!empty($form_state['values']['account'])) {
    $pane_values = $form_state['values']['account'];

    // If the user is editing an order, load a fresh copy to merge changes into.
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);
    }

    $order = $form_state['order'];

    if (!empty($pane_values['login']['phone_number'])) {
      $order->data['phone_number'] = _strip_chars_in_phone_number($pane_values['login']['phone_number']);
    }
    else {
      $order->data['phone_number'] = '';
    }

    //don't cut a new revision, just save phone number
    $order->revision = FALSE;
    commerce_order_save($order);
  }
}

/**
 * Custom utility function to strip invalid characters from phone number input
 * leaving only digits
 * stripping a leading 1
 * substring first 10 digits
 */
function _strip_chars_in_phone_number($phone) {
  $strPhoneDigits = '';

  if (isset($phone) && !empty($phone)) {
    $strPhoneDigits = preg_replace("/[\D]/", "", $phone);
    $strPhoneDigits = preg_replace("/^1/", "", $strPhoneDigits);
    $strPhoneDigits = substr($strPhoneDigits, 0, 10);
  }

  return $strPhoneDigits;
}

/**
 * Custom utility function to format a phone number for display
 */
function _format_phone_number($phone) {
  $strFormattedPhone = '';

  if (isset($phone) && !empty($phone)) {
    if (strlen($phone) == 7) {
      $strFormattedPhone = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
    }
    elseif (strlen($phone) == 10) {
      $strFormattedPhone = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
    }
    else {
      $strFormattedPhone = $phone;
    }
  }

  return $strFormattedPhone;
}

```
> 4 votes

# Answer
I've found it useful to add fields to the Order object directly so that they are retained in the Orders UI and available for use in the Rules API when the order is completed. I can then create the user account via Rules.

More specifically, I use Profile2 to manage extra user data; I've added fields to the Order type (`/admin/commerce/config/order/fields`) and in some cases I can expose these as panes in the order form. For adding data to the user account section along with the email field, I found that the solution by @Wesley goes most of the way. However, adding data to the order object directly doesn't work unless you use entity metadata wrappers. (EMW has been a lifesaver for me on more than one occasion)

To extend his example, say we have a field on the Order type called "Phone Number" (default machine name `field_phone_number`); you will have to alter the callback function as follows:

```
function _example_commerce_order_account_pane_checkout_form_alter_submit($form, &$form_state) {
  if (!empty($form_state['values']['account'])) {
    $pane_values = $form_state['values']['account'];

    // If the user is editing an order, load a fresh copy to merge changes into.
    if ($form_state['order']->order_id) {
      $form_state['order'] = commerce_order_load($form_state['order']->order_id);
    }

    $order_wrapper = entity_metadata_wrapper('commerce_order', $form_state['order']);

    if (!empty($pane_values['login']['phone_number'])) {
      $order_wrapper->field_phone_number->set(_strip_chars_in_phone_number($pane_values['login']['phone_number']));
    }
    else {
      $order_wrapper->field_phone_number->set('');
    }
    // save the wrapper then convert to StdClass object
    $order_wrapper->save();
    $order = $order_wrapper->value();

    //don't cut a new revision, just save phone number
    $order->revision = FALSE;
    commerce_order_save($order);
  }
}

```
> 1 votes

# Answer
For Drupal 8: there is a great module https://www.drupal.org/project/commerce\_checkout\_order\_fields. Just enable it, go to /admin/commerce/config/order-types/default/edit/form-display, scroll down, enable 'Checkout' view, drag/drop fields on the Checkout view, and then go to /admin/commerce/config/checkout-flows/manage/default and add 'Order Fields: Checkout' pane to a step you want. Enjoy!
> 1 votes

---
Tags: commerce
---


title: Drupal 8 block css add

text:
# Question
Title: Drupal 8 block css add
I am using a fresh D8 install. I have created a custom block with a token which I have added to a header. The block is themes from somewhere to float left. If I, through "inspect" in the browser, add an element to float right. All my spacing works out great. I dont want to change other site feilds. Just this block and/or content to float right

How do I add CSS to get this block content to float right? Specific files would be handy or ? Your advise?

The html I have copied from the inspect looks like this

```
<div data-quickedit-field-id="block_content/2/body/en/layout_builder-default-0-73e5980c_7e7f_426b_9046_491d9b827238-2-01e8424e1f1f24943ed5c53651a4049d736f7ab2e67f5602d40887962c657805" class="w3-section field field--name-body field--type-text-with-summary field--label-hidden w3-bar-item field__item" style="float: right;"><h3><a href="/node/8" hreflang="en">Pro Safety</a></h3>
</div>

```

Thanks for Im sure a simple fix

# Answer
> 0 votes
The CSS changes are applied through a subtheme, but if you don't have access to that or only need to make small adjustment you can use the CSS Editor module to add your CSS.

The HTML you supplied doesn't seem to have a unique attribute you can use to target it reliably. Is there are wrapper div with an ID attribute around that code?

With classes you will likely style more than one component, this selector targets elements with both these classes:

```
.field--name-body.field--type-text-with-summary {
 float: right;
}

```

BTW you need to test your code in different browsers and browser window sizes to make sure you're not breaking the layout in some cases.

---
Tags: theming, blocks
---


# Question
Title: How do I use a "contains" operation as restful contextual filter for text fields
I'm trying to create a restful view which takes a string as input, search specific content-type titles for similar nodes and return them as result.

The problem is I can't figure out how to configure the contextual operation to act as *contains*.

# Answer
> 3 votes
When you expose a filter, you can set a filter identifier. This can be used to set the filter value via the URL, E.g.: /search?keywords=foo or /search?keyworks=foo+bar.

Note that if you need to hide this filter in a user view, you can do that with CSS or the Views Block View Filter module which allows you to move exposed filters to separate blocks that don't need to be placed on a user page. Not part of your specs.. but nice to know if you need REST and user pages.

Also, given your requirements, you might want to consider either using the Search API module with it's views structure or code your own rest handler.

The Search API module will lets you easily set up full text searches and manage results order based on boosts, e.g. words found in titles are more important. The DB backend works well in D8, so you don't need Solr server for this. (Though Solr has a lot of neat features).

Coding your own shouldn't be too hard with the D8 rest implementation. You can then do any query variations you need.

# Answer
> 0 votes
Create a rest view as per the image and access the results by this link YOUR-WEBSITE.COM/api/v1/schools?name=COLLEGE\_NAME

---
Tags: views, services, 8
---


title: Error: Undefined index: render element

text:
# Question
Title: Error: Undefined index: render element
I encountered an error:

```
Error message
Notice: Undefined index: render element in Drupal\Core\Theme\ThemeManager->render() (line 200 of core/lib/Drupal/Core/Theme/ThemeManager.php).
...

```

I found the source of the problem, in my `THEME.theme` file, I have this hook:

```
function THEME_preprocess_paragraph__header(&$variables) {
    $blockInstance = Block::load('searchblock');
    $variables['searchBlock'] = \Drupal::entityManager()
        ->getViewBuilder('block')
        ->view($blockInstance);
}

```

In my twig file, I have this code

```
{% block paragraph %}
    {{ searchBlock }}
{% endblock paragraph %}

```

Why is it showing `Undefined index: render element`?

I tried to put `print_r($variables['searchBlock'])`, and this is the output:

```
Array
(
    [#cache] => Array
        (
            [keys] => Array
                (
                    [0] => entity_view
                    [1] => block
                    [2] => searchblock
                )

            [contexts] => Array
                (
                    [0] => languages:language_interface
                )

            [tags] => Array
                (
                    [0] => block_view
                    [1] => config:block.block.searchblock
                )

            [max-age] => -1
        )

    [#weight] => -6
    [#lazy_builder] => Array
        (
            [0] => Drupal\block\BlockViewBuilder::lazyBuilder
            [1] => Array
                (
                    [0] => searchblock
                    [1] => full
                    [2] =>
                )

        )

)

```

In the twig file, I tried to put `dump(searchBlock)`, and this is the output:

```
array(3) {
  ["#cache"]=>
  array(4) {
    ["keys"]=>
    array(3) {
      [0]=>
      string(11) "entity_view"
      [1]=>
      string(5) "block"
      [2]=>
      string(11) "searchblock"
    }
    ["contexts"]=>
    array(1) {
      [0]=>
      string(28) "languages:language_interface"
    }
    ["tags"]=>
    array(2) {
      [0]=>
      string(10) "block_view"
      [1]=>
      string(30) "config:block.block.searchblock"
    }
    ["max-age"]=>
    int(-1)
  }
  ["#weight"]=>
  int(-6)
  ["#lazy_builder"]=>
  array(2) {
    [0]=>
    string(42) "Drupal\block\BlockViewBuilder::lazyBuilder"
    [1]=>
    array(3) {
      [0]=>
      string(11) "searchblock"
      [1]=>
      string(4) "full"
      [2]=>
      NULL
    }
  }
}

```

Seems that the problem occurs in my custom block `SearchBlock` plugin. Here's the content on the `SearchBlock.php`:

```
<?php

namespace Drupal\site_core\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block with search information.
 *
 * @Block(
 *   id = "site_search_block",
 *   admin_label = @Translation("Custom Search Block"),
 * )
 */
class SearchBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#theme' => 'site_search_block',
      '#attached' => [
        'library' =>  [
          'site_core/autocomplete'
        ]
      ],
      '#cache' => [
        'max-age' => 0
      ]
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }
}

```

Here's my `hook_theme` function:

```
function site_core_theme() {
  return [
    'site_search_block' => [
      'template' => 'site-search-block',
    ]
  ];
}

```

Here's my `site-search-block.html.twig`:

```
<div class="search-bar">
    <select id="source" style="height: 0px; width: 0px; position: absolute; border: none; padding: 0px; margin: 0px;">
        <option value="type1">Type1</option>
        <option value="type2">Type2</option>
    </select>
    <div class="term">
        <div class="box-input">
            <input autocomplete="off" class="search-term ui-autocomplete-input"
                data-type1-autocomplete="true" id="searchTerm" name="searchTerm" onkeypress="return searchOnEnter(event)"
                placeholder="Search" />
        </div>

        <div class="box-remove"><button class="btn-remove" onclick="jQuery('#searchTerm').val('');">X</button></div>

        <ul class="ui-menu ui-widget ui-widget-content ui-autocomplete ui-front" id="ui-id-1" style="display: none;"
            tabindex="0">
        </ul>
    </div>
    <input class="btn-submit" onclick="search()" type="button" value="Go" />
</div>

```

Can anyone help me with this?

# Answer
If you don't set a `variables` key for a theme hook implementation, the system defaults to expecting a `render element`. It appears your theme hook doesn't require either of those, so you can fix it by setting an empty array for `variables`. You can change this:

```
function site_core_theme() {
  return [
    'site_search_block' => [
      'template' => 'site-search-block',
    ]
  ];
}

```

To this:

```
function site_core_theme() {
  return [
    'site_search_block' => [
      'template' => 'site-search-block',
      'variables' => [],
    ],
  ];
}

```
> 21 votes

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


# Question
Title: How to upgrade to Drupals latest version via Composer?
Currently I have 8.6.13 installed.

```
composer update drupal/core --with-dependencies
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update

```

When I tried to look in to `composer.json` we don't have `drupal/core` in

require.

https://www.drupal.org/docs/8/update/update-core-via-composer

How to upgrade to 8.7.0?

```
$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.0].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.1].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.10].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.11].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.12].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.13].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.14].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.2].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.3].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.4].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.5].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.6].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.7].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.8].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.9].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.x-dev].
    - Can only install one of: egulias/email-validator[2.0.x-dev, 1.2.15].
    - drupal/core 8.7.0 requires egulias/email-validator ^2.0 -> satisfiable by egulias/email-validator[2.0.x-dev].
    - Installation request for drupal/core 8.7.0 -> satisfiable by drupal/core[8.7.0].
    - Installation request for egulias/email-validator ^1.2 -> satisfiable by egulias/email-validator[1.2.0, 1.2.1, 1.2.10, 1.2.11, 1.2.12, 1.2.13, 1.2.14, 1.2.15, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.2.8, 1.2.9, 1.2.x-dev].

```

# Answer
> 1 votes
I had exactly the same issue while performing upgrades. The solution for me was removing/renaming the *vendor* folder and the *composer.lock* file and run `composer update drupal/core --with-dependencies`.

You can also try to update dependency explicitly with `composer update egulias/email-validator drupal/core --with-dependencies`. This usually works in this type of issues, but it didn't work for me.

Given that you don't see drupal/core in your composer.json you might also try `composer require drupal/core`.

# Answer
> 0 votes
Before installing with Composer, make sure to remove the *vendor* directory and the *composer.lock* file and run `composer install`.

---
Tags: 8, upgrading
---


# Question
Title: How can I duplicate a site without users and nodes?
I have a full site which has nodes, users, views, organic groups... What I need to do, is with f.e. module 'backup and migrate', take this site named A, into a new server, and keep all logic (content types, views, organic group settings), but have no users at all (except user 1 of course), no nodes at all, actual delete everything, but keep all the functionality of the site.

For instance, if site A has already say 5k users, and 1m nodes, start with the site B with 1 user, and not a single node. How can this be achieved? Is there a module or do I need to run a script into MySQL?

# Answer
In drupal 8, this would be no problem thanks to the Configuration API. For drupal 7, it is a bit harder. You should take a look at the Features module: this module can save configuration in a module. Then, you can enable that module in a new website (which would create content types, views, etc.).
> 0 votes

---
Tags: 7
---


# Question
Title: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?
I have seen many times people saying not to use custom PHP/PHP filter (from the Drupal UI) in blocks, nodes, views-args, rules, etc. I have searched around a bit and haven't found much, it seems like this is a Drupal best practice that all "just know".

I understand it poses a potential security risk especially in the hands of end users or people new to Drupal or PHP, but as a developer/site builder what are the real reasons to not use custom PHP from the Drupal UI?

# Answer
> 131 votes
Some reasons:

* Code in your database can not be version controlled and is also harder to find in general later on.
* Eval()'d code is *much* slower than something hardcoded in a file.
* If there is an error somewhere in that code, you will get a very unhelpful error message (error in eval()'d code at line 3) and you might even have go through your database manually to find and fix the error. If it is inside a block that is displayed on all pages and results in a fatal error all the time for example.
* The above is also true when upgrading from Drupal 6 to 7 and whatever API's you used were changed. So you will have to port your code while migrating. If the code is in a module, you can port it in advance, test it, and only deploy it on the new site. Inside a node or block, it will only work with either Drupal 6 or 7.
* Writing and maintaing that code is also harder, because you are working in a textfield inside your browser. Having it in a module allows you to use an editor/IDE with syntax highlighting, autocomplete and so on.
* There is always the possibility of a misconfiguration that gives people access to a text format/block/whatever with php execution enabled. If php.module (in D7, D6 is not so strict, for example for block access rules) isn't even enabled, that risk is much lower already.
* If your CMS allows execution of PHP then an attacker who finds a security vulnerability of XSS or privilege escalation can now use your server for enormously malicious things (as part of a DDOS, sending spam, hosting malware, hacking into other sites/databases on the server, hacking into other servers on the network that might be behind firewalls). In addition to making small vulnerabilities more painful, this makes the site a more likely target of attack if its known that it can be used to execute php.

There might be more reasons, but that should be enough :)

# Answer
> 18 votes
This code is difficult to debug and maintain. I don't know any way to use version control for such kind of php code.

And it's really a potential security risk for people new to Drupal or PHP,

# Answer
> 14 votes
Considering the case of the PHP filter used in a node, the reason not to use it is that you limit the users who can edit that node, if you don't want to allow all the users to use the PHP filter.
Rather than using the PHP filter, it is better to use a custom module that replaces specific text in the node content with the result of the code it executes (without using `eval()`), or that appends its own text to the body content of the nodes. In this case, any user could edit the node, without to have the permission to add arbitrary PHP code that is then run by the PHP filter.

Generally, it is better to avoid `eval()` because it decreases the readability of the code, the ability for you to predict the code path (and possible security implications of that) before runtime, and hence the ability to debug code.

Apart in a development or a test site, I would not enable the PHP filter, or use PHP code that is passed to `eval()`.

The PHP filter has been removed from Drupal 8. It is now a third-party module, not covered from the security advisory policy. This is probably a reason more for not using it in production servers (if the already given reasons didn't convince you).

# Answer
> 11 votes
As a work-around for the various problems specified above - difficulty of code maintenance, version control, error-finding, you have this slightly "klugey" possibility:

Create functions (name them carefully, according to what they do) in some file that's always included - if you have a custom module you're writing for the site, that's a great place to put these functions. The php you enter then is simply: `return my_specialfunc($somevar);` \- `$somevar` here potentially being the node object worked on, or whatever other variables are relevant here.

I find that I still usually want the flexibility, in some places, of calling my own code. In using this technique, maintaining the code is easy since it's simply a matter of modifying the function in the file. Error-spotting is easy since the function will show up in a backtrace.

Notice, however, that this doesn't solve the potential security issues. These are largely dependent upon the security of the Drupal core. In general, database-contained code is often an achillees' heel of security - functionalities using database-contained code tend to be much more prone to exploitation, and security around them needs to be extra-tight. However, Drupal has in general been quite good at maintaining security for these issues - they have arisen and then quickly patched / solved with new releases.

# Answer
> 11 votes
Here is the security vulnerability reason to avoid giving this permission to your users if you don't want your non-admin users to modify the db directly.

```
<?php
echo file_get_contents(dirname(__FILE__)."/../sites/default/settings.php");
?>

```

Hacking the Drupal db credentials

# Answer
> 7 votes
Rather than doing something like `return functionname($object)`, it would be better to use the tokens/filters system insofar as possible. There are modules like Insert View and Embed Node that can help with common circumstances in which people would want to embed PHP in node or block bodies.

# Answer
> 0 votes
You should care about portability of your data. What if you migrate your nodes from drupal 7 to drupal 8 and some node's body text has `<?php whatever_function_that_does_not_exist_anymore(); ?>` in it?

Do not think about your project within 5 months but within 5 years. Updates, good practices and portability are important aspects of any good IT project in my opinion.

Using as less contributed modules as possible is also one aspect of this.

---
Tags: security
---


# Question
Title: When is it appropriate to create an entity instead of a new content type?
What is the benefit to creating new entity types over just building a new content type?

It seems a bit overkill to do all of the custom coding that is required to create a new entity when you have all of the CRUD and Views functionality already built into content types.

# Answer
It's not so much about what the benefits are but more about what's appropriate for a particular situation like you've said. You can represent pretty much anything with a node and for 99% of situations (as I've found at least) you won't need to implement custom entity types.

I always think of the `taxonomy_term` entity type as a good example of why not everything should be a node/content type:

A taxonomy term is essentially for grouping together different entities and as such doesn't require the same functionality as a node. While you *could* theoretically use a content type to perform this functionality (with perhaps a node reference field), a taxonomy term doesn't need to do the same thing as a node so it doesn't really make sense to do so. The same can be said for the `user` and `taxonomy_vocabulary` entity types.

So a taxonomy term is created as a separate entity and is programmed to do only what it needs to, while still getting the benefits of being able to have fields attached, etc.

I think the simple answer is that when a node/content type *doesn't* do what you need it to, or it's just a massive amount of overkill/overhead for very little benefit, then you should choose to write a custom entity.

This is only based on my personal experience; I'd be interested to hear what someone directly involved with Drupal core development had to say about this.
> 70 votes

# Answer
A very simple rule of thumb I use is whether your content need to be publicly displayed on its own. If so, then go for node, if not choose an entity. Entityforms now allows you to create an interface to fill out your entities.

For example, on a website made with D6 we build an advertisement content type (with its image field, begin/end display date...), but then you have to make it *not published* by default and give your editors the rights to edit/view these node and hoped no views/search will display these on the outside world. It's quite cumbersome and it would be easier to deal with entities.
> 17 votes

# Answer
An entity represents a specific **use case**.

I believe the credit for this simple definition goes to Fago, but I'm to lazy to find a reference.

We could use `Content` (aka `Nodes`) for all use-cases if we wanted to, but often that doesn't make sense.

`Content` has an author and settings for both comments and menu location.

`Users`, represent a use case different enough from `Content` because on a `user` neither of the above makes any sense, while on the other hand, a `user` must have an e-mail and a password.

`Taxonomy terms` stand out because they have the built in functionality to be arranged in a hierarchy, even a circular one.

If your use-case is similar enough to an existing entity, go with using that entity. If your entity is governed by significantly different rules than any existing ones though, create a new one.

There is also An Introduction to Entities, but unfortunately it doesn't really answer your question.
> 13 votes

# Answer
I think it is all about the context, a node is largely used for content so that would be blogs, articles, faq's etc. While user for profiles like staff, customers etc. Example of when you might create a new enitity:

* Forum
* Project (in terms of project management)
* Form
* Support ticket
* Group

While you could use a node for something like a support ticket it might not be the best template and defaults... Hope that helps.
> 5 votes

# Answer
This is subject to discussion and in the end you have to make your decisions as a developer.

I choose entities over nodes whenever the data should not be publicly available with their own url. Nodes are getting by default a url alias, published status, a title, meta tags, ... while entities just get a record in the database.

> "I want to be able to add as much banners with text as possible and then in a blogpost choose between one of them"

* Content type would be 'Blog'
* Custom entity would be 'Banner item'
> 2 votes

# Answer
Entities can be created with less overhead than nodes since they don't need to have all the heavy-duty functionalities that entities have.

It also means storage can be simpler - you can build them to grab all the information in a simple query without JOINS if you want. All the fields nicely in just one tidy table.

This can be a huge benefit if you have a lot of functions that need to do queries on the entities, and you are updating lots of entities simultaneously with UPDATE queries to the database. If you can make sure the data is relatively self-contained in a single table, you have fewer worries and possibilities of data corruption.
> 1 votes

# Answer
A content type is designed to be site content. That is, each content type is designed to be publish and appear on the site. For example, an article (out of the box) is designed to appear on the first page.

Now, let's say you want to create an something like an employment or apartment application form. Obviously, you would not want to publish someone's employment application on your web site. Also, what if you wanted to build a list of customer / lead contacts? Would you want to take a chance that this information might be published by mistake on your web site? Personally, I would not.

Hence, the entity form module that is discussed above. It allow you to create a entity type that is not designed to be content. However, these entity types are available to any module that supports entities such as rules, views, and organic group to name just a few.

And then you get into Drupal Commerce where the products are entity types. Basically entities enable developers to extend Drupal in way never foreseen by the original Drupal designers.
> 0 votes

---
Tags: entities
---


# Question
Title: Referencing "type" in nodes returned by loadMultiple();
I know there are easier ways to sort nodes by type, using views, or using:

```
$query->loadByProperties(['type' => 'my_content_type']);

```

... but what I really want to do is return ALL nodes and then do different things based on the type field, like so:

```
$result = \Drupal::entityQuery('node')->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

foreach ( $nodes as $node ) {
  if ( $node->type == "my_content_type" ) {

    // do something...

  } else {

    // do something else...

  }
}

```

However, my condition is never getting met, so I can only conclude that I am referencing the node type incorrectly. What am I doing wrong?

# Answer
Thanks @berramou the solution is to use:

```
if ( $node->bundle() == "my_content_type" ) { ... }

```

Solved!
> 1 votes

---
Tags: 8, entities
---