# Question
Title: How to use Views PHP to rewrite results of a field?
I am using Views PHP to rewrite fields in Views. I can access all variables BUT those that have a build mode. In my case, I have Content: Node field (which can be build according to any display), which should is accessible using the variable `$row->nodefield`. However, the content of that variable is always empty. I have tried with other variables, and every field with a build mode will not be rendered in Views PHP.

Is this a design issue or am I missing something?

I'm using Drupal 7 and Views 3

**EDIT**

Using dpm() on available values return the following:

dpm($row)

dpm($data)

# Answer
Above the "Output Code" section you should check the `$data` variable in the "Value" field.

Usually I just `dpm($data)` to find the field I need. Then you can save it to the `$static['myvalue']` variable for use in the "Output Code" field.

It is confusing but for some reason if you try just the `$row->xxx` variables in the "Output Code" section they are empty or set to the node-id.
> 6 votes

# Answer
The Available Variables `$row` items in Views are kind of useless for getting field values. But you don't need to use `noad_load` to get the data you need. First, as usual, hide the output of the field you want to rewrite, then in the Output Code field of your PHP field you can use `$data` like so:

```
<?php echo check_markup($data->field_field_body[0]['rendered']['#markup'], 'nitf_body'); ?>

```

In this case I'm stripping disallowed tags and attributed from content for use in an NITF export. If you're not sure what's inside of `$data`, you can of course `print_r($data)` to have a look at it.
> 3 votes

# Answer
Additional tip: The $data array indeed contain the raw node data and can be printed. But to render it correctly we need to process the fields with functions like field\_view\_field.
> 1 votes

# Answer
Are you trying to do this inside views? Why not just theme the views template itself instead of using the PHP global? I'm not sure if print\_r will work inside the view field. If it were me, I would just click theme--\>information, you'll see something like views-view-field--MyViewName.tpl.php

(edit, clarification) Under the views module theme folder, copy "views-view-field.tpl.php" then rename it to "views-view-field--MyViewName.tpl.php" and put it under your /templates folder in your site them. In the file, you'll see something like

```
<?php print $output; ?>

```

You can delete that and add all your fields manually like

```
<div class="MyPrettyTitle"><?php print $row->_field_data['nid']['entity']->title; ?></div>
<div class="MyNodeBody">
<?php print $row->_field_data['nid']['entity']->body['und'][0]['value'];?>
</div>

```

etc. Or wrap the $output with whatever you want.

Also, I've never had much luck with DEVEL, I always just use:

```
<?php print var_dump($row);?>

```

Then looking at the source of the page to get the variables. Maybe I'm just using DEVEL wrong, but I find I can get the variables for each row much easier with a regular old PHP var\_dump.
> 1 votes

# Answer
You should NEVER store PHP code in your database (and with View PHP you will). Use a Views hook instead to modify the results.
> 1 votes

# Answer
I spent two days to find the solution. The easiest way is update the "Views Php Module" to 7.x-2.x-dev. The Maintainer fixed this problem in their 2.x version.

You can download from here (Make sure you download **7.x-2.x-dev**): https://www.drupal.org/project/views\_php

Hope can help someone.
> 0 votes

---
Tags: views
---


# Question
Title: Submit form to 3rd party site, receive response to update original form
What I want to do

We have a simple form that people fill out to attach documents for review. We want to monetize it, using a specific vendor we currently use for non Drupal sites.

What we want to add is when someone saves their form, go to a confirm page, stating the price, then submit this to the 3rd party site. They process the payment and post a response back to our site, which we then modify the node to update the status to paid. We currently do this using Google app scripts on many other sites. We want to keep this site in Drupal for other reasons.

I'm very new to drupal, and am having some trouble with how to submit the form, and especially how to receive the post from the 3rd party vendor. I feel this isn't a crazy way to do this, but the lack of modules that

We've looked at Drupal Commerce and Ubercart, etc, but they seem pretty large for our needs.

# Answer
There are a variety of ways you can do this using the 3rd party API and the hooks provided by Webform such as

http://www.drupalcontrib.org/api/drupal/contributions%21webform%21webform.api.php/function/hook\_webform\_submission\_presave/7
> 0 votes

---
Tags: forms
---


# Question
Title: Managing module library dependencies with composer
I've found Dependencies in a custom module with drupal-composer, How can I include a third party library in my custom module without using Composer Manager and How to manage contrib modules composer dependencies on drupal 8 which are releated to my question, but no longer seem to apply since Drupal 8.1 and the deprecation of Composer manager.

Also popular guides such as The definitive introduction to D8 and Composer appear to no longer apply as they also mention composer manager.

The other solution opposed to composer manager, alter the core composer.json file feels like too much core hacking and would probably break with every Drush update of Drupal core(?).

More specifically, I am attempting to update Views vCards from Drupal 7 to 8. I have created my composer.json file as follows:

```
{
  "name": "drupal/views_vcards",
  "description": "Allows creation of vCards using the fields provided by the Views module.",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "homepage": "https://drupal.org/project/views_vcards",
  "require": {
    "maennchen/zipstream-php": "0.3.*"
  }
}

```

But if I put a composer.json file in my module folder, how do I make Drupal aware that that file is there, and how do I make sure the required `zipstream-php` library is downloaded?

Simply running `composer update` from the Drupal root does update a lot of Drupal dependencies, but it does not include the composer.json files that are in the modules folders. I also don't assume I should be calling `composer install` from inside all modules with dependencies.

How do I make Drupal aware of a module's dependency without using composer manager and/or hacking core?

UPDATE:

The composer merge plugin used by core appears to have support a wildcard path:

```
{
    "require": {
        "wikimedia/composer-merge-plugin": "dev-master"
    },
    "extra": {
        "merge-plugin": {
            "include": [
                "composer.local.json",
                "extensions/*/composer.json" // < ---- THIS LINE
            ],
            "require": [
                "submodule/composer.json"
            ],
            "recurse": true,
            "replace": false,
            "merge-dev": true,
            "merge-extra": false
        }
    }
}

```

Why doesn't core merge `modules/*/composer.json`, that would solve everything right?

Update 2:

THe reasoning for not supporting this is covered in this issue (which also has been quiet for some time now).

# Answer
> 7 votes
### New method using drupal-scaffold for greatest flexibility

**For Drupal 8.4.0 and greater using drush \>9.0.0**, drush make is deprecated and you should use a full-composer work flow as detailed in the drupal.org documentation links below. Those links do recommend using a composer project, but this may not work for everyone's web server setup. The following is step-by-step how to setup composer.json *manually* for detail explanation. The instructions regarding adding modules manually can still be done.

```
# Initialize composer. Stability alpha is important for custom modules that may be source managed outside of packagist or drupal.org
composer init --name myvendor/mysite --stability=alpha --license=GPLv2
composer config repositories.drupal composer https://packages.drupal.org/8
composer config discard-changes true

```

Then you need to add to composer.json *manually* the following based on your preferences because there is no way to do so automatically with composer as-is. These will configure drupal-scaffold to install your modules *where you want them* (as opposed to in vendor/ or a directory chosen by some other developer). Change 'webroot' to 'www' or 'public' or what your host is.

```
    "extra": {
        "installer-paths": {
            "webroot/core": ["type:drupal-core"],
            "webroot/modules/contrib/{$name}": ["type:drupal-module"],
            "webroot/modules/custom/{$name}": ["type:drupal-custom-module"],
            "webroot/themes/contrib/{$name}": ["type:drupal-theme"],
            "webroot/themes/custom/{$name}": ["type:drupal-custom-theme"],
            "webroot/profiles/{$name}": ["type:drupal-profile"],
            "webroot/libraries/{$name}": ["type:drupal-library"]
        },
        "patches": {}
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold"
    }

```

Now you can install some dependencies. Note that composer must be able to use scripts and plugins for this to work.

```
composer require composer/installers:^1.4.0 drupal-composer/drupal-scaffold:^2.3.0 cweagans/composer-patches:^1.6.2

```

Run the drupal-scaffold script once (or on your build server as needed):

```
composer drupal-scaffold

```

Drupal core, modules, themes, etc... can be installed as per the instructions below without the drupal-merge-plugin.

```
composer require drupal/core:~8.5.1 drupal/views_vcards

```

### Older method using drupal-merge-plugin or working with core directly

For Drupal 8.1.0 and greater, you can use composer to require Drupal modules directly. The documentation around Using Composer in a Drupal project and Using Composer to install Drupal packages through Drupal.org has been updated to take advantage of drupal.org's packagist. I find it works well already in a deployment scenario.

```
composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/views_vcards

```

For development, I think that manually adding in the dependency with `composer require` works fine. The merge approach works too with the drupal-merge-plugin and I use this for my drush make work flow.

```
composer config repositories.drupal composer https://packages.drupal.org/8
composer require mile23/drupal-merge-plugin
composer update

```

### Update 2016.06.22

I ran into an issue using drush make, which added the traditional Drupal version tags and drupal.org packagist URLs using semver. To that end, I needed to switch to using the stabler packagist at https://packagist.drupal-composer.org, which still supports the traditional Drupal version tags.

Also note that the build server or machine requires an exorbitant amount of memory to do a composer update (or require), which is necessary in all scenarios where running composer update on a similar development machine is not possible in your build process.

### Update 2016.09.23

### Update 2018.03.30

* Noticed an up vote. This is fairly old so decided to clarify about more recent development and setting up your site directly with composer since drush make has been (sadly) deprecated for a while.

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


# Question
Title: How can I make my menu children display horizontally below my main menu?
So the dark blue menu is the main menu, and the light blue lower menu is the children of Help. How can I set my menu up so that it functions like this mockup?

Also, I don't want this to be a dropdown menu. I want the children to stay open while you are on either the parent page or on one of the child pages.

UPDATE: I set it up the way you suggested, but instead of displaying the children in the sub-menu, it displayed the main menu and made the Help link a dropdown. Here is a pic of what happened.

# Answer
There are two ways I know of to achieve this. The first is configuring Drupal core's primary and secondary links functionality and some theming, the second is the Menu Block module.

# Primary and Secondary links core functionality + theming

If your theme utilizes the primary and secondary links variables you can configure the behavior you're looking for in the Menu Settings area.

From the Primary and Secondary Links documentation page:

> Drupal also provides two default system menus called "Primary links" and "Secondary links". ... A powerful feature of this primary/secondary system is when you choose the same menu as the source for both theme variables. In this case, the two menus magically couple together, and the Secondary links shows you the second level of items from the menu for the page that you are on.

Here is a free Drupalize Me Video that shows the process in Drupal 6, it's very similar in Drupal 7.

You would set up your menu with the sub-pages as children of the main page links:

* Home
* News
* Help
    + Basics
    + Content
    + Digital Dialog
    + Exams, etc

For this example I used the Main Menu that is default in core, but you can use any menu.

On the menu settings page (Admin \> Structure \> Menus \> Settings or http://example.com/admin/structure/menu/settings) set **both** the 'Source for the Main links' and 'Source for the Secondary links' to your menu.

When you visit your Help page the secondary links displayed will be the children of the Help menu link. And the child links will stay open while you are on either the parent page or on one of the child pages. In the Bartik theme the secondary links are located in the top right of the page.

To match the layout of menus in your screenshot, you would most likely need to make theming adjustments as the Primary and Secondary links are not blocks configurable on the Admin \> Structure \> Blocks page. At the theme layer the variables are $main\_menu and $secondary\_menu.

# Menu Block Module

If you foresee needing deeper levels of menus or want your menus to be in configurable blocks, or would just rather use a module than adjust your theme, there is the Menu Block module. From the project page:

> \[P\]rovides configurable blocks of menu trees starting with any level of any menu. ... if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree.
> 1 votes

---
Tags: 7
---


title: Chunked Ajax Responses

text:
# Question
Title: Chunked Ajax Responses
Does Drupal support chunked AJAX responses in either direction?

I have not been able to find materials on this so far and am curious:

1. Is Drupal AJAX capable of working with chunked AJAX responses (Does it have the functionality of waiting until all chunks are received and display them as soon as possible)
2. Does Drupal have functionality to send Chunked responses to an AJAX request (Send data as soon as it's ready, so it can be displayed to the client)

What I mean by chunked AJAX is basically what multiple service booking sites do (example: airline tickets) They do multiple requests to different service providers and airlines, and results are displayed as soon as they're available and populated with more as they are sent.

# Answer
I don't think Drupal 7 or Drupal 8 support chunked AJAX response. Because AJAX in Drupal is implemented with **jQuery.ajax** which does not support that.
> 2 votes

---
Tags: 8, ajax
---


# Question
Title: Creating custom settings/variables for site
I created a custom Form from a module in Drupal 8. Here is the code:

```
class SocialSettingsForm extends FormBase {

    public function buildForm(array $form, FormStateInterface $form_state){
        $form['facebook'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Facebook Username'),
            '#description' => $this->t('Enter your facebook username.'),
            'required' => FALSE,
        ];

        $form['actions']= [
            '#type' => 'actions',
        ];

        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
        ];

        return $form;
    }

        public function getFormId(){
            return 'social_socialsettingsform';
        }

         public function validateForm(array &$form, FormStateInterface $form_state){
            $facebook = $form_state->getValue('facebook');
            if (strlen($facebook) < 5){
                // Set an error for the form element with a key of "title".
                $form_state->setErrorByName('facebook', $this->t('The username must be at least 5 characters long.'));
            }
         }

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

            $title =$form_state->getValue('facebook');
            drupal_set_message(t('You specified a title of %title', ['%title' => $title]));
         }

    }

```

The form works fine. But I'm not sure which direction and conventions to follow in order to make use of the user's input.

I would like to make use of the username the user enters, but I'm not sure how to store that input from the form. Ideally I would use these settings in a Twig template or a module.

UPDATE: I have figured out how to add custom variables to my theme but I'm not sure how to get my form to access them. I was able to add

```
function mytheme_preprocess_page(&$vars){
    $vars['facebook'] = 'default';
}

```

But I'm not sure how to get my form to alter this variable.

# Answer
> 1 votes
To save custom configuration you probably want to use `ConfigFormBase`, the code would look something like this.

```
class SocialSettingsForm extends ConfigFormBase {
  ...

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'social.settings', // The name of the config you want to edit
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('social.settings')
      ->set('facebook', $form_state->getValue('facebook'));
  }
}

```

Then everywhere, you can use the config factory of the Drupal global object to get the config like this.

```
function some_preprocess_function(&$variables) {
  $facebook = \Drupal::config('social.settings')->get('facebook', 'default_value_if_no_value_is_set');
}

```

Note the above approach is centered around how you would do it in a module, saving and getting configuration. You should also note that it's best practice to define the configuration a module provides in a yml file located in `module_folder/config/schema/module_name.schema.yml`. I'm not 100% sure what the file is actually used for, as it's possible to save configuration not defined in the config file and all other features seem to "work" just fine without it.

---
Tags: forms, 8
---


# Question
Title: How do you programmatically create a webform with a managed_file type?
I haven't been able to find a single example of how to create a webform with a managed\_file type.

The webform initially had the type 'file', but needs to be changed to accept multiple attachments. When the type is changed to 'managed\_file', the field for uploading attachments does not render.

Here is my code snippet for the attachment field:

```
7 => array(
    'name' => t('Attachment'),
    'form_key' => 'attachment',
    'type' => 'managed_file',
    'upload_location' => NULL,
    'pid' => 1,
    'weight' => 6,
    'value' => '',
    'required' => '0',
    'extra' => array(
      'directory' => 'story',
      'title_display' => 'before',
      'private' => 0,
      'wrapper_classes' => '',
      'css_classes' => '',
      'filtering' => array(
        'size' => '2 MB',
        'types' => array(
          'gif',
          'jpg',
          'jpeg',
          'png',
          'txt',
          'rtf',
          'html',
          'pdf',
          'doc',
          'docx',
          'ppt',
          'pptx',
          'xls',
          'xlsx',
          'zip',
        ),
        'addextensions' => '',
      ),
      'rename' => '',
      'scheme' => 'public',
      'progress_indicator' => 'throbber',
      'description' => '',
      'attributes' => array(),
      'analysis' => FALSE,
    ),
  ),
);

```

Thanks much!

# Answer
Making a couple of leaps here:

1. I couldn't find a D8 release for Webform so assuming D7
2. I'm assuming by managed\_file (which is a FAPI element type) you mean a field API file field, as you mentioned making it accept multiple files (which the managed\_file element doesn't have any support for).

So with those in mind...

Webform implements its own set of components, of which file is one type; it doesn't use the field API, so unfortunately you can't attach field API fields of any type to it.

The out-of-the-box file component doesn't support multiple uploads, but there's a contributed module, Webform Multiple File, which does:

> Module Webform Multiple File provides new Webform component for multiple file uploading. The module based on principles of file field widget and has similar design.
> 0 votes

---
Tags: 8, webforms, files
---


# Question
Title: Editing entity property (title) with ECK and editablefields
I'm using Entity Construction Kit and Editablefields. When configuring the "Manage Display" of a bundle, the properties (specifically, "title") do not have the option of "editable".

Is there a way to make the entity property fields editable as well? I'm considering doing a dummy field that updates the entity title on save.

# Answer
> 0 votes
I think you can use Title module to replace the default title field.

---
Tags: 7, entities
---


# Question
Title: Help me understand this Fatal error: Call to undefined function EntityDefaultMetadataController::bundleOptionsList()
With updated modules to recent releases, Recently this error started appearing when executing 'Modify entity values' in views bulk operations. It happens on all the views in the site. Indications where to start digging is much appreciated. `Fatal error: Call to undefined function EntityDefaultMetadataController::bundleOptionsList() in /home/cdt/public_html/sites/all/modules/views_bulk_operations/actions/modify.action.inc on line 173`

# Answer
The static method `EntityDefaultMetadataController::bundleOptionsList()` is a part of Entity API module that VBO is dependant upon. One of your modifiable entity properties needs this method to retrieve options for the modify operation.

You need to debug why this method isn't available. It's defined in **entity.info.inc** and should be included if the Entity API module is enabled.
> 3 votes

# Answer
There are several things that could have happened, but two are most likely in my experience. Either something has gone wrong in the registry and it needs rebuilding or an op-cache (APC or memcache usually) is out of date/corrupt.

**To fix the registry use registry rebuild:** If you have `drush` installed, download the Registry Rebuild module for drush: `drush dl registry_rebuild`

Then run: `drush rr`

**To fix the op-cache:** Restart the service that controls it (Apache often, but that depends on your server setup), or use the service's built-in clearing mechanism.
> 1 votes

---
Tags: views
---


# Question
Title: Maintenance mode says it's on, but site is still available
Before attempting to do some module updates, I enabled maintenance mode on the site. I then noticed that the site was still available to all visitors, even though the Configuration-\>Development-\>Maintenance Mode page said that maintenance mode was enabled.

I have cleared all caches (via admin pages and drush) several times already, and have checked the settings.php file to see if there was a manual override set. I have also turned the setting on/off several times, logged out and logged back in, etc.

I've never seen this happen before. What else can I try?

# Answer
Have you checked the permission "use the site in maintenance mode" to see whether it is enabled for other users?
> 1 votes

---
Tags: maintenance-mode
---


# Question
Title: How to make 1 or more of total 4 fields mandatory
I have 4 decimal fields where user enters can enter price per day, week, month, year. He can choose to enter 1 or more. At least 1 has to be entered of those 4.

Goal is views exposed filter with around 10 filters, all fields in it are mandatory on node creation so there is always result from view, except those 4 mentioned in first place.

Problem is if i add exposed filters for fields day, week, month, year, "betwean" 0 and 100 for each filter, none of the nodes show up on search page (without using the filters yet), as for now, no node has all prices written, and rarely they do. Users usualy put day and week price, or week and month price, or only year price.

On main view page i would atleast like to have all nodes show up with exposed filters in BEF (like they currently do), and then let view when using filters, filter out those who does not have week or month if customers were using filters with those values.

# Answer
You have to implement your own validation logic through a hook\_form\_alter().

```
    <?php
    function MY_MODULE_form_alter(&$form, &$form_state, $form_id){
      if ($form_id === 'YOUR_FORM_ID')
        $form$form['#validate'][] = 'YOUR_VALIDATION_FUNCTION';
      }
    }

    function YOUR_VALIDATION_FUCNTION($form, $form_state){
      $assingned_values = 0;
      if(!empty($form_state['values']['FIELD1']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD2']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD3']['und'][0]['value'])){
        $assigned_values++;
      }
      if(!empty($form_state['values']['FIELD4']['und'][0]['value'])){
        $assigned_values++;
      }
      if ($assigned_values === 0){
        form_set_error('', 'You must set at least one field');
      }
    }

```
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to make a template for content type with panels
I´ve created a content type "Products" with "N" fields and I try to create a template for this content type, each product should have its own page.

How I do this?

# Answer
> 0 votes
Google searching I found this solution.

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

Best regards!

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


# Question
Title: PHP Fatal error: Call to a member function get_option() views/includes/view.inc on line 2493
I installed the Carbide Builder Module from SooperThemes and now receive this error when trying to go to any node/add page.

Their support says one of my Views displays has a view with a missing display plugin.

I have a lot of views/displays. How can I find it easiest?

UPDATE: Looks like there are some old Views from a D6 installation uses Feeds.

# Answer
> 0 votes
Enable the Devel module and insert a `ddebug_backtrace()` statement before the line containing the `get_option()` method call. It should print out a stack trace that you can follow to some view id.

---
Tags: views
---


title: Hide progress bar

text:
# Question
Title: Hide progress bar
I am using commerce checkout progress module for showing the checkout progress to the user.

I am showing this block in cart page also. I want to hide this block if the cart is empty. How can I achieve it?

# Answer
> 0 votes
The Drupal cart is a view. As such, only the view is aware of the amount of products in the cart and it might be tricky to get the amount of products in the cart. (it can be done by using php, load the order, count the products etc... but it would involve some coding.)

I suppose the easiest way would be to alter the Drupal commerce cart view. Then use the Views Block Area module to place the progress block in the Views header. If you leave the `Display even if the View has no results` unchecked. It should not render on empty carts.

Additionally you will have to remove the cart page block you set via the blocks administration page from the cart page.

You can do that by showing the block on all page except `cart`. The View will take care of it on that page.

# Answer
> 0 votes
Finally found the solution for this. Below code removes the **payment** tab.

```
function example_module_commerce_checkout_progress_items_alter(&$items) {
  unset($items['payment']);
}

```

---
Tags: 7, commerce
---


# Question
Title: How to show conditional tab in webform 7.x-3.x
I created an enquiry form using the webform 7.x-3.x module and I want to create condition on field, but not showing conditionals tab.

I also use webform\_conditional 7.x-1.0-beta2 but conditional tab not showing.

But, I create again enquiry form from webform 7.x-4.x Module. In webform i show conditionals tabs.

My question is how to show conditions tabs in webform 7.x-3.x. I not want to upgrade module webform 3.x to 4.x.

Have any configuration or module to show conditional tab.

# Answer
> 0 votes
If you specifically want to use this within webform you need to use webform conditional to work smoothly.

---
Tags: 7, webforms, entities
---


# Question
Title: How to implement a notifications on my webpages while any data insertion or updation occured on my custom tables
How to implement a notifications on my web pages while any data insertion or updation occured on my custom tables.

My requirement is for an auction website where once an user places a bid, then all the other logged in users in that region should get the notifications.

# Answer
> 0 votes
You need to accomplish with three module and rules, private message and custom module.

rules provide event, condition and action through which you need to set, events supports CRUD. Condition provides you to check condition has been fulfill and Event sends you private message to groups or personal mail / text message.

Private message provides you send bulk message / mail through rules. Message itself can be thread.Private message has feature to count unread message to particular user.

Custom module to create event, conditions and actions for rules to custom table.

---
Tags: notifications
---


title: The home page is showing only texts

text:
# Question
Title: The home page is showing only texts
I am using the drupal 8.1.2 version but the home page is showing only texts like the image attached. Please suggest what to do.

# Answer
> 1 votes
This sympton indicates that CSS is missing. **One reason can be**: It's because that Drupal is not able to crate the aggregated CSS in the files directoy. Give the right permission to the directory (.drupal\_root/sites/defaults/files):

In your defaults directory in linux type the following:

```
find files/ -type d -exec chmod 775 {} +
find files/ -type f -exec chmod 664 {} +

```

In windows am not really familiar with it. You will have to search for that.

And after this run a "drush cr" from your console, or try to do that via UI to clear all your caches. Your css will be loaded after this.

---
Tags: 8, media
---


title: Bots taking over my site

text:
# Question
Title: Bots taking over my site
I just noticed that bots have been taking over my Drupal website for quite a few weeks. There are over 600 pages of content. I only noticed now because the website is on hold (still available online) at the moment. I just got a message from the hosting company that the maximum disk space has been reached, which came as a total surprise.

I've tried changing password but it's still uploading. I deleted the *Basic page* content type because all the content was created with that content type, but now they are using a different content type, and the content is still there even though I thought it would remove all the content when I removed basic page.

How can I stop them from creating content?

# Answer
In the People config page you can set up who can register accounts. Put that option on `Administrators only`. After that identify the bots users and delete them (make sure to delete them, not just disable). Then, identify content created by bots and delete it. Also, don't forget to check who can create content on the website (permissions page).
> 2 votes

---
Tags: 7
---


title: Using putty to patch to cloze module

text:
# Question
Title: Using putty to patch to cloze module
I use Putty to apply cloze module patch. Here are my steps:

1. I go to this directory: sites/all/modules/contrib/cloze
2. I save the patch: wget https://www.drupal.org/files/issues/cloze-report\_form\_quiz\_compatibility\_fixed-2216049-1.patch Save as: cloze-report\_form\_quiz\_compatibility\_fixed-2216049-1.patch
3. I apply patch: git apply cloze-report\_form\_quiz\_compatibility\_fixed-2216049-1.patch (nothing happen. no error)
4. I check the status: git status

Result:

> fatal: Not a git repository (or any of the parent directories): .git

How come?

# Answer
After your step 1, make sure to initialize the GIT repository, which will add the `.git` directory, subdirectories and files that store your repository data.

To do so, just use command `git init` while in your directory `sites/all/modules/contrib/cloze`.

If you're new to using GIT with Drupal, you may want to look at the community documentation located at Building a Drupal site with Git (+ its child pages).
> 2 votes

---
Tags: 7, version-control
---


# Question
Title: How to access the node title within a field template?
I'd like to know the node title within the file link template. How can I get it?

For the current example I use the bootstrap `file-link.html.twig` template. In it, I have the following variables:

```
{#
/**
 * @file
 * Theme override for a link to a file.
 *
 * Available variables:
 * - attributes: The HTML attributes for the containing element.
 * - link: A link to the file.
 * - icon: An icon.
 * - icon_only: Flag to display only the icon and not the label.
 * - icon_position: Where an icon should be displayed.
 *
 * @see \Drupal\bootstrap\Plugin\Preprocess\FileLink::preprocessVariables
 */
#}

```

I dont know if a preprocess function is the correct way to go. I didnt even found a respective hook for drupal 8 for that. I dont even know if this is a field template. But still, the question would also be interesting for other templates than file-link.

# Answer
He wants to get the node title in the file link template (I assume that is `file-link.html.twig`). You can implement the hook `template_preprocess_file_link()` in your mytheme.theme file, get the current node and pass its title to twig, something like:

```
function mytheme_preprocess_file_link(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   $variables['node_title'] = $node->getTitle();
}

```

Then, in `file-link.html.twig`:

```
{{ node_title }}

```
> 4 votes

# Answer
I assume, you are using Drupal 7 and we're talking about a node.tpl.php:

```
<h2<?php print $title_attributes; ?>>
 <a href="<?php print $node_url; ?>">
  <?php print $title; ?>
 </a>
</h2>

```

\*Edit: Just realized, you're using Drupal 8:

For a node.html.twig you could try:

```
  {{ title_prefix }}
   {% if not page %}
    <h2{{ title_attributes }}>
     <a href="{{ url }}" rel="bookmark">{{ label }}</a>
    </h2>
   {% endif %}
 {{ title_suffix }}

```
> -2 votes

---
Tags: 8
---


# Question
Title: What is faster: hook_form_alter or hook_form_FORM_ID_alter?
I want my Drupal site be as fast as it can. So I'm considering whether to use hook\_form\_alter with an if statement inside or hook\_form\_FORM\_ID\_alter. I know that it's a bit more convenient to use the latter but I'd prefer to use the faster method.

Does somebody know which is faster and how much? And I don't only mean form\_alter, but all hooks with an ID in it.

# Answer
> 1 votes
The `hook_form_FORM_ID_alter` is faster than `hook_form_alter`.

Modules can implement `hook_form_FORM_ID_alter()` to modify a specific form, rather than implementing `hook_form_alter()` and checking the form ID, or using long switch statements to alter multiple forms.

Form alter hooks are called in the following order:

1. `hook_form_alter()`
2. `hook_form_BASE_FORM_ID_alter()`
3. `hook_form_FORM_ID_alter()`

I hope this helps :)

---
Tags: performance
---


title: is there is any way to include files?

text:
# Question
Title: is there is any way to include files?
I am writing PHP code in a rule, where I include another PHP file.

```
include_once 'google-api-php-client/src/Google/autoload.php';

```

Where do I need to include files?

# Answer
Try the standard PHP way:

1. `require 'google-api-php-client/src/Google/autoload.php';`
2. `include_once 'includes/google-api-php-client/src/Google/autoload.php';`
3. `include ('includes/google-api-php-client/src/Google/autoload.php');`

or Drupal way:

```
include_once DRUPAL_ROOT . '/includes/google-api-php-client/src/Google/autoload.php';

```
> 0 votes

# Answer
1. You can use `module_load_include()` to include a PHP file.

```
module_load_include('php', $type, 'includes/google-api-php-client/src/Google/autoload');

```

Where type can be either theme name or module name. I guess in this you are building some drupal module so it must be module type. In which case it will look for autoload.php file inside your name module directory. However internally it will do the require\_once instead of include\_once :)
2. You can use Libraries API module to include a php file. For this you will have to keep this google-api-php-client inside libraries folder. And you will perform these steps to implement it.

```
function hook_libraries_info() {
  $path = libraries_get_path('google-api-php-client');
  set_include_path($path."/src/" . PATH_SEPARATOR .  get_include_path());
  $libraries['google-api-php-client'] = array(
  'name' => 'Google OAuth2 Library',
  'vendor url' => 'http://code.google.com/p/google-api-php-client',
  'download url' => 'http://github.com/google/google-api-php-client/archive/master.zip',
  'version arguments' => array(
    'file' => 'src/Google/Client.php',
    'pattern' => '/LIBVER = "([0-9\.a-z]+)/',
    'lines' => 40,
  ),
  'versions' => array(
    '1.0.5-beta' => array(
      'files' => array(
        'php' => array(
          'src/Google/Client.php',
        )
      ),
    ),
    '1.1.5' => array(
      'files' => array(
        'php' => array(
          'src/Google/autoload.php',
        )
      )
    )
  ),
  'files' => array(
    'php' => array(
      'src/Google/Client.php',
    ),
   ),
  );
  return $libraries;
}

```

Note: The version is 1.0.5-beta, so you may need to change the version as per your API version.

Then to include this library in another module.

```
function hook_init() {
  $path = libraries_get_path('google-api-php-client');
  if ($path) {
    set_include_path($path."/src/" . PATH_SEPARATOR . get_include_path());
  }
}

```
3. Since it comes it composer.json/autoload.php you can use these modules to load it automatically from libraries folder. X Autoload, Composer Autoload, Composer Vender Autoload, although you will still need to define the location inside your module.

### Using the XAutoload module

```
   function mymodule_libraries_info() {
     return array(
       'google-api-php-client' => array(
         'name' => 'Google Client Library',
         'xautoload' => function($adapter) {
           /** @var \Drupal\xautoload\Adapter\LocalDirectoryAdapter $adapter */
           // Scan sites/all/libraries/google-api-php-client/composer.json to look for
           // autoload information.
           $adapter->composerJson('composer.json');
         }
       )
     );
   }

```
> 3 votes

---
Tags: rules
---


# Question
Title: How do I create extra permissions for an eck created entity?
I have created an entity using Entity Construction Kit (ECK) and wish to add extra permissions for that entity such as view own, edit own and delete own. I see there has been some movement in this thread Better Permissions and a few others to create better permissions in general for entities but I want to know how can I do it in my own custom module.

I do not want every person on the site to be able to view,edit,delete so I have disabled those perms for my created entity.

I'm stuck and cannot find any good documentation on it.

# Answer
You need to alter the entity info using:

```
hook_entity_info_alter

```

and add the access callback

e.g:

```
function EXAMPLE_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['access callback'] = 'my_entity_access';
}

```

and then in my\_entity\_access

```
function my_entity_access($op, $entity = NULL, $account = NULL) {
  switch($op){
    case 'view':
    // view check
    // e.g return user_access('view my_entity', $account);
    break;
    case 'create':
    // create check
    break;
    case 'update':
    // update check
    break;
    case 'delete':
    // delete check
    break;
  }
  return FALSE;
}

```

See node\_access for more info

You may want to use hook\_permission to define your own permissions also.
> 6 votes

# Answer
Here is a working example:

```
function my_permission() {
  return array(
    'view own forum post' => array(
      'title' => t('View own forum post'),
      'description' => t('View own forum post.'),
    ),
    'edit own forum post' => array(
      'title' => t('Edit own forum post'),
      'description' => t('Edit own forum post.'),
    ),
    'delete own forum post' => array(
      'title' => t('Delete own forum post'),
      'description' => t('Delete own forum post.'),
    ),
  );
}

function my_entity_info_alter(&$entity_info) {
  $entity_info['forum']['access callback'] = 'my_forum_access';
}

function my_forum_access($op, $entity) {

  global $user;

  $entity_type = $op == 'create' ? $entity : $entity->type;

  if (eck__entity_access($op, $entity_type, $user, 'forum')) {
    return TRUE;
  }

  if ($entity && $entity_type == 'forum_post') {
    switch ($op) {
      case 'view':
        if (user_access('view own forum post', $user) && $user->uid == $entity->uid) {
          return TRUE;
        }
        break;
      case 'update':
        if (user_access('edit own forum post', $user) && $user->uid == $entity->uid) {
          return TRUE;
        }
        break;
      case 'delete':
        if (user_access('delete own forum post', $user) && $user->uid == $entity->uid) {
          return TRUE;
        }
        break;
    }
  }

  return FALSE;
}

```
> 2 votes

# Answer
There is a reference to the own functionality through eck's own behavior system, in the "better permissions" issue you mentioned above. Check it out and give us some feedback.
> 0 votes

---
Tags: 7, users, routes, entities
---


title: Where are contact form entries stored?

text:
# Question
Title: Where are contact form entries stored?
I am aware that Webform is now out of the Window and has more or less been replaced by Core Contact Forms. I created a form and it works great. Only problem is, I can't for the life of me find out:

1. If it stores a copy of the submitted form locally?
2. Where it stores it if it does?
3. Or if it does not store it, how to allow it to be stored?

Like webforms, I want to click somewhere and see "Show all submissions". But no idea where?

# Answer
I don't know if it really stores them anywhere by default, but I think that this module wouldn't exist if it does store them. Check it out.
> 3 votes

---
Tags: forms, 8, emails
---


title: Multiple Instances of Entity Form

text:
# Question
Title: Multiple Instances of Entity Form
I am working on a module with a form that allows multiple "members" to be submitted. The form allows the number of members to be specified, then displays a set of member fields that many times. This is working well, but the set of fields for each member is fixed.

I'm looking at whether it would be possible to turn it into an entity form to allow the set of fields for each member to be configured.

Is it possible for an entity form to display several sets of fields on one form, and have them all submitted together?

Any pointers on how to start?

# Answer
> 1 votes
Here is what I would do:

1. Create that many entites as you would like to able to submit with entityTypeManager (members)
2. Create their form objects with EntityFormBuilder-\>getForm($entity)
3. Set out all the elements you don't need (their submit buttons)
4. Add them to form like this:

$form\[$custom\_form\_id\] = array( '#type' =\> 'markup', '#markup' =\> render($created\_form), '#prefix' =\> '', '#suffix' =\> '' );
5. In your submit, call the children form submit functions.

---
Tags: forms, 8, entities
---


title: How do I call a theme function?

text:
# Question
Title: How do I call a theme function?
Can someone tell me that how can I call theme function, in Drupal 8, within other hook function?

Of course, we should write hook\_theme function.

For example (in Drupal 7): `theme('THEME_NAME')`;

What is wrong in below snippet:

```
function theme_sometheme($variables) {
   $another_theme = array('theme' => 'another_theme_for_test', 'arg1'  => 'value');
   return '<div>'. drupal_render($another_theme) . '</div>';
}

```

Note: Above code is not rendering anything.

# Answer
> 3 votes
The correct code is using the following line.

```
$another_theme = array(
  '#theme' => 'another_theme_for_test',
  '#arg1'  => 'value'
);

```

That is similar to the following code you find in `rdf_preprocess_comment()`. The only difference are the theme applied, and the arguments that theme requires; the way you pass the theme name or its arguments is the same.

```
$variables['author'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['author'],
  '#attributes' => $author_attributes,
];
$variables['submitted'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['submitted'],
  '#attributes' => $author_attributes,
];

```

Keep in mind that in most contexts you can just return a render array, which in your case is the following one.

```
[
  '#theme' => 'another_theme_for_test',
  '#arg1' => 'value',
];

```

The necessity to call `drupal_render()` is limited to very specific cases, so most likely you don't need it. If you do, you should use `\Drupal::service('renderer')->render()` instead.

# Answer
> 0 votes
I think in Drupal 8 you need to build a renderable array in any case so that might solve the trick :

```
$another_theme = [
  '#theme' => 'another_theme_for_test',
  '#arg1' => 'value',
];

```

---
Tags: theming, 8
---


# Question
Title: How to add 'odd' or 'even' class in each row of a Views Table output?
I'd like to take advantage of Drupal's default CSS for even/odd rows in a table.
I use Views to list the content of a custom entity with 'Table' format.
I don't know where to put this setting...

Thanks in advance

P.-S. I use Drupal 8 (8.1.2)

# Answer
> 7 votes
This can be related to Drupal, since you want to add classes to table rows, here is how you do it:

Copy the core/themes/classy/themplates/views/views-view-table.html.twig to your theme's template folder, and change the following lines (line 95):

```
  <tbody>
    {% for row in rows %}
      {% set parity = cycle(['odd', 'even'], loop.index0) %}
      <tr {{ row.attributes.addClass(parity) }}>

```

---
Tags: views, 8
---


title: How do I remove markup from fields?

text:
# Question
Title: How do I remove markup from fields?
I want to remove all the default Drupal markup around content types fields.

In Drupal 7, Fences does it like a charm, but its Drupal 8 version is not stable yet. Another choice would be Display Suite Extra, in Drupal 7, and we can do it with Control markup with field templates, but in the Drupal 8 version there isn't any admin/structure/ds/extras and *Check the option Enable Field templates* exists.

How can I get rid of the default markup field wrappers?

# Answer
> 4 votes
Depending on your project and goals there are a few solutions. Drupal 8 core itself generates very little markup, the field markup is now coming from a theme, and the markup from those base themes is much lighter-weight than D7's core. To get started you may want to review the new theme guide, and MortonDK's session from DrupalCon New Orleans.

Given the control you seem to be seeking, you should probably create a theme that's based on Stable (which is the default if you don't set a base theme). Then enable theme debugging, and as you find templates you don't like the output of, copy them from `core/themes/stable/templates/...` into your theme's templates folder. If you explore either stable or classy you'll see a variety of field templates in the field directory, and you can target them on a case-by-case basis in your theme as needed (theme debug will provide you the name suggestions you need to create the properly targeted file).

Some people are copying the entire stable theme so they have all the templates on hand from the start. If you did that you may also want to set the base theme to false so stable is disabled entirely.

You can also use the `hook_theme_suggestions_field_alter()` and `hook_preprocess_field()` in your theme's `.theme` file to make changes before reaching the twig files. If you use the Drupal console to generate your theme, the boilerplate code will come with a large collection of the preprocess functions already defined.

# Answer
> 1 votes
One possible and working solution can be is defining your own custom field templates. This will help!

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


# Question
Title: Able to use custom variables in page.html.twig but not in menu.html.twig
I have a module setting config variables which I'm trying to display in a twig template. When I use

```
function mytheme_preprocess_page(&$variables){
    $variables['facebook'] = \Drupal::config('social.settings')->get('facebook', 'No username');
    $variables['twitter'] = \Drupal::config('social.settings')->get('twitter', 'No username');
    $variables['instagram'] = \Drupal::config('social.settings')->get('instagram', 'No username');
    $variables['youtube'] = \Drupal::config('social.settings')->get('youtube', 'No username');
}

```

I'm able to display the variables in my page.html.twig template by invoking

```
{{ facebook }}{{ twitter }}{{ instagram }}{{ youtube }}

```

However I'd like menu.html.twig to invoke it. Even when adding a preprocess hook for menu like so

```
function mytheme_preprocess_menu(&$variables){
    $variables['facebook'] = \Drupal::config('social.settings')->get('facebook', 'No username');
    $variables['twitter'] = \Drupal::config('social.settings')->get('twitter', 'No username');
    $variables['instagram'] = \Drupal::config('social.settings')->get('instagram', 'No username');
    $variables['youtube'] = \Drupal::config('social.settings')->get('youtube', 'No username');
}

```

menu.html.twig produces nothing when invoking

```
{{ facebook }}{{ twitter }}{{ instagram }}{{ youtube }}

```

I know menu.html.twig is being used because I can make changes to it and the changes will appear. I also know that mytheme\_preprocess\_menu is being called because drupal\_set\_message works from it. However {{ dump() }} from menu.html.twig is not displaying anything on the page.

# Answer
> 2 votes
The menu theme is declared using the variables key (see doc).

That means that only the keys present in the variables array can be passed to the template.

Any custom variable needs to be first added using hook\_theme\_registery\_alter

---
Tags: 8, hooks, theming
---


# Question
Title: How do I retrieve an entity from an entity reference
I have a custom module with three entities. The first represents a chemical compound. The second is a list of the periodic table of elements. The third is a many-to-many binding between these two, and also contains a "quantity" field. This last entity is to be able to create each chemical's chemical formula.

Example-combining the quantities and element symbols to produce CH4O

```
Entity:chemicals
id   name
1    Methanol

Entity:elements
id    symbol   name
1      H       Hydrogen
2      C       Carbon
3      O       Oxygen

Entity:chemical_formulas
id     element    chemical   quantity
1        2          1           1
2        1          1           4
3        3          1           1

```

I have the three entities working to the point that I can get all the correct data in the database. However, retrieving has proven a challenge.

My ChemicalFormulas class contains this function, and this seems to be where the problem is because it always returns 'null'. The ChemicalFormulas-\>getQuantity() function is basically the same, and it works fine.

```
//in the ChemicalFormulas class
public function getElement() {
   return $this->get('element')->value;
}

```

The field is defined as

```
$fields['element'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Element'))
  ->setDescription(t('The Element.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'elements')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

```

I am trying to produce the formula with this function

```
public function getFormula(){
  $query = \Drupal::entityQuery('chemical_formulas')
    ->condition('chemical', $this->id());

  $ids = $query->execute();
  $entries = entity_load_multiple('chemical_formulas', $ids);
  $formula = "";
  foreach ($entries as $entry){
    //Is element supposed to be an entity or the id of an entity?
    //$element = $entry->getElement(); //If it's an entity
    $element = entity_load('elements', $entry->getElement()); //If it's an integer.
    $symbol = $element->getSymbol();
    $quantity = $entry->getQuantity();
    if ($quantity == 1) {
      $quantity = "";
    }
    $formula .= $symbol . $quantity;
  }
  return $formula;
}

```

# Answer
> 0 votes
This gets the function to work the way it is.

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

public function getElementId() {
  return $this->get('element')->target_id;
}

```

If anyone has any suggestions on a better way to design the system to make it behave more optimally, let me know. For example, is there a built in drupal8 way to create many-to-many relationships without having to explicitly define the connecting table as a separate entity?

# Answer
> 0 votes
Entities part:

I think (as much you showed) your entity definition is wrong:

1. Entity names should be always SINGULAR: Chemical, Element, Chemical Formula
2. Your Chemical Formula should have the ability to hold reference to MULTIPLE elements (H20 for example, has H and O elements). Which means you won't able to store this information in this entity table, but you will have to create an external table to hold this information. You can find example for this in core entities (like taxonomy\_terms, if I remember good).
3. If you make this changes right, you won't have query anything, since the referenced entity ids (elements, chemical) will be present in your entity. You only have to load via EntityTypeManager.

Final hint again: always examine core / contrib entities. Node, Taxonomy terms are pretty good examples.

---
Tags: 8, entities
---


# Question
Title: Can we fetch the depth of taxonomy from term load
Term::load (termid) can we get the depth of term. If yes how can we achieve ? If no, how can we achieve this without loading tree nor children is there any other way we can fetch depth?

# Answer
> 1 votes
1. You can use TermStorage loadTree function. It will load the whole tree and the depths of each term will be avaiable.
2. A much more cleaner / efficient way can be to use the "taxonomy\_term\_hierarchy" table, (database service, select..). You query over and over again till the "parent" (or current examined) term parent is 0.

If you really feel you are being lost, take a look on this thread.

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


title: Drupal adding an include

text:
# Question
Title: Drupal adding an include
I am using the Zen theme, what I could like to do is effectly add a php include for a header area. This is common code so a block will not really do.

I have html.tpl.php which is added automatically to each page is there anyway to add custom chunks to every page for example myheader.tpl.php

# Answer
> 0 votes
You can try module\_load\_include

> Loads a module include file.

**Parameters**

**$type:** The include file's type (file extension).

**$module:** The module to which the include file belongs.

**$name:** (optional) The base file name (without the $type extension). If omitted, $module is used; i.e., resulting in "$module.$type" by default.

**Examples**:

```
  // Load node.admin.inc from the node module.
  module_load_include('inc', 'node', 'node.admin');
  // Load content_types.inc from the node module.
  module_load_include('inc', 'node', 'content_types');

```

# Answer
> 0 votes
You rarely (probably never) want to pull in arbitrary PHP into a template. Generally you want all your processing to have happened before you reach this stage. The theme files should be 100% focused on generating markup.

If you are looking to do some processing on every page, you can use `template_process_html()`. Generally this is used to alter page variables before final render, or to add CSS and JS based on information from previous operations.

If you are looking to provide some output, you can add another region to your theme (or use a block in an existing region, but you've already passed over that concept).

---
Tags: 7, theming
---


# Question
Title: Two step user approval after registration
I'm new to Drupal, and need help on user registration.

* A user registers on the site by filling in fields which include: name , DOB, users email(user1), password and official contact email address(ocea).
* Once the form is submitted, an email goes to official contact email address(ocea). The user is approved once the administrator will give his consent.

How I can I achieve this? A module? Rules?

# Answer
> 3 votes
You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on `/admin/config/people/accounts`.

>

As for name, and date of birth, those are fields you can add to user accounts. In Drupal 7, those settings are on `/admin/config/people/accounts/fields`.

>

---
Tags: users
---


title: Clearing cache removed all styling

text:
# Question
Title: Clearing cache removed all styling
I'm fairly new to Drupal, but when trying to install a new module, I was instructed to clear the cache. Now, all of the styling on my website is missing and I don't know what to do.

# Answer
The webserver must not have the correct permissions to access those CSS and JS files. You need to set the correct permissions on the /sites/default/files/css and /sites/default/files/js directories. Allow read access at the very least.
> 0 votes

---
Tags: caching
---


# Question
Title: How do you use Drush to import a bunch of users via a csv file from the command line terminal?
I have a csv file of users and I would like to use the "drush user-create" command to create an account with these users and have them blocked by default with no password.

I noticed that there is a --pipe option, but I'm unsure how to use this with drush user-create to consume a csv file.

My csv file is just an email and the state:

```
peter@yahoo.com,ny
sally@gmail.com,nj
howard@bl.com,oh
billy@yes.com,wy

```

# Answer
> 2 votes
It works with this:

```
awk -F "," '{cmd="drush -y ucrt " $1 ">> output"; system(cmd)}' users.csv

```

But it wouldn't work if you have thousands of users as it takes at least a second to create one. And also I can't seem to see the output when the user account is created. Not sure why "output" isn't working. But overall it works if you need to do it like that.

* -F stands for field separator
* The single quote starts the awk language
* cmd is the command variable u designate
* system is where you run the variable *cmd*
* users.csv is the file.

---
Tags: 8, users, drush, importing-exporting
---


# Question
Title: How to send a vote using Advance Poll and Services Voting Api?
I need to expose a poll to a mobile app. After doing some research I found out that I could receive the votes, through a web service, using the services\_votingapi module, and the go-to poll to use was advpoll, or Advance Poll.

I've made a poll with several choices and added, in a services endpoint, the select\_votes and set\_votes services for votingapi. What I can't figure out now is how to send a vote using the service? there's some documentation at https://www.drupal.org/node/2145873 but I don't know the correct values to send. How do I know the correct entity ids, etc.?

# Answer
Ok, I figured out how this is supposed to work. The required JSON document to POST to the set\_votes service must be this:

```
{
  "votes":[
    {
    "entity_id":"1328",
    "tag":"f5a8bb465",
    "value":"1"
    }
  ]
}

```

entity\_id is the nid of the Advance Poll, tag is the choice\_id of the Poll Choice you want to cast the vote for, and value must always be 1, it's the vote.

In case you need to know those IDs, it may be a good idea to expose them through the node or the view services. Or use the Devel module
> 0 votes

---
Tags: 7, services, rating
---


title: Emails are not sent

text:
# Question
Title: Emails are not sent
I am running Drupal 8 on a DigitalOcean server. I am trying to use the standard Drupal 8 Contact form to get user's email addresses. I currently have the form up and it is visible and holds the information I want but when the user submits their message the form does not send an email to the address that it is set to and two pop ups tell the user that the email is not sent and the message is sent. The message is saved to the contact form storage module that I have downloaded but the email is not sent out. Can anyone help me solve this? I have checked my MX records and the email address that is used in the contact form and is a valid gmail that I have control of and is currently redirected from our server. I am unsure how to solve this issue please help

# Answer
Most likely you don't have an MTA(Mail Transfer Agent) installed/configured on your droplet. You need to install **Postfix** so that it can be used to send emails by local applications.

Below is some info from DigitalOcean tutorials library on how to install/setup/test Postfix.

How To Install and Setup Postfix on Ubuntu 14.04

How To Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 14.04

How To Install and Configure Postfix on Ubuntu 16.04

How to Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 16.04

---

Another option is to use SMTP Authentication Support module

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
> 1 votes

---
Tags: 8, emails
---


# Question
Title: How can I do a multi-level sort in Views?
I have a table format view with multiple columns/fields:

* Date
* Title
* Room

And data that looks like this table (as an example):

## | Date | Title | Room |

## | 4 June 2016 | Yellow-Green | Apple |

## | 4 June 2016 | Sky Blue | Orange |

## | 1 June 2016 | Magenta | Apple |

| 4 June 2016 | Yellow-Green | Grape |

I want to sort the data in the table at multiple levels:

1. First by Date in descending order
2. Second by Title in ascending order
3. Third by Room in ascending order

So from the data given, the table would sort in this order:

## | Date | Title | Room |

## | 4 June 2016 | Sky Blue | Orange |

## | 4 June 2016 | Yellow-Green | Apple |

## | 4 June 2016 | Yellow-Green | Grape |

| 1 June 2016 | Magenta | Apple |

Please note that the data all still needs to be in a single table, rather than splitting into multiple tables, thank you.

The effect I'm trying to achieve in how it's like in Excel -- wherein you can sort the cells by levels -- for instance, first sort by Column B, then sort by Column D, etc.

How can I achieve this in Drupal 7 views without writing/editing any code?

Thanks very much in advance for any help.

(I've edited this question to hopefully clear things up.)

# Answer
> 2 votes
1. Add all sorting cck fields (date/title/room in this case) to the 'sort criteria' section in Views UI
2. Go write a very easy custom module for yourself. Using only one hook, which is hook\_views\_query\_alter(&$views, &$query)

the .module file looks something like this:

```
function [MODULE_NAME]_views_query_alter(&$view, &$query) {
  if ($view->name == '[views_name]' && $view->current_display == '[display_name]') {
    $query->orderby = array(
      array(
        'field' => '[first_sort_cck_field_value]',
        'direction' => 'AESC',
      ),
      array(
        'field' => '[second_sort_cck_field_value]',
        'direction' => 'DESC',
      ),
      array(
        'field' => '[third_sort_cck_field_value]',
        'direction' => 'ASC',
      )
   );

//use dsm($query->orderby) to debug if you use Devel module;

  }
}

```

As an alternative, you can also try follow this post

Good luck :)

# Answer
> 1 votes
In Views, under the "Format" heading you format is already "Table", Click the Settings link, Scroll down until you see "Grouping field Nr.1" and choose date. Then use "Grouping field Nr.2" for the next one.

---
Tags: 7, views
---


# Question
Title: How to change exposed filter select box style in views
i have on exposed filter in views.it in defatult drupal select box style. how to change it like attached screenshot.

# Answer
> 2 votes
You can use fancyselect module.

> Fancy select is a jQuery plug-in developed by Octopus Creative.
>
> This module loads fancySelect jQuery plug-in, which converts simple HTML select DOM elements with a specified CSS class into a stylish select box. You may configure DOM CSS from settings form.

---
Tags: 7, views
---


# Question
Title: How to attach JSON data to JS variable without it being escaped
I'm having so much trouble with drupal 8 right now.

when in Drupal 7 I could do:

```
drupal_add_js("var a = 'b';");

```

and be done with it, for the life of my, I can't figure out how to attach data to a JS variable in Drupal 8

I had to write a custom THEME\_preprocess\_page function to add the JSON value to drupalSettings like this:

```
$variables['page']['content']['#attached']['drupalSettings']['customPricelist'] = $result;

```

but in reality the result get's escaped with quotation marks like:

```
"{"some":"stuff"}"

```

and is not usable..

Any ideas?

# Answer
> 1 votes
something like:

```
$variables['page']['content']['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with alert("Hello world!");.
       '#value' => 'alert("Hello world!");',
       // set attributes like src to load a file
       '#attributes' => array('src' => ''),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world'
  ];
}

```

# Answer
> 1 votes
The best practice of passing data to the JavaScript client is via the drupalSettings object.

```
$page['#attached']['drupalSettings']['somekey'] = [
  'anotherkey' => 'somevalue'
]

```

In JavaScript it is accessible like this:

```
var someValue = drupalSettings.somekey.anotherkey;

```

---
Tags: javascript, 8
---


# Question
Title: Content is not filter with conceptual filter in views
I am using two view one view as a page with exposed filter and another view as a block and filter the content by getting Value from url in contextual filter.

Exp:http://exp.com/?field\_project\_catagory\_tid=112&field\_nd\_portfolio\_tid=92

If we use one conceptual filter this http://exp.com/field\_project\_catagory\_tid=112

and get the value with use the PHP code in conceptual filter

$path=drupal\_get\_path\_alias($\_GET\["field\_project\_catagory\_tid"\]); return $path;

Its working fine and listed the value in both the views

If we pass one more filter then we have url Like this http://exp.com/?field\_project\_catagory\_tid=112&field\_nd\_portfolio\_tid=92 and it works collectively fine.

but if user filter with one filter it is not working.

Then how we can use the value in contextual filter for individually also. Please help

# Answer
> 0 votes
Use **all** instead of id in any one parameter if you want to consider only one parameter. e.g. like

```
http://exp.com/?field_project_catagory_tid=112&field_nd_portfolio_tid=all

```

or

```
http://exp.com/?field_project_catagory_tid=all&field_nd_portfolio_tid=112

```

---
Tags: views
---


title: How to theme form?

text:
# Question
Title: How to theme form?
I created a form in custom module,

Something like:

```
 $form['form00'] = array(
      '#type' => 'textfield',
      '#title' => 'dummy',
    );
$form['form01'] = array(
      '#type' => 'textfield',
      '#title' => 'dummy1',
    );

```

Questions are:

1. How do I theme the form? like wrapping them into some div, giving a class or id, and setting CSS property (e.g. float: left), etc.?
2. Can I control it from AJAX ? If yes,how?

# Answer
Short story for or Q1: Wrap your form01 and form02 in a container: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Container.php/class/Container/8.2.x

Then add your classes with the #attribute variable like here:

```
'#attributes' => array(
    'class' => 'myclass',
  )

```

For Q2: It's a long story, read this: Ajax API on Drupal

Regards,

Rainer
> 2 votes

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


# Question
Title: Adding Content to the top of a form Page
I just want to add an easily editable block of content to the top of a Form page in Drupal 8.

This can either be adding text to the form or adding the form to a content item, I don't mind.

What's the most straight forward way of doing this?

# Answer
> 0 votes
Create a simple block (`/block/add?destination=/admin/structure/block/block-content`) and make it appear on the form's page.

If you can not setup the necessary restrictions for the block to appear, you have to go for hook\_form\_alter (but this means programming your own module).

---
Tags: forms, 8
---


title: Add attribute to main menu item

text:
# Question
Title: Add attribute to main menu item
In my project I would like to add the following attributes to my "Login" main menu item:

`data-toggle="modal" data-target="#login-modal"` (Am using the Bootstrap theme)

I checked out the menu attribute module but it does not allow for these attributes.

Please is there a way?

# Answer
> 4 votes
You can use this HOOK\_menu\_link\_alter and add new attribute from there.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_menu\_link\_alter/7

```
function MYMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/login') {
    $item['options']['attributes']['data-toggle'] = 'modal';
    $item['options']['attributes']['data-target'] = '#login-modal';
  }
}

```

Note : Make sure you clear cache and are checking this for anonymous user.

# Answer
> 0 votes
You can change the menu attribute module

If you are in drupal 7 Just install and enable menu attribute module module then go to module directory and edit menu\_attributes.module to add following lines to menu\_attributes\_menu\_attribute\_info() function

Before return $info; line

```
//Added by ErangaJ
$info['data-toggle'] = array(
'label' => t('Data toggle'),
'scope' => array(MENU_ATTRIBUTES_LINK, MENU_ATTRIBUTES_ITEM),
);
$info['data-target'] = array(
'label' => t('Data target'),
'scope' => array(MENU_ATTRIBUTES_LINK, MENU_ATTRIBUTES_ITEM),
);

```

# Answer
> -1 votes
You can use drupal module Bootstrap login modal

> Adds a login and register link in the nav bar. Opens them in Bootstrap Modals.
>
> This module is intended for use with the Bootstrap theme.
>
> By default the login and register links are added to the navigation region, but they can be moved on the block admin page.

---
Tags: routes
---


# Question
Title: Use Token in contact form as default value
I have a contact form build from the drupal core contact forms.

I am trying to prefill some fields from URL GET parameters like this. `/?foo=bar` But it seems that "default value" doesnt support tokens.

I want to use something like this: `[current-page:url:args:value:foo]` in the default field of my form field.

But this gets just rendered as plain text. Any help is appreciated.

EDIT: Working solution with form\_alter:

```
function MY_MODULE_form_alter(&$form, &$form_state) {
  $args = \Drupal::request()->query->all();
  $form['field_test']['widget'][0]['value']['#default_value'] = $args['foo'];
}

```

Maybe there is a solution with tokens relating to the topic?

# Answer
Usually this is done in hook\_form\_contact\_site\_form\_alter, like this:

```
function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
      $args = \Drupal::request()->query->all();
      $form['subject']['#default_value'] = $args['foo'];
}

```
> 1 votes

---
Tags: 8, tokens, emails
---


title: How to preprocess Bootstrap region

text:
# Question
Title: How to preprocess Bootstrap region
I am using Panels Bootstrap Layouts. I insert bootstrap\_twocol\_stacked into the $content region.

I'd like to be able to access regions of that Bootstrap layout (Top, Left, Right, Bottom) in my page.tpl.php template to restructure the HTML code, but I only seem to have an access to the content. $page\['content'\]\['system\_main'\]\['content'\]\['#markup'\] variable when run e.g.

```
function theme_preprocess_page(&$variables) {
  dpm($variables);
}

```

only contains rendered HTML code and does not give me option to access Bootstrap data as array, like $page\['content'\]\['\***'\]\['top'\].

I tried to look for a preprocess hook (probably one of the panels module function), but could not figure out which one.

Any hints?

What I am trying to do is to move the bootstrap region to the same hierarchy level in the page.tpl.php as other page regions, see the image below.

# Answer
> 0 votes
Here the solution, if somebody is interested:

create new section in your theme, call it e.g. bottom-section and use this preprocess hook to move the content of the bottom pane to bottom-section section

```
function theme_preprocess_panels_pane(&$variables) {
  if ($variables['pane']->panel == 'bottom') {
    // Move to a region
    drupal_add_region_content('bottom-section', $variables['content']['#markup']);
    // Delete the pane from the panel
    $variables = array();
  }
}

```

---
Tags: panels, theming
---


# Question
Title: Commerce Product is not visible for anonymous user in search result
I am using apachesolr, apachesolr\_commerce, apachesolr\_autocomplete for search functionality in drupal 7. Commerce Product is not visible for anonymous user in search result but when loggedin Commerce Product results are including into search results. Any suggestions?

# Answer
Got solutions to Disable Apache Solr Access module and than search works fine for other users as well. Thank you.
> 0 votes

---
Tags: 7, commerce, search
---


# Question
Title: Visibility problem with 'restricted to certain pages'
I'm porting a site from D6 to D8 and having problems with block visibility for listed pages. I have a config like this which worked on D6:

```
news
news/*

```

And pages like `/news/op-ed-suu-kyis-plan-outsource-myanmars-presidency-problems-proxy` would match and display the block. In D8.1.2 I have the same rules, but the migrated page with the same URL doesn't trigger the block. If I remove the rules, the block displays again, so it's definitely something here.

Am I missing some changes in how D8 handles these rules? or is it maybe something with URL aliases?

# Answer
Of course! Now that Drupal 8 returns URL aliases with the leading slashes, I needed to update my rules to:

```
/news/
/news/*

```

to get it working as in D6
> 2 votes

---
Tags: 8, blocks
---


# Question
Title: Can I organize my custom module's twig templates into subfolders?
My module now has a lot of TWIG template files in the `/custom/MYMODULE/template` folder. I tried creating some sub-folders because I thought Drupal 8was supposed to search all sub-folders automatically but I got an error about a missing template file. Should it work?

I've tried setting the subfolder name in `'#theme' => 'SUBFOLDER/mytemplate'` and I don't get an error, but the block contents are just blank (although the title displays).

I have my template defined in `MYMODULE_theme()`, but it feels wrong to specify a sub-folder in there.

# Answer
This is what the docs for `hook_theme` say about the `template` property:

> If specified, the theme implementation is a template file, and this is the template name. Do not add 'html.twig' on the end of the template name. The extension will be added automatically by the default rendering engine (which is Twig.) If 'path' is specified, 'template' should also be specified. If neither 'template' nor 'function' are specified, a default template name will be assumed. For example, if a module registers the 'search\_result' theme hook, 'search-result' will be assigned as its template name.

Unless you've found a bug of omission, I would expect these docs to tell you if there was any auto-scanning of sub-folders going on. The fact that you've tried it and it doesn't work might be seen to back that up.

If you've seen other official docs that reference an auto-scanning feature, you may have hit a bug.

As an aside, I'm not sure what the intent of this code is:

```
'#theme' => 'SUBFOLDER/mytemplate'

```

You would never write that; you would instead use `hook_theme` to register your template with the system, and put the path to the file itself in the `template` property. Then you'd use:

```
'#theme' => 'theme_key'

```

in the render array
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to hide a block in a view when an exposed filter is being applied?
I have built a view with exposed filters. There is a 'popular content' block on this page which I am controlling using the Context module (https://www.drupal.org/project/context)

I would like it so that the popular content displays, but only if no filters are being applied to the view. If a filter is applied then the block should not show.

I can see that the Context module has a query string condition option which I've tried to apply but without success. I've tried adding things like `~?title=*` or `~*?title=**` here but I can't seem to get the behaviour I'm after.

Any help would be appreciated.

**UPDATE**

I've used the answer from @Pierr.Vriens to create a rule component. However, the block now isn't showing on the /MyViewPath page (which is `/courses` on my site). I've put the export of the rule I created below. I'm surprised that it's not showing on the page now at all. The block is being set in the correct region, the 'rules' component has been added to the block settings itself and I've disabled the context module from messing with it too.

Here is an export of the rule I created:

`{ "rules_block_visibility_popular_courses" : {
 "LABEL" : "Hide block for filtered course view",
 "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" : [
 { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "courses " } }
 ],
 "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
 "PROVIDES VARIABLES" : [ "result" ]
 }
}`

**UPDATE 2**

So it was the space at the end of `"courses "` that was causing the problem. The exported rule below did the trick:

`{ "rules_block_visibility_popular_courses" : {
 "LABEL" : "Hide block for filtered course view",
 "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" : [
 { "text_matches" : {
 "text" : [ "site:current-page:url" ],
 "match" : "courses",
 "operation" : "ends"
 }
 }
 ],
 "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
 "PROVIDES VARIABLES" : [ "result" ]
 }
}`

# Answer
> 1 votes
You can use the Rules block visibility module for this. 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 "***check the path of the current page***" (so that the block is only shown for the page with an URL that matches with your view without any filters applied).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to administrators, such as user/1?". If you look at the example included there, just replace its Rules Condition by a *Text comparison* with `Parameter: Text: [site:current-page:path], Matching text: MyViewPath` (assuming that `/MyViewPath` is the path of your view without any filters applied).

**Update**: looking at your exported rule (in revision 3 of your updated question, so without "UPDATE 2" you added to it ), I noticed that there is a ***space*** (blank) at the end of `"course "`. Not sure why that is there, but I'd first try with removing that space. If that doesn't make a difference, I suggest you try a variation of your rule that looks like so (only the Rules Condition differs from what you have in your updated question):

```
{ "rules_block_visibility_popular_courses" : {
    "LABEL" : "Hide block for filtered course view",
    "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-page:path" ], "value" : "courses" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

If that also doesn't help, then it's time for Rules debugging. For that, refer to my answer to "How can I display the value of a variable inside a condition?".

PS: This answer applies to D7 ...

---
Tags: blocks, views
---


# Question
Title: Make a node field read only after the node has been created
I'm building a Drupal 8 module which will create several content types (with several fields) when the module is installed. The content types, field storages field instances, form displays & view displays are created with yml files in mymodule/config/install.

More details on the content types and fields:

* Let there are two node types, A and B.
* B has field called *reference* which is required, can have 1 value and the reference is to a node of type A. So basically B always has exactly one parent of type A.

What I want to do is to make the reference field read-only after the node is created.

In Drupal 7 I did this with Form API and hook\_node\_validate basically as follows:

* I first checked if the form submission was for a new node or an existing node
* If it was an existing node, I loaded the node (which is the node before the form submission at hand) and compared the value of the form submission to the value found on the actual node.
* If the values were not the same, I returned an error.

Now, in Drupal 8 we have the Validation API which is really good thing because it kicks in with also other mechanisms than form submits. I'm only wondering how to implement the read-only locking described above.

Should I create a Constraint Plugin which would do similar loading of the previous version like I explained above and add that constraint with `hook_entity_bundle_field_info_alter()` or is there some other way?

Edit: Just to clarify, I'm interested to make the reference field non-editable on data level so that the value can't be changed even if updating the node programmatically. In other words, just making the field read-only on UI level on node edit form is not enough.

# Answer
After educating myself on the Validation API, here's an example how to add the constraint to validate that the value of an entity reference field has not been changed.

Note: As pointed out by Ivan Jaros, this constraint is not validated if some module is programmatically saving entities without validating the entities first via Validation API.

1. Add a new constraint plugin.

```
/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraint.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Constraint for checking that the value has not been changed.
 *
 * @Constraint(
 *   id = "ValueNotChanged",
 *   label = @Translation("Value has not changed", context = "Validation"),
 *   type = { "string", "entity:node" }
 * )
 */
class ValueNotChangedConstraint extends Constraint {

  /**
   * Message shown when the validation fails.
   *
   * @var string
   */
  public $message = 'Reference value can not be changed.';

}

```
2. Add validator for this constraint.

```
/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraintValidator.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Validates the ValueNotChangedConstraint.
 */
class ValueNotChangedConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  protected $entityTypeManager;

  /**
   * Constructor.
   *
   * @param EntityTypeManagerInterface $entity_type_manager
   *   EntityTypeManager service for loading entities.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager  = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this class.
    return new static(
      // Load the service required to construct this class.
      $container->get('entity_type.manager')
    );
  }

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;

  /**
   * {@inheritdoc}
   */
  public function validate($data, Constraint $constraint) {
    $violation = $this->validateValueNotChanged($data, $constraint);
    if ($violation instanceof ConstraintViolationBuilderInterface) {
      $violation->addViolation();
    }
    return;
  }

  /**
   * Validates that the value is the same than previously.
   *
   * @param EntityReferenceFieldItemListInterface $data
   *   List of referenced entities.
   * @param Constraint $constraint
   *   Our constraint.
   *
   * @return \Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface
   */
  protected function validateValueNotChanged(EntityReferenceFieldItemListInterface $data, Constraint $constraint) {
    // Get the field name of the field we're validating.
    $field_name = $data->getFieldDefinition()->get('field_name');

    // Get the entity the field belongs to.
    $parent_id = $data->getEntity()->id();

    // Entities that are about to be created don't have an ID at this point.
    // We're only interested in existing entities.
    if ($parent_id) {

      // Load the parent node from the database. The new updates are not saved
      // yet so this will be the "old" version of the entity.
      $parent = $this->entityTypeManager->getStorage('node')->load($parent_id);

      // Get the old value we want to compare against.
      $old_value = $parent->get($field_name);

      // Compare the field item lists.
      if (!$old_value->equals($data)) {
        return $this->context->buildViolation($constraint->message);
      }
    }
  }

}

```
3. Add the constraint to the desired field with hook\_entity\_bundle\_field\_info\_alter().

```
/**
 * Implemeantion of hook_entity_bundle_field_info_alter().
 *
 * Adds constraint to field_example_reference field.
 */
function example_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle){
  switch ($bundle) {
    case 'our_content_type':
      $fields['field_example_reference']->addConstraint('ValueNotChanged');
      break;
  }
}

```
> 0 votes

---
Tags: forms, 8
---


# Question
Title: How to add custom class to a <ul><li> fileds on the renderable array of user_profile_form
I have a requirement to add a class to ul li on the user\_profile\_form edit page on admin side. Using Hierarchical Select Taxonomy module regions are listed on this form.The purpose is to modify the listing of the regions by adding different classes for the regions based on the taxonamy id.

# Answer
You can do it 2 ways. One is to modify the element attributes, like this:

```
$form['textfield'] = [
  '#type' => 'textfield',
  '#attributes' => [
    'class' => [
      'ul',
    ]
  ],
];

```

Or, another way, wrap the elements with '#prefix' and '#suffix'.

```
$form['textfield'] = [
  '#type' => 'textfield',
  '#prefix' => '<div class="ul">',
  '#suffix' => '</div>',
];

```

I would use the first preferably when I can.
> 0 votes

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


title: Changing upload size

text:
# Question
Title: Changing upload size
I tried all solutions from google and i can not figure out how to increase from 2 MB to 70MB.

In WHM i did changes like from screenshots:

On the Drupal site, it went up to 8MB; whatever I tried with .htaccess, settings.php, it won't go more then 8. Adding php.ini to the Drupal root folder throws a fatal error.

I tried changing file upload size on image field to 65 and 75 MB, it gets saved but on node add, it still says 8 MB

How can I change the upload size globally ? I have access to WHM, Cpanel, SSH, FTP, root, whatever. Server is private, dedicated. Many mentioned changing php.ini, but where is it ? On various answers its on various places and i want to change this globally.

# Answer
> 1 votes
You may need to increase the post\_max\_size value in php.ini

# Answer
> 1 votes
It seems to me your problem has to do with your php.ini: at worst, Your server should ignore it (it would be useful to know a little bit more about your server environment: shared? Godaddy?).

Here's what your php.ini should have (exclusively):

```

; Maximum size of POST data that PHP will accept.
post_max_size = 70M

; Maximum allowed size for uploaded files.
upload_max_filesize = 70M

```

It would be useful if you posted your php.ini file, to understand your problem better.

# Answer
> 0 votes
Probably the max size on the file field configuration needs increasing. You must increase both. Also check the effective size limit at /admin/reports/status/php. You may not be able to exceed a pre-set maximum without contacting the hosting provider.

# Answer
> 0 votes
Keep in mind that Drupal has settings for the maximum size allowed for uploaded files in different places.

For example, in admin/config/people/accounts you set the maximum size the file for the image associated with user accounts can have, both as dimensions in pixels and as file size.

>

For content types with a field to upload and attach an image to its nodes, there is a setting for that field. (See admin/structure/types/manage/article/fields/field\_image for the *Article* content type and its default *Image* field.)

>

In the case the file size is not set, users will be allowed to upload a file basing on the upload limits set in PHP. (In my case, that is 2 MB, as reported from the field description.)

The same is true when a content type has a field to upload a file.

>

The same is true for other entities to which is possible to add a file for uploading a file or an image. Each field, for each entity, and each bundle of that entity, has a setting for the maximum size of the uploaded files.

So, it can be the PHP settings has been effectively changed, but Drupal is still using its limits set in different places. To be sure, go to admin/structure/types/manage/article/fields/field\_image (if you didn't remove the content type or altered the *Image* field): Drupal will tell you the limit set by PHP.

>

# Answer
> 0 votes
Like @kmbremner and @Antonio Hernandez answered post\_max\_size should be increased also. Here is a screenshot for newbies in WHM like myself.

In PHP configuration editor, switch to advanced mode and close to the bottom you will find post\_max\_size which was 8M by default. Do not forget that you need to change max\_upload\_filesize also.

In Drupal if you leave max file size blank for an upload field (image, video, file), it will read global php values.

---
Tags: 7
---


# Question
Title: management menu invisible for the second administrator
I am using Drupal 7.26, and I need a second administrator user. I created a user who can see the authenticated user's menu, but not the management menu which I (as user #1) can see.

How can I fix this? I want the user I created with administrator role to have access to everything from the management menu.

# Answer
> 0 votes
The page under admin require the *access administration pages* permission, or the *administer themes* one. (See `system_menu()`, the `'access arguments'` lines.)

```
  $items['admin'] = array(
    'title' => 'Administration',
    'access arguments' => array('access administration pages'),
    'page callback' => 'system_admin_menu_block_page',
    'weight' => 9,
    'menu_name' => 'management',
    'file' => 'system.admin.inc',
  );
  $items['admin/compact'] = array(
    'title' => 'Compact mode',
    'page callback' => 'system_admin_compact_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
    'file' => 'system.admin.inc',
  );
  $items['admin/tasks'] = array(
    'title' => 'Tasks',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['admin/index'] = array(
    'title' => 'Index',
    'page callback' => 'system_admin_index',
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
    'file' => 'system.admin.inc',
  );

  // Menu items that are basically just menu blocks.
  $items['admin/structure'] = array(
    'title' => 'Structure',
    'description' => 'Administer blocks, content types, menus, etc.',
    'position' => 'right',
    'weight' => -8,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
  );
  // Appearance.
  $items['admin/appearance'] = array(
    'title' => 'Appearance',
    'description' => 'Select and configure your themes.',
    'page callback' => 'system_themes_page',
    'access arguments' => array('administer themes'),
    'position' => 'left',
    'weight' => -6,
    'file' => 'system.admin.inc',
  );

```

The user you create must have a role with the right permission. Go to admin/people/permissions and assign to the role of that use the necessary permissions, listed under *System*.

Keep in mind that the user #1 has every permission, independently from the roles it has. If you are wondering why there is a difference between the user you created and the user you normally use, even if they have the same role, that is the reason. Drupal check the currently logged-in user is the user #1, as visible in the code for `user_access()`.

```
  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

```

User #1 could not have any extra role, and simply be an authenticated user, and still it would have all the permissions, contrary to the normal authenticated users, who have just the permissions you assign to the *authenticated user* role.

# Answer
> 0 votes
1.I found from the database and from table "users" the uid that belongs to the user i want to be an administrator. 2.I found the file user.module here: mysite/modules/user/user.module 3. I changed the following code : // User #1 has all privileges: if ($account-\>uid == 1 || $account-\>uid == my\_uid ) { return TRUE; } and it's worked.

---
Tags: 7, users
---


# Question
Title: Access page.tpl.php variables from html.tpl.php
I've got a well-established theme that's building a lot of variables for the page template, ie. $variables\['page'\]\['stripe\_color'\] = $some\_node\_data; However, now I'd like to apply this variable to the body tag; so, it needs to be communicated to html.tpl.php

I know there's a bunch of ways to this, store it in a global, reevaluate in the theme\_preprocess\_html, but I'm wondering if there's a simple variable somewhere that's available that I'm not finding.

# Answer
Sounds like a perfect use case for the more generic `hook_preprocess`:

```
function MYTHEME_preprocess(&variables, $hook) {
  if ($hook == 'page' || $hook == 'html') {
    $variables['shared_var'] = 'foo';
  }
}

```

`$shared_var` will be available in both html.tpl.php and page.tpl.php. This will be processed twice, so if it's expensive to build the vars, make sure you statically cache them.
> 0 votes

---
Tags: theming
---