# Question
Title: File Upload visible in $_FILES but drupal file functions create empty file
I created a custom form with a file upload field:

```
$form['csvfile'] = array(
    '#title' => 'CSV File',
    '#type' => 'file',
);

```

When I submit the form, I can see the correct information in the $\_FILES array:

However, when I try to use the code in the examples module to get the contents of that file and write it to an unmanaged file, the file is empty.

So, the resulting file is 0 bytes long.

How do I access the uploaded file in a drupal-y way? I know I can just use the basic PHP functions to access the file, but I'm trying to learn how to do it the way drupal intends.

My submit handler code is almost entirely lifted from the examples module.

```
function herdapi_form_bulkupload($form, &$form_state) {
    $form = array();
    $form['email'] = array(
        '#title' => 'Owner Email',
        '#type' => 'textfield',
    );

    $form['password'] = array(
        '#title' => 'Password',
        '#type' => 'password',
    );

    $form['csvfile'] = array(
        '#title' => 'CSV File',
        '#type' => 'file',
    );

    $form['submit'] = array(
        '#value' => 'Upload',
        '#type' => 'submit',
    );

    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = FALSE;

    return $form;
}

function mymodule_form_bulkupload_submit($form, &$form_state) {

    dsm($form_state);
    dsm($_FILES);
    $data = $form_state['values']['csvfile'];

    // With the unmanaged file we just get a filename back.
    $filename = file_unmanaged_save_data($data, NULL, FILE_EXISTS_REPLACE);
    if ($filename) {
        $url = file_create_url($filename);
        $_SESSION['file_example_default_file'] = $filename;
        drupal_set_message(
            t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)',
                array(
                    '%filename' => $filename,
                    '@uri' => $filename,
                    '!url' => l(t('this URL'), $url),
                )
            )
        );
    }
    else {
        drupal_set_message(t('Failed to save the file'), 'error');
    }
}

```

# Answer
Drupal forms which include a file upload field must also set the encoding type to multipart/form-data.

```
  $form['#attributes']['enctype'] = 'multipart/form-data';

```

Reference: Drupal.org: Uploading Files

---

There is a good checklist for debugging your situation here:

https://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php

Not mentioned in the checklist there is that Suhosin, a commonly installed extension, can empty some submitted values. As well as following the checklist in the linked question, check to see if you have Suhosin installed - if so then you may be

One thing I'd try straight away is whether uploading a *very small file* triggers this bug. If so that might suggest that you're hitting a limit in PHP's max post data or Suhosin.
> 1 votes

# Answer
Even though this is an old question, it is among the first results when looking for this matter using Google. The answer is found in https://www.drupal.org/node/1537950 from where I modify a little the original code:

```
function mymodule_form_bulkupload_validate($form, &$form_state) {
  $file = file_save_upload('csvfile', array(
    'file_validate_extensions' => array('csv'),
  ));
  if (!$file) {
    form_set_error('csvfile', 'No file was uploaded');
  }
  $form_state['values']['file'] = $file;
}

```

Long story short, since this isn't a managed\_file, Drupal doesn't do anything more than just add the "multipart/form-data" to the enctype attribute of the form. Anything more, like saving locally the $\_FILES, validating and adding the $file to the $form\_state array is something you are responsible for.
> 1 votes

---
Tags: 7, forms, files
---


# Question
Title: Pass node field value to view filter in a block
**Background**

For the node type *article* I want to display a block view of map markers generated from a content type called *sted* (places). For the content type *article* I have made a entity reference field (multiple values allowed) called *kartreferanse* (map reference) where you can pick multiple nodes of the type *sted* (places). So far so good. I have also made a view in a block that displays markers for all the content types *sted* (places) using a Geolocation - CommonMap. Now I want to pass the reference field to the view to show only the places picked in the field *kartreferanse* (map reference) for the current node. I have tried using contextual filters *(field\_kartreferanse: Content) Content: ID* with no luck, and/or tried building a relationship using *field\_kartreferanse: Content* in the view.

**The question**

How can i pass the ID of the current node (article) to the view (in a block) and use the entity reference field in the article to show right node IDs in the map block view? Do I also have to make some filter-criteria for this to work? (field\_kartreferanse: Content) Innhold: ID (= \[Content: Nid\]) (Later I will have to make this view work in a multilingual site.)

(Drupal 8, local install / mamp, geo locationfield, views 8.1.10)

# Answer
> 7 votes
The easiest way to use a view in a block (or anything that uses a build array) is as a render element:

```
$node = \Drupal::routeMatch()->getParameter('node');

$current_nid = $node->id();

$view_arguments = [$current_nid];

 $build['news'] = [
   '#type' => 'view',
   '#name' => 'myviewname',
   '#display_id' => 'block_1',
   '#arguments' => $view_arguments,
   '#weight' => 30,
 ];

return $build;

```

The first argument passed in will be used as your content ID.

If you want to do it all through the UI, you set your contextual filter to pull from the content id.

then if you place a block based on the view, it will pull in from the current node.

# Answer
> 7 votes
Finally i made it.

**First** you make a content type for the items (in this case *sted* / *place*). Then you make or edit the content type where the relevant items is going to be displayed (in this case *article*). For the articles you add a reference field. The `Type of item to reference` is `content` and the content type to reference is *your items* content type. (I chose unlimited values for the field).

**Create a view** that shows content of the type *your items* in a block and choose the styling you want (e.g. grid, unformatted list, custom style...). The preview of the view now show all your items. Edit one of the articles so that it reference one/some of the items (not all). Add the view block to be displayed with the **articles**.

**Edit the view to show only the relevant items:**

**(advanced) Relationships** add: `Content using field_your_refernce_field - (Relate each Content with a field_your_refernce_field set to the content.)`.

**(advanced) Contextual filters** add: `CONTENT ID`. Edit the Contextual filter (CONTENT ID) `When the filter value is NOT available` `Provide default value` `Content ID from URL` and (above) "Relationship:" choose `field_your_refernce_field`

(For the view preview add the ID of your test-article into the `Preview with contextual filters:` to see the result.)

---
Tags: 8, views, google-maps
---


# Question
Title: Restricting access to specific nodes for specifc users?
Using drupal 7 I have implemented `hook_node_access` but am having real trouble figuring out how to go a step further and achieve the following using `hook_node_access_records` and `hook_node_grants`.

For a given content type ('submission') I want to limit users with a particular role ('curator') and an additionally set field in their user profile ('location') to see only nodes that have a specific matching field value set ('location').

So in this case curators from London can only see submissions to the gallery in London rather than see all 'submission' nodes.

**Update**

I have made some progress here in my understanding. See the code below. My question now is can i do the following to check set a realm and grant id that i can use to lock specific users out?

Below I am trying to set a lock such that any user who has the grant id cannot access the node (this will be a subset of people within a given role) and for everyone else I just want the sites normal configured access permissions to apply.

```
function hook_node_access_records($node) {

$grants = array();

if ($node->type == 'submission') {

    $grants[] = array(
      // Say this node is in our realm.
      // By convention we prefix the name of the realm
      // with the module name.
      'realm' => 'submission-permissions',
      // Define the grant id - users in the realm must
      // have this grant id to access this node.
      'gid' => $node->field_location[LANGUAGE_NONE][0]['target_id'],
      // Users who match cannot view the node.
      'grant_view' => 0,
      // Users who match cannot update the node.
      'grant_update' => 0,
      // Users who match cannot delete the node.
      'grant_delete' => 0,
      // In the case another module provides exactly
      // this access record, the one with the highest
      // priority wins. Usually leave this as 0.
      'priority' => 100,
    );
  }

}

/*
 * Implements hook_node_grants().
 */
function hook_node_grants($account, $op) {

    $grants = array();

    $role = is_string($account) ? $account : $account->roles[4];

    if (($role == 'curator') && ($op == 'view')){

        // Get the currently looged in users accounts details
        $user_fields = user_load($account->uid);

        $location = is_string($user_fields) ? $user_fields : $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        if (!empty($location)){

            $grants['submission-permissions'][] = $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        }

    }

    return $grants;

}

```

# Answer
I had to do something similar in a project last year and ended up using Taxonomy Access Control (TAC). If you make your location field a taxonomy and use the same taxonomy field on your user profile and content type, you can set perms for your curator role relative to the taxonomy term. It has to be enabled on a role by role basis so it won't impact any other roles on your site.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: What is replacement of SSL/HTTPS in drupal to encrypt login credentials
I have one question, in my website i am not using ssl so my drupal login send id and password as plain text, then i have used the **encrypt\_sumissions** module but that is use **jcryption** library but this is not useful, I want to know how can i encrypt login credentials without ssl/https.

Should I change in drupal core, I am new to this please provide me detailed information. Thanks

# Answer
> 3 votes
Save yourself the headache and use TLS/SSL. Drupal won't, and isn't meant to, solve your problem. It isn't worth trying to cobble something together. If the cost of the certificate is an issue, go to https://letsencrypt.org/ and get a free cert.

---
Tags: users
---


# Question
Title: How to award User Points after checkout using Rules?
I'm trying to award some User Points to users who select a certain plan during his checkout process.

Here is the explanation of my website functionality.

1. When a user register with a role, the user will get access to the website with certain functionality.
2. Some users will be having permission to create new nodes.
3. During the node creation, the user needs to select a plan (I'm using `Commerce Node Checkout` module to add product as plan).
4. Based on the user's selection, the user will be redirected to the checkout page.
5. After completion of the checkout process, the user will receive some User Points. For this I have created a rule, but it is not working as expected.

Here is the export of my rule:

```
{ "rules_per_day" : {
    "LABEL" : "Per day",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "per day" ],
    "REQUIRES" : [ "commerce_order", "userpoints_rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "commerce_order_contains_product" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "product_id" : "day_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI",
          "operator" : "=",
          "value" : "1"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "50",
          "tid" : "0",
          "entity" : [ "commerce-order" ],
          "description" : "You have received  the points for selected plan.",
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "approved"
        }
      }
    ]
  }
}

```

The Rules Condition checks whether the order contains a specific product withe the product id `n`.

I don't understand what I did wrong or what I have missed in this rule. Any suggestions to make this rule work?

# Answer
In order for your Rules Condition to be satisfied, ***ALL*** these criteria must be true:

* Order contains the product whereas the SKU of that product must be "***day\_4dxivfX2oFRAqQH-Ij6VBFnBheZBRIo744cF46KKPSI***".
* The quantity of the specified product on the order must be "***= 1***".

Since the user does not seem to receive the userpoints, it must be because of either of these reasons:

* **Reason 1**: your Rules Condition is not satisfied. Assuming that there is no typo in the SKU value, it could be because the quantity is NOT "***= 1***".

As a quick check to find out if this is what is causing your issue, simply do a test in which you (temporary) change this rules condition to the opposite, by using the "negate" checkbox for that Rules Condition. If in that scenario the userpoints are granted, you can be sure that the quantity is indeed NOT "***= 1***" (even though you may think/expect that to be the case ...).
* **Reason 2**: your Rules Condition is OK, but your Rules Action for some unknown reason does not actually grant the points to the user.

As a quick check to find out if this is what is causing your issue, just add another Rules Action (before the one you have already) to simply "Display a message" (which you find within "System"). All the message should be is something like "Rules Action triggered". If in that scenario such message is actually shown, you can be sure that the cause of your problem is something related to your Rules Action (to grant points) that is not working as you think/expect it to work.

If none of the above helps, then it's time for Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".
> 1 votes

---
Tags: 7, nodes, commerce, rules, userpoints
---


title: How to change view title tag <h1>?

text:
# Question
Title: How to change view title tag <h1>?
Drupal uses the `<h1>` tag in the title of the view. I want to change title's tag `<h1>` to `<h2>`.

# Answer
> 2 votes
hope this will help you..

```
function mymodule_views_pre_render(&$view) {

  if ($view->name == 'view_name') {

    // Here you can do any php you want to get the title you need for your view.

    $view->build_info['title'] = "<h2>My custom title!</h2>";
  }

```

or by views-view-unformatted--**viewmachinename**.tpl.php file

```
 <?php if (!empty($title)): ?>
  <h2><?php print $title; ?></h2>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

```

# Answer
> 2 votes
You can change the title, as well as h1 to h2, using view title

# Answer
> 2 votes
You can trick this leaving empty the title view field and adding the title as a text on the header view area.

# Answer
> 1 votes
This can be done with a simple configuration supported at the views-fields area.

Click the title field you want to theme under the **Fields** area and configure the following in the pop-up,

Under the **Rewrite results** tab enable the option *Rewrite the output of this field*, here you will be having the replacement token for title configure it as

```
<h1>[title]</h1>

```

If you still need to strip all the other html tags in the title check the **Strip HTML tags** (This will strip all the html tags including the `<h1>` tag you have configured above hence add the `<h1>` tags in the **Preserve certain tags** )

# Answer
> 1 votes
You can find the `<h1>` tag for the title in the page.tpl.php file of your theme.

If the path of your view is 'bike', you would use page--bike.tpl.php. If your path is 'bike/three\_wheel' you could use page--bike-three\_wheel.php.php.

1. Copy the page.tpl.php file to a folder
2. Rename the file (page--bike.tpl.php)
3. Edit the file with your new tag (or another thing)
4. Save the file
5. Put the file in the same place of your page.tpl.php file
6. Clean the cache
7. Enjoy

Reference:

How to override Views use of page.tpl.php

---
Tags: views, theming
---


# Question
Title: PluginNotFoundException: "The "iframe" plugin does not exist." at core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52"
**how to solve such error:**

```
Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "iframe" plugin does not exist." at /var/aegir/platforms/drupal8-dev/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52" while reading response header from upstream, request: "GET /admin/config/content/formats/manage/basic_html HTTP/1.1"

```

The plugin 'iframe' have been existing since i found it in the enabled filter list

```
  http://drupal.stackexchange.com/questions/218781/create-a-new-text-format-filter

```

then i believe when i have clear the cache at some stage it came up with this exception when trying to acces again to

```
        admin/config/content/formats/manage/basic_html

```

where i have initially add this plugin filter

The exception come up when i am trying to uninstall the module so it is problematic

it seems that this error is reccurent when i googleized it but i did not found where the problem lies

# Answer
removing manually the module and deleting the %iframe% entry in config table should do

it happens when there's no definitition of the plugin

```
   /*protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) {
// Avoid using a ternary that would create a copy of the array.
if (isset($definitions[$plugin_id])) {
    return $definitions[$plugin_id];
}
elseif (!$exception_on_invalid) {
    return NULL;
}

throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));

```

so what i understand is my custom module dont have a valid plugin manager !?

https://www.drupal.org/docs/8/api/plugin-api/d8-plugin-discovery
> 0 votes

---
Tags: 8, input-formats
---


# Question
Title: How to hide a block for specific users using Views?
I have a bunch of blocks that I would like to have hidden by default and only shown to specific users that will be determined by a view.

Is this possible? If so, how?

# Answer
> 1 votes
Under the block settings in views, there is an option called "access," which you can use to allow access based off of role (anonymous user, registered user, etc). If your users have specific user roles that you can filter off of, you can use this to do what your looking for.

# Answer
> 0 votes
Probably not the best way to go about this, as you really don't want to put logic in the theme... but if you are using some other way to single out users other than roles, you could always use a check in the theme to make sure the user should have the block displayed, if so, print the contents in views-view--myview.tpl.php.

# Answer
> 0 votes
# Part 1:

Enable the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is **YES** or **NO** (a boolean, right?) a user with a `uid` that matches one of the users you're looking for.

# Part 2:

Here is a Rules Component which you can use as an example (you should be able to import this rule in your own environment if you have the Rules UI enabled):

```
{ "rules_block_visibility_show_block_for_some_uid" : {
    "LABEL" : "Show block for some uid",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the user's uid is YES or NO equal to `1`. Adapt the value of the uid to fit your needs, and/or add other uids you'd need via an additional (OR) Rules Condition.

With that, we're coming close to an actual answer to your question.

# Part 3:

Head over to the "Block" settings for the block you want to show only for the user with (eg) `uid = 1`. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

All you have to do is to select the Rules Component from Part 2.

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.

---
Tags: views, blocks
---


# Question
Title: Change system mail on run time when sending mail
I have 4 domains using domain access module like a.com, b.com, c.com, d.com. currently when user registers he receives a mail from admin@a.com which is default in site configuration. Now what I want is to Change system mail on run time with respect to 4 diffrent domains so that when user registers from b.com he will receive mail from admin@b.com and so on.As this info is saved in system configuration so how to change the mail id of the site when sending mail on run time.

# Answer
You can alter the mail using `hook_mail_alter(&$message)`

> Alter an email message created with MailManagerInterface-\>mail().

with in message array you have 'from' field as well.

Example

```
function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {
    // Login to get domain specific email id.
    $email_id == _some_logic_to_get_email();
    $message['from'] = $email_id;
  }
}

```

Refernce: https://api.drupal.org/api/drupal/core%21core.api.php/function/hook\_mail\_alter/8.2.x
> 4 votes

---
Tags: 8, emails
---


title: Apply image styles to image field

text:
# Question
Title: Apply image styles to image field
I have a code where view is rendered programatically and it contains an image field. However usually images are coming from nodes where different image style is applied so location of image is in different folder. If I preview the view manually style is applied and images appear in the proper styles folder but if this is executed by code it doesnt happen. Anyone with ideas how easily to trigger application of image styles from the code without walking each returned image field, checking is image style applied and so on.

# Answer
I went with only solution which came to my mind - foreach the view results, check the image fields and then apply image style and create derivatives. Because when view render image fields programatically it doesn't actually set the files in proper styles folder, it is done on browser request but this doesnt suit our use case.
> 0 votes

---
Tags: views, theming, media
---


title: How can I add a fee programmatically?

text:
# Question
Title: How can I add a fee programmatically?
I know how to add a line item programmatically, but I can't seem to find a way to specifically add a custom commerce fee in PHP. Commerce fees seem to register in two locations in the order array: Once under commerce\_line\_items, and once under commerce\_order\_total (See attached image). They are different than a regular line item in that they don't show up as products, but rather in the order totals box at the end of the order. The fee shown in the attachment is one that has been entered using the Edit form in the admin section. I need to add one in code. Any ideas?

# Answer
What you're seeing is the commerce price component and the relevant line item that were added to the order. It gets added by the `commerce_fees_apply()` function from `commerce_feeds.rules.inc`.

So, if you're wanting to programmatically add a $5 fee to an order, then you can do so like this:

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = commerce_fees_load('machine_name_of_fee');
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');

```

Where `'machine_name_of_fee'` would be the machine name of the fee that was created using the UI. Remember that the 3rd argument will be an amount and not a decimal. You'll also need to pass in the currency code. If you're wanting it to take the value of the currency code of the order, you could replace `'USD'` with something like.

```
$currency_code = $order->commerce_order_total[LANGUAGE_NONE][0]['currency_code'];
commerce_fees_apply($order_wrapper, $fee, 500, $currency_code);

```
> 1 votes

# Answer
If you stucked in why #1 doesn't work, you should try something like this:

```
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'FEE_MACHINE_NAME';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
$order_wrapper->save();

```

Good luck!
> 1 votes

---
Tags: commerce
---


# Question
Title: Sending email notifications to webform submissions
I am trying to create a rule that will send an email to a list of webform submissions, notifying them when new content is created. So far, here's what I have:

**Event**: after saving new content of type \[type\]

**Conditions**: content is of type

**Actions**: Using a Rules view display, I'm grabbing the webform submissions, and then looping through to send mail to the value of the webform submissions.

All works well, until I need to send the mail. Rather than looping through and sending to the email addresses that I'm trying to get from the webform submissions, it appears to be sending to the submission ID instead.

I'm sure there's something I'm missing in either my rules view display, or the rule itself, but I've hit a wall. Anyone know what I might be doing wrong?

# Answer
To make this work, you should *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of webform submissions that you want to be processed.
* add a loop to perform a Rules Action, for each webform submissions contained in your Views results.

Since you want this Rules Action to be "... sending to the email addresses ...", you need to make sure that these email addresses are contained in the Views result (if needed enhance you view to have them included).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".
> 0 votes

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


# Question
Title: Moving from subdomain to top level, link/image paths incorrect after manual edit
TL;DR Filepaths contain old subdomain prefix after find replace database and site code, can't determine cause.

I have a hosted site on `mywebsite.com/drupal`, I want to move it to my computer `localhost`.

I have a LAMP stack and I compress and download the contents of `mywebsite.com/drupal` and export its mysql database, `mydb.sql`, using phpmyadmin.

I uncompress and place all the files from `mywebsite.com/drupal` in `/var/www/html/`, I create a new database, `local.db`, locally and import `mydb.sql`. I edit `/var/www/html/sites/default/settings.php` $databases array and connect it to `local.db`.

I ensure all files permissions are correct by running

```
chown user:user -R /var/www/html/
chmod -R 755 /var/www/html/

```

I can then access my site using a browser and going to localhost, however the images are missing none of the links work.

Initially I thought the cause was that there are many instances in the database and my site code still containing filepaths with the subdomain `/drupal/` prefix, images for example:

```
src="/drupal/sites/default/files/inline-images..."

```

When I move the site to `localhost`, it should just be:

```
src="/sites/default/files/inline-images..."

```

To solve this, I did a find `/drupal/` and replace `/` in my database, reimported it and then used `grep -rl '/drupal/' ./ | xargs sed -i 's_/drupal/_/_g'` on `/var/www/html/`.

I thought this would have resolved the problem, however when I access `localhost`, the problem persists, images and links still contain the `/drupal/` prefix in their filepaths. I've read on a few migration guides that I should flush all caches on the drupal backend before moving (which I did) and also potentially flush the mysql cache using phpmyadmin, however I get an error `#1146 - Table 'mydb.cache' doesn't exist` when I try to execute the truncate commands.

Other guides mention `.htaccess`, which I copied over from `mysite.com/drupal`, admittedly I don't understand everything inside it deeply, but I can't find any code which is prefixing filepaths with `/drupal/`.

As a sanity check, I created `/var/www/html/drupal/` and copied my site and then everything works fine.

I don't understand, how can the filepaths remain the same when I have changed all instances in the database and site code? I think there is something easy I'm missing but I can't figure it out.

# Answer
Is this Drupal 7 or 8? Not sure that it matters, but take a look at around line 102 of your .htaccess file, should look like this:

```
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

```

The issue you describes sounds like the RewriteBase is incorrect. What does your .htaccess say?

Can you also tell me what your settings.php file has for the base URL value?

```
# $base_url = 'http://www.example.com';  // NO trailing slash!

```
> 0 votes

---
Tags: caching, migrations, .htaccess, configuration
---


title: Add new attributes for rendering?

text:
# Question
Title: Add new attributes for rendering?
In Drupal 8, how can you add new attributes to be rendered into the twig file?

I want to provide a region.html.twig that can be extended for subtheming.

So, I want the default to be:

```
{%
  set wrapper_classes = [
    'region',
    'region-' ~ region|clean_class,
    'container',
    'container--100',
  ]
%}

{%
  set outer_column_classes = [
    'container__col',
  ]
%}

{%
  set inner_column_classes = [
    'container__inner',
  ]
%}

<div{{ wrapper_attributes.addClass(wrapper_classes) }}>
  <div{{ outer_column_attributes.addClass(outer_column_classes) }}>
    <div{{ inner_column_attributes.addClass(inner_column_classes) }}>
      {% block content %}
        {{ content }}
      {% endblock %}
    </div>
  </div>
</div>

```

Simply making them arrays or strings as you would in D7 doesn't work - they never reach the twig template.

I noticed that Bartik uses the Attribute class to create new/empty Attributes. Is this kosher to do, exactly?

```
use Drupal\Core\Template\Attribute;

function mytheme_preprocess_region(&$variables) {
  $variables['wrapper_attributes'] = new Attribute();
  $variables['outer_column_attributes'] = new Attribute();
  $variables['inner_column_attributes'] = new Attribute();
}

```

When I do that, my new attributes appear and are rendered in the template. Is this even worth doing, or is it a lot more trouble to extend templates and manipulate them?

# Answer
> 3 votes
Your question is exactly about this issue:

> **Allow instantiating Attribute objects within Twig**
>
> **Problem/Motivation**
>
> Sometimes you have an array of attributes and it would be nice if you could addClass, removeClass, setAttribute, etc. rather than trying to do array manipulation.
>
> **Proposed resolution**
>
> Add a function to our Twig extension to allow creating an Attribute object from an array of attributes.

Issue: https://www.drupal.org/node/2616756

And the change record for **8.3.x**:

```
{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}
</div>

```

https://www.drupal.org/node/2818293

---
Tags: theming, 8
---


# Question
Title: Remove status messages from content output?
I want to move status messages into a region, but I can't seem to get it to stop being output as part of the main content output.

I tried this:

```
function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'content' && isset($variables['elements']['messages'])) {
    unset($variables['elements']['messages']);
    //$variables['elements']['messages']['#printed'] = FALSE;
  }
}

```

While that removed it from the array, it is still being rendered.

# Answer
> 5 votes
at /admin/structure/block, you can find the block "Status Messages" and move it to the "- None-" region, or another region of your choosing.

---
Tags: theming, 8
---


title: Including a sub-template in a theme

text:
# Question
Title: Including a sub-template in a theme
I've read numerous answers to similar questions here but I can't for the life of me work out how to do this seemingly simple thing. I simply want to include a Twig template (`theme_name/templates/system/footer.twig.html`) from another Twig template in my custom theme (`theme_name/templates/system/page.twig.html`).

In my `page.html.twig` I've tried all of the following (obviously with `theme_name` as the actual theme name):

```
{% include 'themes/custom/theme_name/templates/system/footer.html.twig' %}
{% include 'footer.html.twig' %}
{% include 'system/footer.html.twig' %}
{% include directory ~ '/system/footer.html.twig' %}
{% include '/' ~ directory ~ '/system/footer.html.twig' %}
{% include "@theme_name/system/footer.html.twig" %}
{% include "/var/www/html/web/themes/custom/theme_name/system/footer.html.twig" %}

```

Each of these produces the following error, with the template varying on the method I've tried:

> Twig\_Error\_Loader: Template "themes/custom/theme\_name/templates/footer.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/custom/theme\_name/templates/footer.html.twig" in the Drupal theme registry.) in "themes/custom/theme\_name/templates/homepage/page--front.html.twig" at line 177. in Twig\_Loader\_Chain-\>getCacheKey() (line 115 of /var/www/html/vendor/twig/twig/lib/Twig/Loader/Chain.php).

I've even tried using `hook_theme` in my `theme_name.theme` file to no avail.

```
<?php

function my_theme_theme() {
  return [
    'footer' => [
      'variables' => [],
    ],
  ];
}

```

# Answer
No need to set up hook\_theme, Just include like this:

```
{% include '@theme_name/system/footer.html.twig' with content %}

```

this will include that template in your main template. The variables will need to be available from the main template.

The "with" statement sets up the variables being sent to the sub-template. See http://twig.sensiolabs.org/doc/tags/include.html
> 3 votes

---
Tags: theming, 8
---


title: Creating Interactive Charts

text:
# Question
Title: Creating Interactive Charts
I'd like to create a page in D8 that allows my users to input some values. Once they've done that I'd like them to click a button that then creates two pie charts for them based on the values they input.

I see the Charts Module is not available for D8. Wondering if anyone here has suggestions for how best to accomplish this in D8 as of this writing?

# Answer
Have a look at the Easychart module, which has an official release for Drupal 8 (also for Drupal 7).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

* It defines a new content type (= *Chart*) used to add charts to your site.
* It creates a chart widget that can be used in your own content types.
* It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (*CKeditor* and *TinyMCE* are supported).
* It provides an intuitive interface to configure charts through the Easychart plugin.
* It supports pasting of CSV data to create charts from it.
* overheid.vlaanderen.be contains some real world examples of a Drupal website (not yet D8 though) with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

# Resources:
> 3 votes

# Answer
If you're comfortable in code, you may like to directly use the Google Chart API.

Example pie chart:

```
<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
          ['Mushrooms', 3],
          ['Onions', 1],
          ['Olives', 1],
          ['Zucchini', 1],
          ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

```
> 1 votes

---
Tags: 8, charts
---


# Question
Title: How to add a folder to my site with media or media browser?
My site uses media browser and media browser plus and when you upload a file you get a drop down of where to upload files. Where can i go to add a directory to this drop down list?

# Answer
Turns out a a list of vocabularies is being used to generate the drop down. In other words look at taxonomies and find out which one is being used and add a new term vocabulary
> 0 votes

---
Tags: 7, media
---


title: How are links rendered?

text:
# Question
Title: How are links rendered?
In Drupal 8, what code determines if a link is output as text, or an anchor tag with text?

I have entered a `route:<nolink>` item in the menu, but the output is this:

```
<span target="" data-highlight="0" data-icon="" title="Description of wris." data-drupal-link-system-path="<front>">wris</span>

```

Instead, I want an anchor tag with just # for the href.

Is there a reason why it only outputs a span? Where can I adjust this? Or, should I do this?

# Answer
TL:DR; you need to overwrite the `link_generator` to change this behavior.

Drupal 8 uses the link generator for this. You can take a look at

`Drupal\Core\Utility\LinkGenerator::generate` if you want to know the code behind it all.

The key part is this:

```
elseif ($url->isRouted() && $url->getRouteName() === '<nolink>') {
  $generated_link = new GeneratedNoLink();
  unset($attributes['href']);
}

```

If you take a look at `GeneratedNoLink` you will see

```
/**
 * This class holds a <span> generated from the <nolink> route.
 */
class GeneratedNoLink extends GeneratedLink {

  /**
   * {@inheritdoc}
   */
  const TAG = 'span';

}

```

So you need to implement your own no link class and not unset the href and everything should be fine. Doing so you more or less need to copy most of the logic in Drupal\Core\Utility\LinkGenerator::generate to determine when no link should be used.

## Note

Links/urls can be generated in various ways, some use `link_generator`, some use `url_generator`, some use the `link` RenderElement. In your case it looks like the link\_generator is used, but that could be changed by custom theme/module.
> 6 votes

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


# Question
Title: Custom template for view with block display in a page
I created a template `views_block__applications_block_1.twig` for a block used on one of my pages. The block is based on a block view (unformatted list). Under blocks, the machine-readable name is `views_block__applications_block_1`. After searching around, I found that `views_block__applications_block_1.twig` should be the right template name. But no matter what I try, it doesn't seem to be working, all changes to the file are invisible. Can anybody point me in the right direction?

File content:

```
{#
/**
 * @file
 * Theme override to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 * - view: The view object.
 * - default_row_class: A flag indicating whether default classes should be
 *   used on rows.
 *
 * @see template_preprocess_views_view_unformatted()
 */
#}
<h1>TEST<h1>
{% if title %}
  <h3>{{ title }} - TEST</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

```

# Answer
The correct naming is:

`views-view--applications--block-1.html.twig`

Also, the custom template should be based on the `views-view.html.twig` template, rather than on the `views-view-unformatted.html.twig` template.

The following are the possible template names sorted by precedence:

```
[base template name]--[view machine name]--[view display id].html.twig

[base template name]--[view machine name]--[view display type].html.twig

[base template name]--[view display type].html.twig

[base template name]--[view machine name].html.twig

[base template name].html.twig

```

(Source: http://redcrackle.com/blog/drupal-8/theme-views-templates)
> 4 votes

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


# Question
Title: Is there a way to limit where a block displays based on a query in the URL?
I have a page with a pager that displays a certain block at the top. I only want that block to be display on the first page but right now it display when I go to Page 2, 3, etc.

# Answer
You can implement a condition plugin that does just that and then configure your block to use that condition, we did something similar once:

```
/**
 * Condition on the page query param.
 *
 * @Condition(
 *   id = "yourproject__first_page",
 *   label = @Translation("First page (by url query param)")
 * )
 */
class FirstPage extends ConditionPluginBase {

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    $match = !\Drupal::request()->query->get('page');
    return $this->configuration['negate'] ? !$match : $match;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    return $this->t($this->configuration['negate'] ? 'The %param parameter is not %value' : 'The %param parameter is %value or empty', ['%param' => 'page', '%value' => 0]);
  }

}

```
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: How can I use CKEditor for teaser text on a long form text field?
In Drupal 8, the teaser text for a long form text field (specifically, text of type "long, formatted, with summary") does not have a CKEditor wrapper around it:

How can CKEditor be added to this textarea?

# Answer
> 3 votes
This is core limitation right now.

I would recommend that if you want an editor on a teaser/summary field, you simply create a separate field, that also gives you options like having a separate text format for it.

The text long with summary field type might eventually get removed in Drupal 9 or so.

---
Tags: 8, wysiwyg
---


# Question
Title: Display Suite View Only Showing Default Display
Custom displays are no longer showing up on the Front-End; instead only the default view is showing. The following message displays next to the template section on the display page (structure/types/manage/contenttype/display/display\_name) "This layout is defined in code: disable layout." When I click "Disable Layout" link it takes me to a new page and displays: "This operation is not possible." What does this error mean? What is the cause? How can it be corrected?

It is not clear whether this error is the reason the display is not showing on the frontend. I have tried accessing the display several different ways include through a view, shows the default (view-mode-full) content display, not the one it is set to. Though the default view is picking up my assigned custom classes.

It is as if Display Suite will not display more than one display on front-end. I can customize and edit "full content" display but this displays on front-end regardless.

# Answer
> 3 votes
It was caused by a conflict with View Role Per Node Module Even though I did not have any node views assigned based on role, it still seemed to be interfering with the Display Suite behavior.

---
Tags: display-suite
---


# Question
Title: Limit the number of registrations by field
I am using Entityforms to take registrations for events. There is limited space and the form allows users to select which event they would prefer to attend.

Is there any way (rule, etc.) to disable or remove certain dates once the limit has been reached?

# Answer
> 1 votes
You can disable specific dates in date popup by implementing some custom code as per shown in jQuery UI DatePicker: Disable Specified Days. To work with jQuery in Drupal you can check the date popup alter example here.

OR you can try Work Calendar Module with Date Restrictions Module (both are in dev and not suggested to use on Production unless working without any error).

---
Tags: 7, rules
---


# Question
Title: Register for an event and create an account on one page
It's been a while since I've used Drupal and I now need to implement the following but can't seem to determine how. I have a site that's set up for event registration and need visitors to be able to sign up for an account as part of that one-page process. They'll then need to be able to edit their registration details and such but that part is in hand. What I'm not seeing is a way to combine account creation with the submission of non-profile form data all in one go.

Any pointers would be greatly appreciated.

# Answer
Based on this existing answer, I could find the Inline Registration module. It lets you register while creating a node at the same time (one form). Since this is node-specific, this may allow a "event registration" content type to be defined then assigned to the user registration form.
> 0 votes

---
Tags: forms, users
---


# Question
Title: How can I display a custom field for node reference in another content type?
I have a node with custom fields that I would like to pull into a different content type. I do not want to display the full node, only one or two fields. Currently with Node Reference I only have options to display the title, ID, or the full node.

My content type has the option to list unlimited nodes of this type, so the end result could possibly have multiple node ids.

I think the best way to do this would be with a custom ph formatter but I am a little lost on how to make it work.

# Answer
You can create a view for the entity reference field with the fields whichever you want to list.

Below is the setting for the entity reference to select a view

In Field Setting--\> Entity selection--\>Mode --\>Select Views and assign the same to "View used to select the entities \*"

Here is the link to create a view of entity reference type link,
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Pass multiple sets of variables to theme function
If I want to loop through multiple sets of theme variables in my custom theme template, how do I define them in my theme function and pass them to hook\_theme?

For instance, in my case, I'm generating an email body to send via drupal\_mail(), and the body will contain a list of spa openings. I want to iterate through each set in the mail (the same way views templates iterate over views rows). I have my theme function defined like so:

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_module_mail' => array(
      'variables' => array(
        'service_name' => NULL,
        'time' => NULL,
        'therapist' => NULL,
        'booking_link' => NULL,
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

```

and I can pass one set of variables to the template just fine like so:

```
foreach ($available_openings[$tid['tid']] as $mail_opening) {
  $variables = $mail_opening;
  $body = theme('my_module_mail', $variables);
}

```

but what I want to do is pass an array of the variables array so that in my template can do something like this:

```
<?php foreach ($openings as $id => $opening): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $opening; ?>
  </div>
<?php endforeach; ?>

```

What do I need to change to do that?

Thanks.

# Answer
> 0 votes
And, the general rule of "post a question and that helps you figure it out yourself" applies here yet again.

All I did was modify my theme hook like so:

```
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my-module-mail' => array(
      'variables' => array(
        'openings' => array(
          'service_name' => NULL,
          'time' => NULL,
          'therapist' => NULL,
          'booking_link' => NULL,
        ),
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

```

and fill my $variables array like so:

```
  // Loop through all openings for this category.
    foreach ($available_openings[$tid['tid']] as $mail_opening) {
      $variables['openings'][] = $mail_opening;
    }
    $body = theme('my_module_mail', $variables);
    // Define mail parameters.
    $params = array(
      'subject' => t('Your Available Openings'),
      'body' => $body,
    );
    // Send the mail.
    drupal_mail('my-module-mail', 'featured_openings', $entity->mail, language_default(), $params);

```

and it works like a charm.

---
Tags: 7, theming
---


# Question
Title: How to create a fixed width image style for all landscape and portrait images?
I have an image style: Scale 580x580px.

* When I upload a *landscape* image it gets a width of 580px.
* When I upload e.g a *portrait* image with **809 (width) x 1100px (height)** the width of the image (after image style is applied) on the page is **427 x 580px.**

How do I manage the width is always 580px? So for all uploaded landscape and portrait images?

# Answer
> 1 votes
`Scale` only scales the image so it looks proportionate. It will go with either the height 580px or width 580px, which ever is closer.

If you want your image to be exactly 580px *x* 580px you could use `Resize` but you will see your image will look stretched.

The only other option that will give you the exact 580px *x* 580px is `Scale and Crop`

If you are afraid that something important will get cut off, you can use this awesome module:

**Focal Point** by DA's own bleen

> Focal Point allows you to specify the portion of an image that is most important. This information can be used when the image is cropped or cropped and scaled so that you don't, for example, end up with an image that cuts off the subject's head.

Then use `Focal Point Scale and Crop` as your image style effect.

---
Tags: media
---


title: User accounts for customers

text:
# Question
Title: User accounts for customers
How would I go about having a feature for customers to create their own accounts on my Drupal? Will I need PHPMyAdmin and some SQL?

# Answer
> 1 votes
This is a setting that's built into the core of Drupal. On D7/D8 the **Who can register accounts?** (**Public registrations** in D6) setting adjusts who can create accounts on your Drupal installation.

* *Administrators only*
* *Visitors*
* *Visitors, but administrator approval is required*

The settings form can be found under **/admin/config/people/accounts** (**/admin/user/settings** in D6).

# Answer
> 0 votes
For D7

You can look Profile 2 module and Profile2 Registration Path module.

> The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module by default.
>
> Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.
>
> Optionally, profile forms are shown during user account registration. Similar to the deprecated core profile module, fields may be configured to be private - thus visible only to the profile owner and administrators.
>
> By default the UI behaves similar to the deprecated core profile module, thus showing each profile type in each own tab below user//edit. Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".

For D8

You can look Profile module.

> Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.
>
> Optionally, profile forms are shown during user account registration. Fields may be configured to be private - thus visible only to the profile owner and administrators.
>
> Profile types are displayed on the user view page, and can be configured through “Manage Display” on account settings.

---
Tags: users
---


# Question
Title: Implementing different user registration
I have looked elsewhere for the problem I faced, but I cannot get any clue on solving the problem. Consider, based on the type of user, I want to implement different user registration page. In current D8 version, I could add fields at admin/config/people/accounts/fields. Let's say a teacher has fields like *Fname*, *Lname*, *ID*, *Contact*, and *School Name* whereas student has fields like *Fname*, *Lname*, *Course*, and *Age*.

If I add those mentioned fields in the user table, I won't be able to differentiate whether that is teacher or student. In that case, how do I make two different registrations, one for teacher another for student, and store them as Drupal users so that I can apply functions such as `\Drupal::currentUser->isAuthenticated()` on them?

# Answer
I would argue that you only need one type of user, but want multiple types of profiles. It sounds like you are looking for the profile module. From the module description:

> Why use profiles instead of user account fields?
>
> * With profile, user account settings and user profiles are conceptually different things, e.g. with the “Profile” module enabled users get two separate menu links “My account” and “My profile”.
> * Profile allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
> * Profile supports private profile fields, which are only shown to the user owning the profile and to administrators.

It also supports multiple registration forms to allow users to register and create their profile in one form.

https://www.drupal.org/project/profile
> 6 votes

# Answer
In addition to the Profile module, there's another contributed module written for this: https://www.drupal.org/project/multiple\_registration

If you don't want to rely on a module, you can use the Form API to create your own registration form. Or you can use hook\_form\_alter to alter the registration form beforehand. You could use a query string to determine which kind of form it is, such as /user/register?type=teacher or /user/register?type=student.
> 3 votes

# Answer
In D8 you have the new feature *form modes*.

When you have added the custom user fields go to "Manage form display". At the bottom of the page enable the form mode "Register". Then you get a new tab at the top of the page and you are able to choose the fields for the custom register form.

If you install the module Field Group, you can group the two sets of fields for teachers and students in tabs.
> 3 votes

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


# Question
Title: How to apply or assign custom view mode to user display?
I am using Display Suites. I have created a custom view mode and have made it available to the user display per Display Suite documentation, but I cannot figure out how to apply the custom view mode to the user display. It always shows in the default view mode.

If I were editing a node, there would be a vertical tab called Display Settings that would have a field for selecting the view mode to use. When editing an existing user profile, there is no Display Settings tab.

---

In various Drupal issues queues, specifically Display Suites, Panels and Profile 2, other users have asked essentially this same question: How do I assign a custom view mode to the user profile display?

Is the Drupal core responsible for user data and display? Perhaps the problem lies there instead of with whatever module.

# Answer
> 1 votes
The question is too old, but for those who are still looking similar functionality. We can implement hook\_entity\_view\_mode\_alter in our custom module and change the rendered view mode dynamically. Check sample below:

```
/**
 * Implements hook_entity_view_mode_alter().
 */
function MODULE_NAME_entity_view_mode_alter(&$view_mode, $context) {
  // For nodes, change the view mode when in full display mode.
  // Add/Remove any condition based on requirement.
  if ($context['entity_type'] == 'node' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}

```

---
Tags: users, display-suite, entities
---


# Question
Title: How do I modify the layout or look-and-feel of a specific node?
How do I modify the layout or look-and-feel of a specific node, for example the one whose ID is 230?

Which template file should I create to only change the output for a single node?

I had done it before in Drupal 6. I don't know how to achieve it in Drupal 7.

# Answer
In Drupal 6 the template file should be like `node-<nodeid>.tpl.php`

In Drupal 7 the template file should be like `node--<nodeid>.tpl.php`

Difference between these two is **double hypen**.
> 2 votes

# Answer
One of the things you can do to help with this is to enable Theme Debug mode, see here:

https://www.drupal.org/node/223440#theme-debug

This will tell you what templates are currently being used, and will provide suggestions for what templates to use, when you inspect the source of your node page (the suggestions are in HTML comments, so make sure they're enabled in your inspector).

It also details how to create your own custom template suggestions, the patterns of which is detailed here:

https://www.drupal.org/node/1089656

Make sure you place the templates inside your theme directory in order for the theme to pick them up.
> 2 votes

---
Tags: 7, nodes
---


title: display custom user fields with twig?

text:
# Question
Title: display custom user fields with twig?
I added for users a couple of fields : *field\_telephonenumber* and *field\_company*

how can i display them in user.html.twig or maybe page.html.twig

# Answer
> 3 votes
You can configure which fields are displayed in the view mode `compact`:

```
admin/config/people/accounts/display/compact

```

Then you can in twig display all fields with

```
{{ content }}

```

or single fields with

```
{{ content.field_example }}

```

To put a user in a page template you can use Twig Tweak:

```
{{ drupal_entity('user', 1, 'compact')

```

The third parameter is the view mode and you can use theme hook suggestions to catch this with your custom user twig to make adjustments of the user fields.

---
Tags: theming, 8
---


# Question
Title: Update a content type field via db not working D8
I have a content type field with **machine name** **`field_p_frontip`** and for that i have a table **`node__field_p_frontip`** and in that there is field value like **`field_p_frontip_value`** . Eventhough i manually inserted a value in to that field its not taking effect in the front end . I updated the value in the **`node_revision__field_p_frontip`** table too and cleared the **cache** .Why its not working ,any idea ?

I done this because i done via `hook_form_alter` and its not taking effect .

`node__field_p_frontip` table structre :

```
+-----------------------+------------------+------+-----+---------+-------+
| Field                 | Type             | Null | Key | Default | Extra |
+-----------------------+------------------+------+-----+---------+-------+
| bundle                | varchar(128)     | NO   | MUL |         |       |
| deleted               | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id             | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id           | int(10) unsigned | NO   | MUL | NULL    |       |
| langcode              | varchar(32)      | NO   | PRI |         |       |
| delta                 | int(10) unsigned | NO   | PRI | NULL    |       |
| field_p_frontip_value | longtext         | NO   |     | NULL    |       |
+-----------------------+------------------+------+-----+---------+-------+

```

and `node_revision__field_p_frontip` table structure :

```
+-----------------------+------------------+------+-----+---------+-------+
| Field                 | Type             | Null | Key | Default | Extra |
+-----------------------+------------------+------+-----+---------+-------+
| bundle                | varchar(128)     | NO   | MUL |         |       |
| deleted               | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id             | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id           | int(10) unsigned | NO   | PRI | NULL    |       |
| langcode              | varchar(32)      | NO   | PRI |         |       |
| delta                 | int(10) unsigned | NO   | PRI | NULL    |       |
| field_p_frontip_value | longtext         | NO   |     | NULL    |       |
+-----------------------+------------------+------+-----+---------+-------+

```

**From Berdir's comment**

---

I was trying to set the value of the field '`field_p_frontip`' in form\_alter as follows , but both didnt worked .

`$form['field_p_frontip']["en"][0]['#default_value']['value'] ='192.168.1.100'; $form['field_p_frontip']['#default_value'] = '192.168.1.100';`

# Answer
To update the value of a field for a node, you need to.

1. Load it
2. Modify it
3. Save it

In code it looks like this:

```
$node = \Drupal\node\Entity\Node::load($nid);
if ($node) {
  $node->field_p_frontip = '192.168.1.100';
  $node->save();
}

```

How you set the value of the field, depends on the field itself. Most fields are simple, and can be set with a scalar value. If field has multiple values or stores more complex data (like the address field), you need to account for this complexity. Usually this is done with arrays.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Personal contact form button if available
How can I add a button to the user twig template that links to their personal contact form, but only shows if that user has the form available, and the person viewing the page has permissions to use it?

# Answer
> 1 votes
This was the solution I came up with:

```
/**
 * Implements hook_preprocess_user().
 */
function MYTHEME_preprocess_user(&$variables)
{
    $account = $variables['elements']['#user'];
    if ($account->getEmail() != '') {
        $contactUrl = Url::fromRoute('entity.user.contact_form', ['user' => $account->id()]);
        if ($contactUrl->access()) {
            $contactLink = Link::fromTextAndUrl('Contact', $contactUrl);
            $variables['contact_btn'] = $contactLink->toRenderable();
            $variables['contact_btn']['#attributes'] = array('class' => array('btn', 'btn-primary', 'btn-contact-user'));
        }
    }
}

```

---
Tags: 8
---


title: Theming multi-value fields in Views

text:
# Question
Title: Theming multi-value fields in Views
I added the `field_tags` to my view.

Now I want to add a the tag name as a class name, so I can colour each tag differently.

ex:

```
<div class="tag1">tag1</div>
<div class="tag2">tag2</div>
<div class="tag3">tag3</div>

```

Unfortunately, unchecking display all values in same row is not an option for me since I need to limit the view to 4 results.

Therefore, somehow I need to be able to loop through them and attach each of them the tag name as a class name.

How can I achieve this?

# Answer
The only work-around solution that I can think of would be to:

Create a separate view for the tags.

Then there I will be able to uncheck display all values in same row.

Re-write field to `<div class="{{ field_tags }}"> {{ field_tags }} </div>`

Then use View Fields View to insert the Tags view as a field in my other view and pass the nid as contextual filter.

Probably not the best solution, so if anyone has a better one I'd love to hear it.
> 1 votes

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


# Question
Title: Add bootstrap button to rewrite output views
I have a view with a table, the last column is a link but should be a button. So in the last field i enable rewrite output and add this code

```
<button type="button" class="btn btn-default">
      [clone_node]
</button>

```

I am using the bootstrap theme. But views is filtering out the button code. What is the fasted way to change the link into a button?

# Answer
It might not be what you need, but in Bootstrap you can create buttons using the `<a>` anchor, which will not be filtered out by Views.

```
  <a class="btn btn-default" href="#">
        [clone_node]
  </a>

```
> 3 votes

---
Tags: views, theming
---


# Question
Title: Show calculated value at the bottom of every node for a specific content type
I am beginner in Drupal. I am using different content types and views for my project. Here for specific content type I have created number of fields. Two of the fields are integer field type.

I want to calculate those two fields and show the calculated values at the bottom of every single node for a specific content type.

How can I achieve it? using views or by any other way.

# Answer
**Computed Field** module will do for you.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

if you need this through views, you can check this link there are answers which might help you.

also this module will help you,

**Views Custom Field**

> Now that the Views module has incorporated the rownumber and markup fields, only the PHP field is left for this module. I started a new project called Views PHP. It also includes support for PHP filters and sorts.
> 0 votes

# Answer
A not commonly known/used alternative to the Computed Field module (suggested in the previous answer), is the Math Field module. Some more details about this module (from its project page):

> The Math Field module defines a new field type to dynamically calculate values on entity forms. **This is an alternative to Computed Field that does not require the use of PHP Filter.**
>
> Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

**Bonus**: you would not need the "PHP filter" (as is the case for the Computed Field module), IMO only that should be a valid reason to investigate this alternative ...
> 0 votes

---
Tags: views
---


title: How to interpret kint output

text:
# Question
Title: How to interpret kint output
I have installed devel kint module on my drupal 8. Everything is fine with the module.

But my problem is how should I interpret the output of kint correctly. Especially when I want to render field within file entity.

**Here is the scenario:**

1. I have a form created with YAMLForm in my front. In that form user can upload image.
2. User submit the form.
3. When I debug data with kint, I can see the url of the image, but I am unnable to display it thru .

Please find below a screenshot of the kint output

**I have tryied with the following but no chance :**

```
{{ file_url(data.picture['#value']['#file'].entity['#values'].uri['x-default']) }}
{{ file_url(data.picture.0['#item'].entity.uri.value) }}
{{ file_url(data.picture.entity.fileuri) }}

```

I've Googled for hours but couldn't find any clues.

Thanks in advance for your help.

# Answer
> 2 votes
You can't load protected values. So kint is not much help here.

But you can try this, load directly the uri value:

```
{{ file_url(data.picture['#value']['#file'].uri.value) }}

```

---
Tags: theming, 8, entities
---


# Question
Title: Page not Found error when Views block containing node titles links placed on a specific content type
I have a content type News whose nodes are used to generate two blocks using views "Most read news articles" and "Latest news articles". These blocks are printed through `node--news.tpl.php` tpl file when news is displayed in full view mode.

Problem is that that all the title links in blocks lead to "Page not found" due to URLs overridden as http://example.com/news/node/49610 while actually they should be like http://example.com/node/49610

When checking through firebug I can see that links are correct:

`

Popular product taken down

`

All links work perfectly When same blocks are placed on the `<front>`.

Any help to resolve this is highly appreciated.

# Answer
That link isn't correct. It should be relative to your web root ("/node/49610") and not the current page ("node/49610").
> 0 votes

---
Tags: views, theming, javascript, navigation
---


# Question
Title: EntityFieldQuery fieldCondition Date not working as expected
No matter what i try i cant get EntityFieldQuery to work i have a date and i need to check if it is between the start date and end date of a date field that is set to unlimited values.. it should be at least between any one.. here is what i got.. can anybody help me?

UPDATE 10/26/2016: So from what I found doing some more googling to do what I want I need to use delta\_group so I added it to the code below but it doesn't seem to be working. Anybody have any idea what I'm doing wrong?

```
    $myDate = date('Y-m-d H:i:s');
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'caregiver_db')
          ->propertyCondition('status', 1)
          ->fieldCondition('field_available_dates', 'value', $myDate, '>=', 0)
          ->fieldCondition('field_available_dates', 'value2', $myDate, '<=', 0);

    $results = $query->execute();

```

# Answer
> 1 votes
So it looks like the final issue I was having was the operators I was using. Had to go \<= on value and \>= value2. I had it the other way around before. Here is the code that worked.

```
$myDate = date('Y-m-d H:i:s');
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'caregiver_db')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_available_dates', 'value', $myDate, '<=', 0)
      ->fieldCondition('field_available_dates', 'value2', $myDate, '>=', 0);

$results = $query->execute();

```

# Answer
> 0 votes
You could also use the ***BETWEEN*** operator, like:

```
$fromDate = date('Y-m-d') . ' 00:00:00';
$toDate = date('Y-m-d') . ' 23:59:59';
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'caregiver_db')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_available_dates', 'value', array($fromDate, $toDate), 'BETWEEN');
$results = $query->execute();

```

Also just go for the value if it's not a start/enddate field.

---
Tags: entities
---


# Question
Title: Drupal 8 ajax callback in form_alter only works on a specific server configuration
I'm writing because I have spent the last few days investigating what seems to be a real conundrum and I'm pretty much at my wit's end.

I have a very simple Drupal 8 form\_alter which creates a set of two dropdowns during user registration. user picks an option from the first one, and then the second is populated based on that first choice. both dropdowns' options are pulled from an external database.

***problem is:*** *the ajax callback runs smoothly on my webhost, but not on the client's.* instead, I get the following error on Firebug:

```
AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /user/register?ajax_form=1
StatusText: OK
ResponseText:

Drupal.AjaxError.prototype = new Error();
-----------------------------^

```

and here's the code:

**databases configuration**

```
$databases['default']['default'] = array (
  'database' => 'mydatabase',
  'username' => 'mydatabase_username',
  'password' => 'mydatabase_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
$databases['external']['default'] = array (
  'database' => 'myexternaldatabase',
  'username' => 'myexternaldatabase_username',
  'password' => 'myexternaldatabase_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

```

**mymodule.info.yml**

```
name: My Module
type: module
description: 'User registration form customisation'
package: mypackage
core: 8.x

```

**mymodule.module**

```
<?php

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id == 'user_register_form') {
    // Switch to external database
    \Drupal\Core\Database\Database::setActiveConnection('external');

    $db = \Drupal\Core\Database\Database::getConnection();

    $query = $db->select('table1', 't1');
    $query->fields('t1', array('field1', 'field2'));
    $query->orderBy('field1');
    $table1 = $query->execute()->fetchAllKeyed();

    // Switch back to default database
    \Drupal\Core\Database\Database::setActiveConnection();

    $options = array(
      '0' => t('Choose a Value'),
    );

    $options = $options + $table1;

    $form['field_table1'] = array(
      '#type' => 'select',
      '#title' => t('Select from Table 1'),
      '#options' => $options,
      '#ajax' => array(
        'callback' => '_mymodule_dropdown_callback',
        'wrapper' => 'mymodule-dropdown-2',
        'event' => 'change',
        'progress' => array(
          'effect' => 'fade',
          'message' => t('Loading...'),
        ),
      ),
    );

    $form['field_table2'] = array(
      '#type' => 'select',
      '#title' => t('Select from Table 2'),
      '#prefix' => '<div id="mymodule-dropdown-2">',
      '#suffix' => '</div>',
      '#options' => array(0 => 'Choose from Table 1 first'),
      '#default_value' => '0',
    );

  }
}

function _mymodule_dropdown_callback(array $form, \Drupal\Core\Form\FormStateInterface &$form_state) {

  $values = $form_state->getValues();
  $field1 = $values['field_table1'];

  // Switch to external database
  \Drupal\Core\Database\Database::setActiveConnection('external');

  $db = \Drupal\Core\Database\Database::getConnection();

  $query = $db->select('table2', 't2');
  $query->fields(
    't2',
    array(
      'field1',
      'field2',
      'field3',
    )
  );
  $query->condition('field1', $field1);
  $query->orderBy('field2');
  $table2 = $query->execute()->fetchAllKeyed(1, 2);

  // Switch back to default database
  \Drupal\Core\Database\Database::setActiveConnection();

  unset($form['field_table2']);

  $form['field_table2'] = array(
    '#type' => 'select',
    '#title' => t('Select from Table 2'),
    '#prefix' => '<div id="mymodule-dropdown-2">',
    '#suffix' => '</div>',
    '#default_value' => '0',
  );

  $default = array('0' => t('Choose a Value'));

  $form['field_table2']['#options'] = $default + $table2;
  return $form['field_table2'];

}

```

from what I could gather, the problem is a difference in server configuration between my webhost and the client's, but I have no idea what to look for. I scoured the web but came up empty.

if anyone would be willing to point me to the right direction, or if you need more clarification on the servers' configurations, please let me know (I felt it would be overkill to simply dump a lot of server configuration here).

any help is greatly appreciated. thank you in advance.

kind regards, Luciano

# Answer
well, as it turns out, there was a problem with AJAX in Core prior to version 8.2. here's an example from the (awesome) support at Drupalize.me:

https://www.drupal.org/node/2619878

as for the reason why it was working on my server configuration, it's (probably) because they have upgraded PHP in a rather odd fashion (applying patches for example) and that caused some functionality to "work" where it wasn't, er, supposed to.

it also helped that I looked at the error logs and meddled with the code in core, but you know -- you're not supposed to hack core.

anyway it seems like this issue has been fixed as of Drupal 8.2, so I'm closing this ticket for now.
> 0 votes

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


# Question
Title: Is there something equivalent to template_preprocess_search_results()?
I just realized that template\_preprocess\_search\_results() function has been left out in Drupal 8 for some reasons, although `template_preprocess_search_result()` (for single results) is still there.

I need to be able to manipulate the search results prior to rendering as I would with `template_preprocess_search_results()` in Drupal 7.

# Answer
The method that builds the search results is `SearchController::view()`, which contains the following code.

```
  $results = array();
  if ($request->query->has('keys')) {
    if ($plugin->isSearchExecutable()) {
      // Log the search.
      if ($this->config('search.settings')->get('logging')) {
        $this->logger->notice('Searched %type for %keys.', array('%keys' => $keys, '%type' => $entity->label()));
      }

      // Collect the search results.
      $results = $plugin->buildResults();
    }
    else {
      // The search not being executable means that no keywords or other
      // conditions were entered.
      drupal_set_message($this->t('Please enter some keywords.'), 'error');
    }
  }

  if (count($results)) {
    $build['search_results_title'] = array(
      '#markup' => '<h2>' . $this->t('Search results') . '</h2>',
    );
  }

  $build['search_results'] = array(
    '#theme' => array('item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'),
    '#items' => $results,
    '#empty' => array(
      '#markup' => '<h3>' . $this->t('Your search yielded no results.') . '</h3>',
    ),
    '#list_type' => 'ol',
    '#context' => array(
      'plugin' => $plugin->getPluginId(),
    ),
  );

```

So, you can use `template_preprocess_item_list(&$variables)`, checking that `$variables['#context']['plugin']` is set. (I am not sure about using `template_preprocess_item_list__search_results(&$variables)`, since I have never tried using such preprocess function.)

The `$plugin->buildResults()` method called from `SearchController::view()` just builds the results as array of items themed with search\_result.

```
  $results = $this->execute();

  $built = array();
  foreach ($results as $result) {
    $built[] = array(
      '#theme' => 'search_result',
      '#result' => $result,
      '#plugin_id' => $this->getPluginId(),
    );
  }

```
> 2 votes

# Answer
You can create a new module and inside your YOUR\_MODULE.module file put this code:

```
function YOUR_MODULE_preprocess_item_list__search_results(&$variables) {
  //to use dpm() you nedd the devel module
  dpm($variables['items']);
}

```

Install your module and you will see the output in the search result
> 3 votes

---
Tags: 8, search, theming
---


# Question
Title: How to create a rule to send an email to a list of selected email addresses?
I have a Content Type Named `XYZ`. This content Type has a field named `Email Addresses`, which contains the List of Email address of the users in the Portal.

Now when the user adds the Content of XYZ and selects the desired Email Address from the Email Addresses List, the email should be sent to all the selected Email Addresses.

I know the Rules module should be used to perform this, but guide me the steps, how to make such rule?

# Answer
Assuming this question is about D7, you can use the Rules module to create a rule like so (in Rules export format):

```
{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

```

Some more details about the above rule:

* **Rules Event**: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
* **Rules Action**: a "loop" for all selected values of a multi value select list (contain the eMail IDs), with machine name `field_email_addresses` (adapt the machine name to fit your needs). For each item (= `current_email_id`), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.

After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with `drupal_message`).

**Video tutorial**: have a look at the List and loops video which show a similar scenario.
> 1 votes

---
Tags: rules, emails
---


# Question
Title: Drupal 8, "view ui query" to drupal code query api ?
When we build a view from the view ui, we can show what is the "hard query" is executed, example :

```
SELECT node__field_house_count_added.field_house_count_added_value AS node__field_house_count_added_field_house_count_added_value, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {node__field_house_tags} node__field_house_tags_value_0 ON node_field_data.nid = node__field_house_tags_value_0.entity_id AND node__field_house_tags_value_0.field_house_tags_target_id = '4'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_1 ON node_field_data.nid = node__field_house_tags_value_1.entity_id AND node__field_house_tags_value_1.field_house_tags_target_id = '5'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_2 ON node_field_data.nid = node__field_house_tags_value_2.entity_id AND node__field_house_tags_value_2.field_house_tags_target_id = '16'
INNER JOIN {node__field_house_tags} node__field_house_tags_value_3 ON node_field_data.nid = node__field_house_tags_value_3.entity_id AND node__field_house_tags_value_3.field_house_tags_target_id = '6'
LEFT JOIN {node__field_house_count_added} node__field_house_count_added ON node_field_data.nid = node__field_house_count_added.entity_id AND (node__field_house_count_added.deleted = '0' AND node__field_house_count_added.langcode = node_field_data.langcode)
WHERE ((( (node__field_house_tags_value_0.field_house_tags_target_id = '4') AND (node__field_house_tags_value_1.field_house_tags_target_id = '5') AND (node__field_house_tags_value_2.field_house_tags_target_id = '16') AND (node__field_house_tags_value_3.field_house_tags_target_id = '6') )))
ORDER BY node__field_house_count_added_field_house_count_added_value DESC
LIMIT 2 OFFSET 0

```

Is there a way for get quickly the query, but in the query api format ? Like :

```
$query = db_select('users', 'u')
  ->condition('u.uid', 0, '<>')
  ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
  ->range(0, 50);

```

Thanks :)

# Answer
No, there is not.

You're also not supposed to write a query directly against entity or field tables yourself. Use the entity query API instead:

https://www.sitepoint.com/drupal-8-version-entityfieldquery/

```
$uids = \Drupal::entityQuery('user')
  ->condition('uid', 0, '<>',
  ->range(0, 50)
  ->execute();

```
> 0 votes

---
Tags: views, 8, database
---


# Question
Title: Composer is git cloning modules instead of download them?
My composer file looks as follows:

```
{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/drupal-extension": "~3.0",
        "drupal/search_api": "1.x-dev",
        "drupal/search_api_view_modes": "1.x-dev",
        "drupal/paragraphs": "^1.0",
        "drupal/features": "3.x-dev",
        "drupal/robotstxt": "^1.0",
        "drupal/search_api_solr": "1.x-dev",
        "drupal/metatag": "1.x-dev",
        "drupal/pathauto": "1.x-dev",
        "drupal/acquia_connector": "^1.4",
        "drupal/sharethis": "2.x-dev",
        "drupal/field_group": "1.x-dev",
        "drupal/ckwordcount": "^1.0",
        "drupal/menu_link_attributes": "1.x-dev",
        "drupal/yaml_editor": "1.x-dev",
        "drupal/devel": "1.x-dev",
        "drupal/menu_block": "^1.4"
    },
    "replace": {
        "drupal/core": "~8.2"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url":  "https://packages.drupal.org/8"
        }
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        },
        "installer-paths": {
            "modules/contrib/{$name}": ["type:drupal-module"],
            "themes/contrib/{$name}": ["type:drupal-theme"]
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    }
}

```

For all the modules that were downloaded as a 'dev' status, they appear to have been git cloned. Therefore, the changes aren't recognized or saved to my git tree, and don't push. These modules did not make it to my remote repository, and did not show up on the remote website.

I am not sure how this occurs, but for time being, I had to:

* cd into module directory
* rm -rf .git folder
* git rm --cached modulename
* git add modulename
* git commit -m "Adding module"
* git push

The module(s) then make it into my project repository and make it up to the remote server.

What is the correct workflow here? I am not running any build process or tool remotely but want to retain my project build with composer tracking the modules and themes I have installed.

# Answer
> 7 votes
Yes, that's what it does when you specify a dev version.

The recommended way to handle a composer project is to *not* commit composer managed code. all you commit is the composer.lock file and it is guaranteed that a composer install with install the exacty same versions, every time.

See https://getcomposer.org/doc/faqs/should-i-commit-the-dependencies-in-my-vendor-directory.md for more information on that and ways to work around it if you really want to.

Have a look at https://github.com/drupal-composer/drupal-project, it gives you a project environment that is preconfigured using the recommended git ignore settings and follows modern standard by keeping the vendor folder and other non-publich files out of the public web folder.

Update: One of the reasons why git does it, is that drupal.org AFAIK does not give you the possibly to download a specific dev snapshot, only the latest. And one of the main features of composer is to build the lock file and get the very same commit every time you run composer install, until you run composer update again.

---
Tags: 8, composer
---


# Question
Title: Proper way to create image field in a content entity
My site allows users to upload images and add title and description to it. So I make a new class which extends `ContentEntityBase`. In its `baseFieldDefinitions()` method, I put an image field beside title and description fields:

```
$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setRequired(TRUE);

```

I expect to see a file/image upload control in the add/edit form, but I don't see it. I see only the title and description textboxes.

I tried to find "*create('image')*" in all Drupal source code but didn't see any examples. So I don't know if creating an image field like this is the proper way or not?

# Answer
See ...

```
$entity->getFieldDefinition('image')

'file_extensions' => string(16) "png gif jpg jpeg"
'file_directory' => string(31) "[date:custom:Y]-[date:custom:m]"

```

And edit

```
$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setDescription(t('Image field'))
  ->setSettings([
    'file_directory' => 'IMAGE_FOLDER',
    'alt_field_required' => FALSE,
    'file_extensions' => 'png jpg jpeg',
  ])
 ->setDisplayOptions('view', array(
    'label' => 'hidden',
    'type' => 'default',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'label' => 'hidden',
    'type' => 'image_image',
    'weight' => 0,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```
> 10 votes

# Answer
Thanks Matt for your prompt answer. I don't want to build the entity form and the image widget manually. Found out that I need to call `setDisplayOptions()` and `setDisplayOptions()` in `baseFieldDefinitions()`, now it works:

```
$fields['image'] = BaseFieldDefinition::create('image')
  ->setLabel(t('Image'))
  ->setRequired(TRUE)
  ->setDisplayOptions('view', [
    'label'   => 'above',
    'type'    => 'image',
    'weight'  => 0,
  ])
  ->setDisplayOptions('form', [
    'type'    => 'image_image',
    'weight'  => 0,
  ]);

```
> 4 votes

# Answer
To create an image field you would use the form api like so:

```
$fields['image'] = array(
'#title' => t('Image'),
'#type' => 'managed_file',
'#description' => t('The uploaded image will be displayed on the node page.'),
'#default_value' => $this->get('image'),
'#upload_location' => 'public://images/',
'#required' => TRUE,
);

```

You can learn more here https://api.drupal.org/api/drupal/elements
> -3 votes

---
Tags: 8
---


# Question
Title: How to avoid that a module encodes json puts out "\u0026" instead of "&"?
I am using a module to encode to json, but it puts out "`\u0026`" instead of "`&`".

How can I avoid that?

# Answer
**Explanation:**

Content as Json module simply returns the content by running it through drupal\_json\_output(), which in turn call drupal\_json\_encode(). Inside drupal\_json\_encode drupal ensures to have unicode conversion to special characters including '\<','\>','&'.

```
function drupal_json_encode($var) {
  // The PHP version cannot change within a request.
  static $php530;

  if (!isset($php530)) {
    $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
  }

  if ($php530) {
    // Encode <, >, ', &, and " using the json_encode() options parameter.
    return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
  }

  // json_encode() escapes <, >, ', &, and " using its options parameter, but
  // does not support this parameter prior to PHP 5.3.0.  Use a helper instead.
  include_once DRUPAL_ROOT . '/includes/json-encode.inc';
  return drupal_json_encode_helper($var);
}

```

If you see if your php version is greater than 5.3 than json\_encode() it self takes the argument to make sure all are unicode converted, it php is less than or euqall to 5.3, than drupal imcludes a helper `json-encode.inc` file which do the same.

**Solution:**

Way 1: The best would be to handle it on the client consuming the json data, have quivalent parser on the consumer side as well.

Way 2: Hook into contentasjson module to return json the way you want.Alter menu callback to register your own page callback

```
function mymodule_menu_alter(&$itmes) {
  $item['contentasjson/%/%']['page callback'] = '_my_custom_json_as_content';
}

//Copy the code as it from contentasjson module `contentasjson_get_data()` callback with a small change the json_encode function.
function _my_custom_json_as_content($type, $id) {
  switch ($type) {
    case "node" :
      $data = _contentasjson_get_node( $id );
      break;

    case "comment" :
      $data = _contentasjson_get_comment( $id );
      break;

    case "menu" :
      $data = _contentasjson_get_menu( $id );
      break;

    case "taxonomy_term" :
      $data = _contentasjson_get_taxonomy_term( $id );
      break;

    case "taxonomy_vocabulary" :
      $data = _contentasjson_get_taxonomy_vocabulary( $id );
      break;

    case "custom_data" :
      $data = _contentasjson_get_custom_data();
      break;

    default :
      $data = _contentasjson_get_error_message_type( $type );
      break;
  }

  // If false (no data object returned), generate return message
  $data = ($data == FALSE ? _contentasjson_get_error_message_id( $id ) : $data);
  // Here is the small change we are doing.
  json_encode( $data );
}

```
> 2 votes

---
Tags: 7
---


# Question
Title: Watchdog reports many spammy looking page not found warnings
Periodically, I like to run the following command to see what kind of activity and errors are going on with our website in real time.

```
drush ws --tail --full

```
1. Every second or so, there is a page not found error, but the pages are things that have absolutely nothing to do with the content of our website, following our Drupal URL format. Our site has been migrated a few times and may have old content from a long time ago, but again, this content doesn't relate at all to our subject material. Does anyone know what might be happening or if this is normal?
2. How do I stop the command from running?

Thanks!

# Answer
Pretty much every site online is being scanned by bots looking for security holes. The more popular the site, the more common this is. They don't necessarily follow links from the site itself, and even on Drupal sites you'll see requests for paths like "/wp-admin".

And you can exit via Ctrl-C.
> 1 votes

---
Tags: drush, log-messages
---