# Question
Title: Google Analytics Reports: how to remove pageviews for Top Pages and add published date
I've installed google analytics reports to be able to see the most viewed nodes of my website. I were able to add the Top Pages view to my home page but i wanted to know how can i :

1. add published date
2. remove the number count and leave the title only.

See image

# Answer
You're looking a one difficult task & one simple one. Starting with the simple one (reverse order):

1. The **Top Pages** area is a block that's installed with the module. The *Google Analytics Reports Summary (Google Analytics): Top Pages* view can be configured in the Views UI (**/admin/structure/views/view/google\_analytics\_reports\_summary/edit/attachment\_top\_pages**). To remove the views count you can click the *Page Tracking: Pageviews* field and use the **Remove** button or **Excluded from display** checkbox to get rid of it.
2. Adding the publish data is a bit harder because what the underlying View is querying. The view is querying data tables from your Google Analytics account. As such, there is no Drupal node data to display from the query. Normally, the Views way to solve this would be to add a relationship with the node table then reference the publish date. However, the module doesn't provide a relationship handler to node content so you're looking a couple things here:
    1. Select a Google Analytics field that can be joined on the node table. *Page Tracking: Page* is a close candidate here as it contains a unique path used for the node link. Nid would be better, but that data isn't sent to Google Analytics by default (you'd have to configure a GA custom variable).
    2. Once you have a selected joined field. You'd have to build your custom relationship handler on which you can join to the node table to retrieve the publish date.
> 1 votes

---
Tags: 7, views, google-analytics, log-messages
---


title: Site url token in view

text:
# Question
Title: Site url token in view
Are there any way to get site's base URL value in a token within view to use in its header and field(s).

My local developments is on drupal installation in a sub-directory while on server it is on a domain.

# Answer
> 2 votes
You can use `global $base_url;` if you are using the PHP filter.

# Answer
> 1 votes
You may use https://www.drupal.org/project/views\_base\_url

1. Add field Global: Base url
2. Hide it
3. Use token \[base\_url\] D7 {{ base\_url }} D8

# Answer
> 0 votes
I don't know how to get a token with the base URL but if you are rewriting links, etc. you can start with a slash like `href="/mydirectory/mypage` and Drupal will automatically add the base URL.

# Answer
> 0 votes
In No results behavior I have selected Global: Unfiltered text, and

```
< a href = "/search-landing-sell-property-type"> Click here </a>

```

results in the correct path to the page.

---
Tags: 7, views, tokens
---


title: View Content inside of User edit form

text:
# Question
Title: View Content inside of User edit form
I created a view content about active classes and now I want to show them inside of user edit form to that they can see their clasess active with a contextual fiter url at view content, how can I make that? please help

# Answer
You need to pass a contextual filter in the view of User ID, and pass the User ID from url as the value. It doesn't matter if this path is aliased, as it will look at the system path (user/uid) to get the value.

Then, the view will filter content based on relationship to that user id.

Without much more information, that is all I can give you to go on. But if it is a basic setup, that should work.

See: https://www.drupal.org/node/1578564

Then to show it on the form, it depends on what or where you want it.

One way would be to create a Block display of your View, and place it in a region on the block admin page. Be sure to set the visibility to authenticated roles, and the path to 'user/\*/edit' so it only shows for users on the user edit form.

Another way, if you want to code it, would be embedding the output into the form with views\_embed\_view inside of a hook\_form\_alter for the user edit form. There are some examples on that doc page on how to use it.

Example:

```
$form['classes'] = [
  '#markup' => views_embed_view('your_view', 'block_display_id', $user_id);
]

```

Where `$user_id` is the user viewing the form.
> 2 votes

---
Tags: 7, forms, views
---


title: Site won't display after logging in

text:
# Question
Title: Site won't display after logging in
OK, so I have a weird one that I have never seen before. I have about 15 Drupal sites setup locally that are all running fine. I am attempting to setup a new one that I am setting up from a Drush archive dump that was given to me. I have used this method plenty of times in the past.

I am on a Windows 7 box and am running WAMP server v2.5. Apache v2.4.9, PHP5.5.12 and MySQl 5.6.17. So, I create the database, create the entry in my HOSTS file and create the entry in my Apache httpd-vhosts.conf file. I tweak my settings.php file with the correct dB connection info and attempt to go to the site and the site comes up just fine.

I can view the homepage. If I attempt to go to something like local.mysite.com/admin, I get "Access Denied" as expected. However, if I go to local.mysite.com/user and then login with user 1, I get "This site can’t be reached - ERR\_CONNECTION\_RESET" in Chrome and then I continue to get that even if I attempt to go to the homepage again. If I go to local.mysite.com/user/logout, it will successfully log me out and then the home page comes up again just fine. It only won't display when I login.

I thought maybe it was the temp directory, but I used Drush to check what that was set at and made sure I had that on my local box. I checked the PHP logs, the Apache logs and the MySQl logs and nothing jumped out at me as out of the ordinary. I also checked to make sure the .htaccess files were in place. I also checked this in multiple browsers and got the same result. I also tried changing the name of the site from local.mysite.com to "foo" in my HOSTS file and in Apache and restarted Apache and the site comes up, but it does the same exact thing. The site cant be reached as soon as I login. I'm at a total loss here.

# Answer
Couple things you can try.

1. Clear the session table, as it sounds like there may be some preexisting sessions left over from the archive.
2. Clear the cache tables as well
3. Make sure the folders/files are owned by the Apache user
> 0 votes

---
Tags: installation
---


# Question
Title: The website is way too slow Error while sending QUERY packet. PID=11597 in /home/******/public_html/sites/all/modules/apdqc/apdqc.mysql.inc
all the pages on the website are taking more than 1 minutes to be displayed, and sometimes they are showing Connection Reset, I had a previous issue which caused the server to be down once I clear the cache / enable a module and to solve it I have added the Asynchronous Prefetch Database Query Cache Module, I have even switched to a new Server.

Error that's being logged is the following:

```
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11602 in /home/****/public_html/includes/database/database.inc on line 2204
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11592 in /home/****/public_html/sites/all/modules/apdqc/apdqc.mysql.inc on line 871
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11592 in /home/****/public_html/includes/database/database.inc on line 2204
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11593 in /home/****/public_html/includes/database/database.inc on line 2204
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11597 in /home/****/public_html/sites/all/modules/apdqc/apdqc.mysql.inc on line 871
[27-Sep-2016 14:55:10 UTC] PHP Warning:  Error while sending QUERY packet. PID=11597 in /home/****/public_html/includes/database/database.inc on line 2204

```

Setting / specification of server and website are right below:

* Drupal 7
* PHP Version 5.6.x
* realpath\_cache\_size 150k
* realpath\_cache\_ttl 4000
* memory\_limit 1200M
* Apache 2.4
* MYSQL DB Server Version 5.6.X

> $conf\['cache\_backends'\]\[\] = 'sites/all/modules/apdqc/apdqc.cache.inc';
>
> $conf\['cache\_default\_class'\] = 'APDQCache';
>
> $databases\['default'\]\['default'\]\['unix\_socket'\] = '/var/lib/mysql/mysql.sock';
>
> $databases\['default'\]\['default'\]\['host'\] = NULL;
>
> $conf\['lock\_inc'\] = 'sites/all/modules/apdqc/apdqc.lock.inc';
>
> $databases\['default'\]\['default'\]\['init\_commands'\]\['innodb\_lock\_wait\_timeout'\] = "SET SESSION innodb\_lock\_wait\_timeout = 100";
>
> $databases\['default'\]\['default'\]\['init\_commands'\]\['wait\_timeout'\] = "SET SESSION wait\_timeout = 1000";
>
> $databases\['default'\]\['default'\]\['init\_commands'\]\['read\_rnd\_buffer\_size'\] = "SET SESSION read\_rnd\_buffer\_size = 8388608";
>
> $conf\['session\_inc'\] = 'sites/all/modules/apdqc/apdqc.session.inc';
>
> $databases\['default'\]\['default'\]\['init\_commands'\]\['isolation'\] = "SET SESSION tx\_isolation='READ-COMMITTED'";
>
> $databases\['default'\]\['default'\]\['init\_commands'\]\['join\_buffer\_size'\] = "SET SESSION join\_buffer\_size = 8388608";

in an Average day, we have almost 300 concurrent users. the Process Manager is showing a huge CPU % usage from the following COMMAND

```
/usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/lib/mysql/****.*******.***.err --open-files-limit=10000 --pid-file=/var/lib/mysql/****.*******.***.pid

```

What I want is to know how to track what is the issue here? and why there's this huge of CPU Usage, and how to stop the Connection Reset of the pages / elements inside the website?

PS: I have disabled the ERROR logging, access log, no devel module is added, the cron is set to be run every day at midnight, my status report has zero errors/notices related to apqdc and there's an Expire caching module, in addition to XMLSITEMAP, and Metatags

**\[edit\]**

* Model: HP - DL180 G9
* Processor: 2x Intel Hexa-Core Xeon E5-2620v3 \[ 6 Core(s) \]
* RAM: 64 GB
* HDD: 2x 480GB
* Linux CENTOS 7.2
* WHM version 58.0

my.cnf information:

```
core file size          (blocks, -c) 1000000
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 256494
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 4096
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 14335
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

default-storage-engine=MyISAM
innodb_file_per_table=1
performance-schema=0
max_allowed_packet=268435456
open_files_limit=107000
innodb_buffer_pool_size=5G
innodb_checksum_algorithm=crc32
innodb_flush_method=O_DIRECT
innodb_read_io_threads=50
innodb_spin_wait_delay=30
innodb_sync_spin_loops=200
innodb_write_io_threads=20
metadata_locks_hash_instances=256
binlog_format=ROW
innodb_flush_log_at_trx_commit=2
innodb_autoinc_lock_mode=2
table_open_cache_instances=250
table_open_cache=10000
thread_cache_size=100
max_user_connections=800
max_connections=7000
innodb_lock_wait_timeout=25
wait_timeout=600
read_rnd_buffer_size=8388608
join_buffer_size=8388608
query_cache_size=2000000

```

php.ini information:

```
 max_execution_time = 200
max_input_time = 120
memory_limit = 250M

```

# Answer
The php errors you listed happen in core and in apdqc. This php bug report points to the max\_allowed\_packet being too small. The php memory limit shouldn't cause the issue you are describing. Another cause could be a low wait\_timeout value, but you are setting that to 1000.

If you can move the 'init\_commands' from the settings.php into your my.conf file that has a small chance of improving your issue. You can remove them and then go to the status report page and apdqc should tell you what to add to my.conf.

In terms of getting to the bottom of this issue; knowing the stacktrace of what caused this is key. This core patch is a must: Add backtrace to all errors and add `$conf['error_level'] = 2;` to your settings.php file. If you have syslog use that, if not re-enable the dblog in order to log this issue.
> 0 votes

# Answer
Reduce the php memory limit to no more than 512M. Depending on the version of PHP you have, anything higher (even 512) is ineffective and can cause issues.

Secondly, completely uninstall `apdqc` module, and see if that alleviates the issue.

Third, profile your application with xhprof and/or New Relic and/or Blackfire.io.

Without knowing more about your setup, you might want to review the issue queue for APDQC module to narrow down what the issue could be:

https://www.drupal.org/project/issues/apdqc?categories=All
> 1 votes

---
Tags: database, caching, meta-tags
---


# Question
Title: Is there a hook to alter webform confirmation message?
In Drupal 7 using webforms, is there a `hook` that can alter the outgoing confirmation message shown to someone who has just submitted a form?

My thoughts are to put a text placeholder inside this textarea and do a `str_replace` to update the output based the submission itself.

# Answer
A solution for using submissions value in Submission confirmation message is using Webform Tokens module.

And another solution as you asked is using hook\_form\_alter add your custom submit handler ( make sure yours getting run before webform's default) change the submitted string with what you want.
> 2 votes

# Answer
Like the @zhilevan told you can use hook\_form\_alter for placeholder and for `str_replace` you can implement `hook_template_preprocess`.

Here is an example.

```
function my_module_preprocess_webform_confirmation(&$vars) {

    $confirmation = check_markup($vars['node']->webform['confirmation'], $vars['node']->webform['confirmation_format'], '', TRUE);
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    $submission = webform_get_submission($vars['node']->nid, $vars['sid']);
    $confirmation = _webform_filter_values($confirmation, $vars['node'], $submission, NULL, FALSE, TRUE);

   // Strip out empty tags added by WYSIWYG editors if needed.
   $vars['confirmation_message'] = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';

}

```

Source Webform Token support on confirmation message.

you can also take a look on tpl file option. Here webform-confirmation.tpl.php
> 4 votes

---
Tags: 7, webforms, forms
---


# Question
Title: How do I change the HTML surrounding a particular node?
I'm new to Drupal and have been tasked with fixing some HTML on a page.

There are 3 seperate sections on this page, one of which needs a couple of new classes. I've identified the section I need to change is Pane within a Node (I think). However, I cannot find what .tpl file actually influences the output of this.

How do I find out which .tpl file houses the HTML for a given Pane?

# Answer
> 1 votes
Enable theme\_debug mode, once it is done you can find which .tpl file the particular section in the **firebug**. For enabling theme debug mode **`drush vset theme_debug 1`**

In the firebug, you can find which .tpl file the section is using.

---
Tags: theming, panels
---


# Question
Title: Custom module wiped out all content of type
I've recently written a custom module for my site that deletes nodes older than two years whenever cron runs. It worked perfectly!

However a few weeks later, after updating Drupal 8 to 8.1.10, all the nodes of type "recent" were deleted! I don't know if it is connected to the module or not, but I have a hunch that it is.

Here is the .module file:

```
<?php

function delete_old_nodes_cron() {

        $node = $variables['node'];

        $query = \Drupal::entityQuery('node')
        ->condition('created', strtotime('-2 year'), '<=')
        ->condition('type', 'recent');
        $nids = $query->execute();
        foreach ($nids as $nid) {
            $node = node_load($nid);
            $node->delete();
        }
}
?>

```

and the .info.yml file:

```
name: Delete old nodes
description: Deletes nodes older than 2 years.
package: Custom
type: module
version: 1.0
core: 8.x

```

# Answer
> 3 votes
Your query seems to be ok, irrespective of drupal version it should work. Here are the few pointers to debug.

1. Check the query output, is your query returning all nodes of type 'recent' without filtering by created

```
function delete_old_nodes_cron() {
  $query = \Drupal::entityQuery('node')
      ->condition('created', strtotime('-2 year'), '<=')
      ->condition('type', 'recent');
  $nids = $query->execute();
  dpm($nids);
}

```
2. Make sure for your recent created nodes created time is not altered somewhere.

---
Tags: 8
---


title: Open messages in Bootstrap modal

text:
# Question
Title: Open messages in Bootstrap modal
I use bootstrap theme, and I want to open messages in bootstrap modal; after searching, I found the Bootstrap Modal Messages module, which is not available for Drupal 8.

Is there any way for Drupal messages to appear in a Bootstrap modal?

# Answer
> 2 votes
This can be done by twig template and jquery. Add only 'Status messages' block on 'Highlighted' region. and in the twig template add like below:

```
{% if page.highlighted %}
          {% block highlighted %}

            <div class="modal fade" id="modal-div">
              <div class="modal-dialog" role="document">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title">Message</h4>
                  </div>
                  <div class="modal-body">
                    {{ page.highlighted }}
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  </div>
                </div>
              </div>
            </div>

          {% endblock %}
        {% endif %}

```

After that in jquery file :

```
$(window).load(function(){
    if($.trim($("#modal-div .region-highlighted").text()) != ''){//region will be printed even if the highlighted area is blank
        $('#modal-div').modal('show');
    }
});

```

This will show your messages in modal window.

# Answer
> 1 votes
Drupal at the end of the day outputs HTML just like any other non Drupal site.

If you look at the Modal Messages Documentation all you have to do is add modal html attributes (ex: `data-toggle="modal"` or `class="modal fade"`) to your Drupal message divs.

If you look at the D7 module, all the "magic" (adding the attributes) is done through jQuery.

---

Alternatively, you can add the attributes by adding the following to your **themename.theme** file

```
function themename_preprocess_page(&$variables) {

  if (!empty($variables['page']['highlighted'])) {
    $variables['page']['highlighted']['#attributes']['class'][] = 'modal fade';
    $variables['page']['highlighted']['#attributes']['data-toggle'][] = 'modal';
  }
}

```

The above will work as long as your `Status messages` block is placed in the Highlighted region in `/admin/structure/block`.

---
Tags: 8, theming
---


# Question
Title: Remote entities versus local entities for third party integration
While integrating any third party tool with its own data storage capabilities, I usually end up with a question

So far I could figure out following Pros and Cons in both the cases.

**PROS for storing on Drupal(local entities):**

* Easy reporting with views.
* Being local entites to Drupal, we can leverage drupal out of the box functionalities like add/edit/delete forms.

**CONS for storing on Drupal(local entites):**

* It creates dependency on Drupal, while the third party tool has all possible capabilities to run as standalone application.

**Another possible option could be storing at both places Drupal and third party tool**

* But that would cause data syncronisation problem, and will require development at both ends to push data changes.

An example of such integration I recently came across is Camunda(BPM tool).

What will be a suitable place for data storage? Should we keep it on Drupal, or should we leverage third party storage capabilities?

# Answer
> 1 votes
Personally, I go usually with a caching system within Drupal. How this is implemented really depends on the external system, and how it works, but essentially I'll pull the data from the external source when first requested, and save it within Drupal somehow, whether that be into a node, or a custom entity, or some other data entity unrelated to Drupal entities.

The reasoning behind this is that pulling data from a 3rd party application into Drupal, then delivering it to the user, adds a lot of overhead and processing time. Essentially the browser makes a request, Drupal then starts to build it, makes it's own request (same as a browser) to the 3rd party app, gets the data back, finishes the Drupal page build, and sends it to the browser. This can make for some particularly long page builds. Whereas, if you pull it the first time from the 3rd party app and cache it, it takes longer for that first request, but subsequent requests will already find the data within Drupal, making for faster page loads.

Some things to consider however:

* Will the data change every request? If so, then it should not be cached within Drupal.
* Will the data never change on any request? If so, then it should be created as either a Drupal entity, or a non-Drupal entity, within Drupal, permanently
* Will the data ever be deleted? If so, then it should be cached within Drupal, and periodically checked to see if it's been deleted. If however it must definitely not be accessed after it's been deleted, then it should not be cached within Drupal, else you risk showing the data to the user after it's been deleted.
* Can you cache the data safely for a period of time? For example, maybe you can make the Drupal cache expire periodically.
* Will you need the data to be accessible as fast as possible, when it's cached? You may want to create a cron mechanism that makes requests to the 3rd party for any new items, caching them immediately so they are ready right away when necessary.

Each 3rd party app is different, so there is not a one-size-fits-all solution to this. The various limitations and requirements need to be researched, with a solution created accordingly.

---
Tags: 7, entities
---


title: Using blocks in multiple regions

text:
# Question
Title: Using blocks in multiple regions
In one demo projects I have found that I need to place same block in two different regions. I have the knowledge that one block can be placed to one region only. Can anyone help me with this ?

# Answer
Using the Context module you can achieve your required feature.

This module will help you to place all your blocks in multiple regions on same or multiple page.
> 4 votes

# Answer
Try it module\_invoke

```
$block = module_invoke('block', 'block_view', 'block_machinename');
print render($block['content']); in tpl file

```
> 0 votes

# Answer
You can also use the multiblock module (http://dgo.to/multiblock) - D7
> -1 votes

---
Tags: blocks
---


# Question
Title: How can I loop through a multivalue field's values?
I have two authors for the same blog, so I want to display both authors details on a page. Below code will display only one because `$node->field_author[LANGUAGE_NONE][0]['target_id']` contains 0. So next author value will be like this `$node->field_author[LANGUAGE_NONE][1]['target_id']` So how can I use foreach loop here to display both author details?

```
if (isset($node->field_author[LANGUAGE_NONE][0]['target_id']) && is_numeric($node->field_author[LANGUAGE_NONE][0]['target_id'])) {
  $nid = trim($node->field_author[LANGUAGE_NONE][0]['target_id']);
  $nodeauthor = node_load($nid); //$node->type = 'poll';
  if ($nodeauthor) {
    $nodeView = node_view($nodeauthor, 'teaser');
    print drupal_render($nodeView);
  }
}

```

# Answer
The solution is:

```
  foreach($node->field_author[LANGUAGE_NONE] as $key => $value){
    $nid = $value['target_id'];
    //$key is the index 0, 1 ....
  }

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: how to use tokens as “views filter criteria” for a custom table?
I created view for fields from a custom table using handlers. I need to create a filter so that only the users who created the data can see the data. how can I create the filter?

# Answer
> 0 votes
We do not have token based filters, but instead what we can use is 'contextual filters', with in contextual filters you can get current logged in user.

I am assuming you are storing user information(mostly uid) to know who created what.

Now since its a custom table, the relation/join for users table with your custom table you have to define while exposing it to views. Here goes the sample code.

```
/**
 * Implements hook_views_data().
 */
function dev_test_views_data() {

  $data = array();

  $data['custom_view_expose']['table']['group'] = t('Custom table exposed');

  $data['custom_view_expose']['table']['base'] = array(
    'title' => t('custom table exposed'),
    'help' => t('Contains records we want exposed to Views.'),
  );
  $data['custom_view_expose']['record_id'] = array(
    'title' => t('Record ID'),
    'help' => t('The record ID.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
  );
  $data['custom_view_expose']['data'] = array(
    'title' => t('Data'),
    'help' => t('The Data.'),
    'field' => array(
      'handler' => 'views_handler_field',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );
  // Allow views to join it with users table if needed while querying database.
  $data['custom_view_expose']['table']['join'] = array(
    'users' => array(
      'left_field' => 'uid',
      'field' => 'uid',
    ),
  );

  $data['custom_view_expose']['uid'] = array(
    'title' => t('User ID'),
    'help' => t('The record user ID.'),
    'field' => array(
      'handler' => 'views_handler_field_user',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    // Allow this field to show in relationship option.
    'relationship' => array(
      'base' => 'users',
      'field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('Users'),
    ),
    // Get this field as contextual filter option.
    'argument' => array(
      'handler' => 'views_handler_argument_user_uid',
      'numeric' => TRUE,
      'validate type' => 'uid',
    ),
  );

  return $data;
}

```

The above code exposes a very simple table as in screenshot

Now while creating the views within your contextual filter options will see uid as on the fields for which you can pick value to come from current logged in user, and views will automatically filter down results. Adding views screenshot

.

---
Tags: views, tokens
---


# Question
Title: Manage content type's different status for different users
I want to know if there are any modules for the following situation:

I have a content type A with reference to user 1 to user N. Now that content type A will have different status for different users let's say for user 1 it has Status1, user 2 it has Status2. First thing is how can I achieve this functionality is there any module which will be useful for this situation ?

Other part of the scenario is when user1 logs in he should see content type A with status S1 and when user2 logs in he should see content type B with status S2.

Is this possible at all in Drupal? Please suggest me.

Thanks for reading!

# Answer
Based on chat with @parth I realised the status field belongs more to relation of book and user rather than book. Here is my recommendation in that case.

**Way 1:**

The easiest way I could think of is

* have a custom table as book\_inventory with columns as book\_entity\_id, user\_id,status,record\_id

**In order to allow admin to a UI in place to udpate status with fields as**

* autocomplete field for book
* autocomplete field for user
* status could be dropdown field

this UI will let admin to set status for any book against any user down to your form UI, you can list what books are assigned to what users from your custom table with an edit link when the admin clicks the edit button the same form UI will open but prepopulated with all the fields now with help of this table you always have information user and book status with you, you can query your database and get the status runtime and in case you do not have a record agaisnt requested user and book, in that case you can have a default status, I believe 'not purchased' in your case

**Way 2:**

Other approach would be to try Relation module instead of entityReference, as relation module will allow fieldable relation between book and user.
> 1 votes

---
Tags: 7, users
---


# Question
Title: what is "field_create_field" and "hook_field_info"? is there difference motive
I want to create a field, i searched on drupal and find field\_create\_field can create a field but I also find that hook\_field\_info is also to create to field.

My question is what is basic difference between both of them? Are they use for same purpose?

I need the difference and where both are used?

# Answer
**function field\_create\_field** is used to create a field. When you debug this function you will get $field array with the id property filled in.

**function hook\_field\_info** defines Field API field types. For more info refer here.

For more clarification you can simply debug both these functions then you will get the all basic differences.
> 3 votes

# Answer
`field_create_field` can create field object with passing the **field definition** as function argument.

`hook_field_info` can only define the **field definition**.

The main reason why we need a separate function to define **field definition** is to get benefit from the **alter** behavior of Drupal (e.g. `hook_field_info_alter`). It is what I guess.
> 1 votes

---
Tags: entities, hooks
---


title: Disable caching for the front page

text:
# Question
Title: Disable caching for the front page
How can I disable caching for the front page, programmatically?

# Answer
I think one way to achieve that is by altering `'<front>'` route with a RouteSubscriber service.

```
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    arguments: ['@config.factory']
    tags:
      - { name: event_subscriber }

```

Then in your RouteSubscriber.php class :

```
/**
 * Event subscriber.
 */

namespace Drupal\mymodule\Routing;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscribe to KernelEvents::REQUEST events and redirect if user is press.
 */
class RouteSubscriber extends RouteSubscriberBase  {

    protected $configFactory;

    /**
     * RouteSubscriber constructor.
     * @param ConfigFactoryInterface $config_factory
     */
    public function __construct(ConfigFactoryInterface $config_factory) {
        $this->configFactory = $config_factory;
    }

    /**
     * {@inheritdoc}
     */
    public function alterRoutes(RouteCollection $collection) {
        if ($route_front = $collection->get('<front>')) {
            $route_front->setOption('no_cache', TRUE);
        }
    }
}

```
> 2 votes

---
Tags: 8, hooks, caching
---


# Question
Title: How to reset UID number back to default order?
I have a Drupal 7 website with only UID1 user which is root admin. I deleted previous users. Now if I create a new user, it gets UID of e.g. 74.

It should be UID 2 and so on.

Anyway, I had same problem with resetting nodes back to 1. And I did it by following this answer, but it worked only if you have no nodes. Now, I have at least one user and I don't know if that query would work for 'users'.

# Answer
I've found the discussion thread about the issue about why `users` table is not auto-increment and creating a new `sequences` table for that purpose.

> This is NOT a full sequences API not at all but it's enough for some uses. actions\_aid and simpletest\_test\_id , that's duplicate code not to mention it belongs to the DB layer. This patch solves that. Further work: we can reuse this for users.uid as that should not be serial because of the known problems. The postgresql folks can create a version which uses proper sequences. The mysql folks can support more than the single serial mysql allows -- like a timestamp and a serial. Sorry for the hasty writeup.

In your case, you just update the value in `sequences` table to `1`.

**AND**

You need to run `ALTER TABLE sequences AUTO_INCREMENT = 1` as well.
> 1 votes

---
Tags: 7, users, database
---


# Question
Title: How do I programmatically disable/enable a block?
I have the following code but its not disbling the block. It remains active and visible on the sidebar where i have placed it.

```
$theme="themename";
$block="client-block-1938";
$module="modulename";
$region="right_top_box";
db_merge('block')
        ->key(array('theme' => $theme, 'delta' => $block, 'module' => $module))
        ->fields(
                       array(
                              'region' => $region,
                              'status' => 0,
                              'visibility' => 0,
                           )
             )
->execute();
cache_clear_all();

```

# Answer
Use db\_update.

```
db_update('block')
   ->fields(array(
     'status' => 0,
     'weight' => -10,
     'region' => 'disabled',
   ))
   ->condition('module', 'modulename')
   ->condition('delta', 'modulename_delta')
   ->execute();

```
> 1 votes

# Answer
I think this should work.

```
     db_update('block')
        ->fields(array(
          'status' => 0,
          'weight' => -10,
          'region' => 'disabled',
        ))
     ->condition('module', $module)
     ->condition('delta', $delta)
     ->condition('theme', $theme)
      ->execute();

    cache_clear_all();

```
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Database::setActiveConnection not working as expected?
```
kint(Database::setActiveConnection('preview'));
\Drupal::logger('Little kitties')->info('Mau');
kint(Database::setActiveConnection('default'));

```

As my expectation this would create a watchdog entry in preview database. The entry got created in the default database instead.

This means, setActiveConnection() only affects direct queries (select and db\_query..)? That would be really sad.

# Answer
> 3 votes
`Database::setActiveConnection()` doesn't influence those objects that already have a `\Drupal\Core\Database\Connection` object, which means that the following code will not use the *preview* connection for altering the database table.

```
use \Drupal\Core\Database\Database;

$schema = Database::getConnection()->schema();
$old_key = Database::setActiveConnection('preview');
$schema->addField($table, $field, $spec, $keys_new);
Database::setActiveConnection($old_key);

```

When you call `\Drupal::logger()`, you get a `DbLog` object that was already initialised before `Database::setActiveConnection('preview')` is executed, which means it will use the old connection.

To be able to use the new connection for logging, you should try creating a custom logger that uses the connection you want, without you setting the connection before calling its methods.

As side note, `Database::setActiveConnection()` returns the old key; it's easy to restore it: Just call again `Database::setActiveConnection()` passing the value returned from the previous call, as I did with the code I shown.

# Answer
> 2 votes
However it does not stands in the question precisely my intention was to "switch" the database connection in the background for all services in the system. If someone is interested, here is the solution for it. The only requirement of this, that you have to have all the different database credential arrays in your settings.php (or in local settings respectively):

```
use Drupal\Core\Database\Database;
use Drupal\Core\TypedData\Exception\MissingDataException;

class DatabaseSwitcher {

  private $defaultContainer;

  public function __construct() {
    $this->defaultContainer = \Drupal::getContainer();
  }

  public function changeToDifferentDb($database_key) {
    $this->overrideDatabaseService($database_key);
  }

  public function changeToDefaultDb() {
    \Drupal::setContainer($this->defaultContainer);
  }

  private function overrideDatabaseService($database_key) {
    $database = $this->getExistingDatabaseConnection($database_key);
    $container = \Drupal::getContainer();
    $container->set('database', $database);
    \Drupal::setContainer($container);
  }

  private function getExistingDatabaseConnection($database_key) {
    $db_info = Database::getConnectionInfo($database_key);
    if (!$db_info) {
      throw new MissingDataException(sprintf('The %s database key is not defined', $database_name));
    }
    return Database::getConnection('', $database_key);
  }

}

```

---
Tags: 8, database
---


title: Different language on the basis of URL?

text:
# Question
Title: Different language on the basis of URL?
We all know that its possible in Drupal to set different language on different nodes, but is there any option available from which we can set the language on the basis of URL?

For an instance, we can switch themes in Drupal on the basis of URL: https://drupal.stackexchange.com/a/816/3808

# Answer
> 1 votes
Check a sample code provided in **How to change Drupal's default language programmatically?** You can trigger this code yourself based on your requirement.

Another way of doing this can be is 'Use another language than "default" as standard'. And You can find an example of hook\_language\_negotiation\_info() on Drupal 7 default language after translation.

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


# Question
Title: url redirections not working for anonymous users
I have set a redirect rule in EventSubscriber. So according to rule, when I hit example.com/my-page in browser, it should redirect to example.com/success or some external url also.

But issue is(for anonymous user):

On hitting first time this url "example.com/my-page", REDIRECT SUCCESS!! But on second time it does not redirect. It remains "example.com/my-page" only.

Now If I logged in, flush all cache, then again log out and check "example.com/my-page", it again works -- REDIRECT SUCCESS!! But again after redirecting first time when accessed the same, it stops redirecting.

# Answer
> 4 votes
This is probably because of the page cache for anonymous users. The cache is implemented as middleware and runs before any event subscriber, even if you set a high priority.

If your site serves dynamically generated responses and redirects for every single request, then you don't need this cache and you can uninstall the module **Internal Page Cache**.

If you want to disable the page cache in code:

```
\Drupal::service('page_cache_kill_switch')->trigger();

```

This will deny any page caching on the current request.

---
Tags: 8, caching
---


# Question
Title: Drupal.attachBehaviors only working for some fields when using Ajax .load
The following code works for some things that I do in terms of .load() such as adding Chosen to fields.
But it won't do anything to date fields, conditional fields or field groups. They get left with no JS.

I've added other similar forms on the page as a test so the scripts are available and I've also added the scripts to the theme's .info file.

Is there any way to fully .load() a form? It has to added using Ajax as it's a really slow form and kills website performance.

EDIT: As Jimmy Ko pointed out, this isn't a good method. Instead, this link shows how to change the target of a form submit in an iFrame to the parent so I'll try loading the form that way with a custom tpl so only the form is shown in the iFrame.

```
   (function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Check so it doesn't repeat load
    if ($('#page-content-st-node-form').length == 0) {
    // Load
     $('.page-bar').load('/node/add/page-content-st #page-content-st-node-form', {}, function() {
     Drupal.attachBehaviors($('#page-content-st-node-form'));
     });

    }

  }
};
}

)(jQuery);

```

# Answer
$.load() will not update the Drupal.settings object, which contains the references to which fields need to be ajaxified. This is why you are seeing the issue you have. In order to load a form through AJAX, you need to return the form as well as the settings for the form alonng with the form, after the form has been rendered. This will update the Drupal.settings object, which then will ajaxify your form.

First you need to declare a callback path in hook\_menu()

```
function hook_menu()
{
  $menu['my/ajax/callback'] = array
  (
    'title' => 'AJAX callback',
    'page callback' => 'my_ajax_callback',
    'access callback' => TRUE,
  );

  return $menu;
}

```

Then you need to generate your form, and ajax settings, in the callback path

```
function my_ajax_callback()
{
  $form = drupal_get_form('some_form');
  $rendered_form = render($form);
  $javascript = drupal_add_js(NULL, NULL);
  $settings = FALSE;
  if(isset($javascript['settings']))
  {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ' .
      drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data'])) .
    ');</script>';
  }

  $response['form'] = $rendered_form . $settings;
  drupal_json_output($response);
}

```

Finally, you need to make an ajax call to get your form, and append it to the page somewhere, finally calling Drupal.attachBehaviors()

```
$.ajax(
{
  url:'/my/ajax/callback',
  success:function(data)
  {
    // Create a div and set the returned data as the contents,
    // so as to turn them into HTML
    var formElement = $("<div/>").html(data.form).contents();

    // Append the form somewhere on the page
    $("#some_container").append(formElement);

    // Finally call Drupal.attachBehaviors
    Drupal.attachBehaviors(formElement);
  }
});

```

For more of an understanding on what I'm doing with Drupal behaviors, read my tutorial on working with JavaScript in Drupal 7, in particular the section on attaching behaviors: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api
> 1 votes

---
Tags: 7, forms, javascript, ajax
---


# Question
Title: How to upload files to the sites/default/files place without going to the Cpanel backend just through admin backend?
How to upload files to the *sites/default/files* folder without going to the Cpanel backend, just through the admin backend?

I need to put there a set of Ubercart images to make a *bulk product import* via ***feeds*** and ***.csv*** sheet.

# Answer
> 0 votes
If you want to upload files from UI you can use the elFinder file manager module. I've checked this module. Seems it's what you're looking for. You can upload multiple files from admin UI itself. You can access the URL like follows

```
http://example.com/elfinder

```

**Features**

> * Integrated with WYSIWYG API capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor
> * Multiple file upload
> * File copying/moving with Drag & Drop support
> * Quick file and directory rename
> * Image resizing
> * Lightbox-preview
> * Contect menu with generic file/directory operations
> * Inline text file editing
> * Favories directory list
> * Directory selection history
> * Working with archives
> * File descriptions

screenshot

---
Tags: importing-exporting
---


# Question
Title: Drupal 8: How to get the ['third_party_settings'] of an image field inside hook_preprocess_image_formatter(&$variables)
I have a custom module that requires that I pass variables to my image-formatter template via `hook_preprocess_hook()`, in this case `hook_preprocess_image_formatter()`.

From within the preprocessor, I would like to acquire `$field_display['third_party_settings']['My_Module']`

I should be able to do that by exposing the `#view_mode` and the `#field_name` of the ImageObject I am preprocessing. I may even be able to hard-code `#view_mode = 'full'` in which case all I need to do is exposed the `#field_name` in my processor to acquire the \['third\_party\_settings'\]. Any ideas?

EDIT: I forgot to mention that I will be heavily depending on the data that is contained in the image object that is contained within `$variables['item']` to acquire the info needed for this. A gist of part of that object can be found at the following url with data containing the `field_name`: https://gist.github.com/awasson/55ad5da56076e5cb57dd8f3aa68a05f0

Thanks!

# Answer
Although this is pretty specific, it may help someone else with a similar problem.

The answer is in getFieldDefinition() object of $variables\['item'\].

In order to acquire the field name of an image object from within HOOK\_preprocess\_image\_formatter(&$variables) which is a variation of HOOK\_preprocess\_HOOK(), you would use:

`$field_name = $variables['item']->getFieldDefinition()->getName();`

Used within the context of a module file it would look something like the following:

`/**
 * Implements hook_preprocess_HOOK()
 * This allows us to pass attributes to the image_formatter template.
 */
 function MY_MODULE_preprocess_image_formatter(&$variables) {
 // Get the field name
 $field_name = $variables['item']->getFieldDefinition()->getName();
 }`
> 0 votes

---
Tags: 8
---


# Question
Title: Increase upload file size by content type
I have worked with our host to increase our upload file size to 2GB. However, on one page it still states that the files must be less than 3MB. How do I change that? I am a Drupal novice so please bear that in mind.

The following is on a content type on our website (classified as a 'story'):

> Files must be less than 3 MB. Allowed file types: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

So I am trying to increase the size to be 2GB as per what our host is allowing. How do I increase the file size to upload?

# Answer
> 1 votes
It sounds like the content type "story" has a 3MB limit set on that file field.

You can increase that limit by browsing to "example.com/admin/structure/types" and select the "Manage fields" tab (for the "story" content type). Find the field in question (the file upload field) and edit it. You should find a setting for the maximum upload size there.

If you'd like to learn more about fields, and specifically file fields, check out this Drupal.org resource and and this one as well.

Now, the other thing you will need to review is your .htaccess file. There are a couple of php flags you will want to review:

```
php_value post_max_size
php_value upload_max_filesize

```

Review the .htaccess file first because no matter what setting you set for your file field on the content type "story", it will be overridden by the setting in the .htaccess file.

---
Tags: 7, files
---


# Question
Title: Why is smtp not sending emails via SendGrid?
I am attempting to add SendGrid to a Drupal 7 site. I have been following the offical sendgrid.com documentation for this, and following the instructions for using the smtp authentication support module. (https://sendgrid.com/docs/Integrate/Open\_Source\_Apps/drupal.html)

After installing and activating the smtp Authentication Support Module using drush (for which I used version 7.x-7.x-2.x-dev because of a bug with the default version), I was able to activate the module without error and follow the instructions in the documentation.

* Going to configuration \> System \> SMTP Authentication Support
    + Turn the module on
    + Make sure Email delivery is turned on
    + Adding a provier witht eh name sendgrid
    + SMTP server: smtp.sendgrid.net
    + SMTP port 587
    + User encrypted Protocol: No
    + username and password for my sendgrid account
    + set email from address and email name
    + save configuration (which went through without error)

I then filled out a test email address and saved the configuration again.

I got a confirmation message that the settings were stored without error and that the test email had been sent.

I received the test email, but when I checked the headers on the email I received I can see that it has not arrived via SendGrid, but has come directly from my server. I can also see no activity on the SendGrid account at all. I have repeated the test sending system emails linked to user signup and I get the same result, I receive the email but it does not come via SendGrid.

I have also tried using port 465 and SSL as the encryption protocol, but while the the test email reported to have worked, I received no emails at all with these settings. Also as before no activity is logged in SendGrid.

Just to be thorough I tested my SendGrid account using telnet and was able to send an email using the same setting and account username and password used in drupal, including port number. The email was sent without issue, registered in SendGrid activity feed and the received email header references SendGrid.

I have gone as far as I can think of. Can anybody suggest where I might be going wrong?

# Answer
> 3 votes
We use SendGrid with SMTP Authentication Support and have not encountered any problems.

SendGrid may not allow unencrypted connections on port 587, depending on your package. That is the port for TLS/STARTTLS, so if you want to use port 587, you should select *use TLS* under *Use encrypted protocol*. This is how all of our sites that use SendGrid are set up.

One trick that can trip you up is the configuration of Mail System. If you use Mime Mail or another system that requires Mail System to be installed, you must configure Mail System to use SMTP explicitly, or it will fall back to Drupal's default mailer (PHP `mail()`)

For a quick out of the box, you need to configure Mail System (`/admin/config/system/mailsystem` on Drupal 7) to use `SmtpMailSystem` for your module class (for example as the Mime Mail module class, or as the Site-wide default MailSystemInterface class).

For an alternative integration option, there is a SendGrid Integration module which uses the API rather than plain SMTP.

---
Tags: 7, emails
---


# Question
Title: Is there an easy way to load a related entity from an entity?
I have a content entity that references another entity, ie:

```
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['other_entity_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Other Entity'))
      ->setSetting('target_type', 'other_entity')
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);

```

Is there an easy way for me to load the other entity from the entity that references it?

# Answer
You can use the entity field property. ie:

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

```
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Set up Node content 'localization' / site wide region filter - similar to languages idea
What is a good approach re structure and modules to be able to render site content based on a location drop down? It is not an option to display all the content via views.

I'm aware of Views Global Filter. This is be good, but it doesn't work against nodes for one. Therefor only addresses some of the site content.

In principle the user would select from a dropdown a location (custom, based on municipalities). This would then dictate the content presented to that user.

From the admin side, the menus stays the same. One could then create different 'versions' of the same page, each flagged for a specific locality. If the locality doesn't have a corresponding node version, the 'default' node version would be displayed.

Ultimately, I would like to be able to use one dropdown (session stored) that will affect the node content displayed, other views used on different pages and search results.

The translate module is very close, but I don't need the translate functionality, but the rest. Where a few objects are associated to the same url, but rendered depending on the filter.

> Example Something like this (-no it's not a multi-council site, just the concept here):

```
id    page     name               zone
--    ----     ----               ----
1      1       Local Council      East
2      1       Local Council      West
3      1       Local Council      North
4      2       Building permits   East
5      2       Building permits   West
6      3       Pet Registration   East
etc...

```

> main-menu:
> Home | Local Council | Building | Pets

Therefor, the first page version will be the 'default' and any subsequent ones are then flagged for a zone. If a zone does not have a node with their flag, the default is displayed.

Location offers an option to get a location associated to the node, but how do I track the different 'versions' of the same page to same menu item then? And how do I stop search from giving me every version as a result?

I can see various bits that is getting close, but if some could explain the puzzle pieces please.

# Answer
There are two 'out of the box' solutions. The one is to use taxonomies to classify your content in different zones (one for the default zone), and views to decide when to display what.

All you then need to do is allow for your content to be self referencing - in other words add a entity relation field on each content type to itself.

So if you have a content type called `basic_page`, add an entity relation field in `basic_page` that can reference `basic_page` (cardinality of unlimited). Your default zone node can now have relations to nodes of the other zones.

The other option - the one I would rather consider - is using the entity-translation module. The module allows you to define 'custom languages'. Now each zone can be a 'language'. The fact that you are using languages to implement zones is the beauty abstraction - you are 'interpreting' language as a zone.

Using entity translation, all your node data is automatically 'grouped' as translations of the same entity.

I have done translations on Drupal sites a couple of times: IM me if you have questions.
> 2 votes

---
Tags: 7, nodes, location, input-formats
---


title: What does maintenance mode do?

text:
# Question
Title: What does maintenance mode do?
What does maintenance mode actually do? I'm not asking for a high level overview, nor am I asking for a code dump. I'm asking for a technical, *functional* definition. What does maintenance mode actually do? Does it shut down everything for all users except admin and just show them a static page?
Is there a technical reference (short of the code itself) that covers what maintenance mode actually does?

# Answer
> 4 votes
The main functionality of maintenance mode is that it allows the site to use the theme system without requiring the database.

It does almost exactly what you had guessed, it locks out all users that do not have the 'use site in maintenance mode' permissions or administrator roles. A site in maintenance mode will use a different template file than the live site, normally `maintenance-page.tpl.php`.

Maintenance mode also kicks in in other situations:

1. Site installation
2. Updates
3. Any time the database fails

# Answer
> 3 votes
Maintenance mode simply prevent anonymous users and authenticated users without the *access site in maintenance mode* from accessing the site. These users will only be able to view the special maintenance page. This prevents most reads and writes to/from the database and loading of most of Drupal and additional modules' code.

# Answer
> 2 votes
It just limits the users who can access the site to the ones with the *access site in maintenance mode* (Drupal 7 and 8) or *administer site configuration* (Drupal 6) permission.

It doesn't disconnect the database, but it limits the page being accessed to a strict number of users. Drupal will still connect to the database, but the access is very limited, since you don't normally give that permission to normal users.
Also the module's activity is reduced, even if modules are not blocked, although in Drupal 8 the only accessible routes are the ones explicitly stating to be accessible during maintenance. (In the routing.yml file, the module needs to set `_maintenance_access` to `TRUE`.)

# Answer
> 0 votes
Maintenance mode is more about disallowing unauthorized users from accessing the site. There's a permission in `admin/people/permissions` that controls this access.

Maintenance mode also disables any theme for the site and sets a message for site users. That config can be found at `/admin/config/development/maintenance`.

If a custom maintenance theme is needed, that'll have to be set in the settings.php file. To read more about this please see Drupal.org

When you run update.php, the site will briefly go into maintenance mode while it runs database updates. Same with `drush updb`. It happens automatically without many users even noticing that it happens. Some modules such asRedirect or Advanced CSS/JS Aggregation check whether or not the site is in maintenance mode, probably in an effort to not pull in non-functioning code.

To read more about maintenance mode, read the Drupal Gardens post on maintenance mode.

---
Tags: maintenance-mode
---


# Question
Title: Is it possible to completely hide the admin menu for a role, while still grant it some admin permissions?
I need to create a 'Demo' role that can completely hide the admin menu toolbar, but can still access some admin pages to, well, demonstrate stuff.

What would be the best way to do this in drupal 8? Is there some kind of built in functionality to do this?

# Answer
> 4 votes
Uncheck "Use the administration toolbar" for the 'demo' role under Users \> Permissions.

---
Tags: 8, users
---


title: Can't remove document file from Media

text:
# Question
Title: Can't remove document file from Media
I've created a WebForm that allows a user to upload a document file. The file stores to Media which I'm using for images. I can delete the image files but I'll be dog-gone if I can figure out how to delete the document files. I've deleted the WebForm submission but when deleting the file in Media, I get the 'in use and cannot be deleted' message. Does anyone know how to delete this type of file? I'm in the Administrator account so privileges shouldn't be the issue. Thanks!

# Answer
You probably need to delete or remove the file from any nodes, or webform submissions that it references. There should be a usage tab on the actual media resource. I don't have a media site handy so I can't provide screenshots. Once that usage tab is empty, it **should** be possible to delete that file. Otherwise I'd check the recent log messages in `admin/reports` to see if there's a file permissions issue, like the only file owners can delete files.
> 0 votes

---
Tags: webforms, media
---


# Question
Title: hook_field_formatter_view not being called
I cannot for the life of my figure out why `cc_byline_author_field_formatter_view` is not being called here. `hook_field_formatter_info` works as I can select the formatter for my field. Cache clear, module name change, module disable and re-enable have not helped.

Thanks for having a look.

```
/**
 * Implements hook_field_formatter_info().
 */
function cc_byline_author_field_formatter_info() {
  return array(
    'cc_byline_author_author_replace' => array(
      'label' => t('Byline Author Replacement'),
      'field types' => array('text'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function cc_byline_author_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  die;
  return '';
}

```

# Answer
> 1 votes
Whelp, there goes an hour.

Turns out I was configuring the "Default" Display rather than the "Full Content" Display.

---
Tags: theming
---


# Question
Title: How to get read count of blogs in Blog module?
I am using blog module to implement blog section in my website, I am not getting the count of the each blog. What is the variable that stores read count of each blog. Any suggestion will be appreciated.

# Answer
> 1 votes
The core **Blog** module does not track read statistics for content; that's the purview of the **Statistics** module.

To enable read statistics:

1. Install the Statistics module.
2. Follow its configuration link (**/admin/config/system/statistics**).
3. Set the **Count content views** option to enable view counting.

---
Tags: 7, nodes
---


# Question
Title: What is the reason of hidding comments and links in node.tpl.php?
What is the reason of first hiding the `comments` and `links` and later showing theme in `node.tpl.php`?

even if I delete following three lines of this system it does not change anything,
`hide($content['comments']);`
`hide($content['links']);`
`<?php print render($content['comments']); ?>`

*from node.tpl.php*

```
    <div class="content clearfix"<?php print $content_attributes; ?>>
            <?php
              // We hide the comments and links now so that we can render them later.
              hide($content['comments']);
              hide($content['links']);
              print render($content);
            ?>
          </div>

          <?php
            // Remove the "Add new comment" link on the teaser page or if the comment
            // form is being displayed on the same page.
            if ($teaser || !empty($content['comments']['comment_form'])) {
              unset($content['links']['comment']['#links']['comment-add']);
            }
            // Only display the wrapper div if there are links.
            $links = render($content['links']);
            if ($links):
          ?>
            <div class="link-wrapper">
              <?php print $links; ?>
            </div>
          <?php endif; ?>

          <?php print render($content['comments']); ?>

```

# Answer
> 1 votes
You don't need to remove them from your node.tpl.php -- but that is always an option.

I recommend a better solution, however.

First, you can check out this resource to read more about how to deal with fields when they are being displayed on a node.

A really good solution (and one I always recommend) is using modules like Display Suite to customize the fields on your content type. You can customize the create/edit form as well as you can control which fields you want to be visible when visitors are looking at nodes.

# Answer
> 1 votes
The reason they are hidden and then re-displayed is because it gives more granular control over their placement.

Removing those three lines may not seem to do anything. But for them to do something some conditions have to be met: Links and comments have to be present and populated. This means that comments has to be enabled on the node or that something is hooking into the node links and adding links based on display mode, etc. One of these places is on a teaser view mode, you'll see a "Read more" link.

Also, content\_extra\_fields is a module that I like for simple placement of the links and comments using the field\_ui.

---
Tags: 7, theming
---


# Question
Title: How to load .css file only on your custom 404 Not Found page?
Following this guide I created a custom `page--404.tpl.php` page for my custom 404 Not found page. We put this in `template.php`:

```
function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
 }
}

```

Now I need to load CSS only when that page is loaded. This here only shows how to load it in either node or front page, but not custom 404 page.

This does not work:

```
    $header = drupal_get_http_header("status");
    if($header == "404 Not Found") {
      $vars['theme_hook_suggestions'][] = 'page__404';
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/bootstrap.css");
      drupal_add_css(drupal_get_path('theme', 'dev') . "css/404/custom-style.css");
    }

}

```

# Answer
> 2 votes
As mentioned by @Yogesh, you should use `drupal_add_css`. Your code cannot work because you have missing slash. Please use below code.

```
function themename_preprocess_page(&$vars) {
 // Adds a Custom 404 page
 $header = drupal_get_http_header("status");
 if($header == "404 Not Found") {
   $vars['theme_hook_suggestions'][] = 'page__404';
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/bootstrap.css");
   drupal_add_css(drupal_get_path('theme', 'dev') . "/css/404/custom-style.css");
 }
}

```

# Answer
> 0 votes
Another option could be to use CSS Injector. It would allow you to load CSS based upon the path. Might be a simpler solution but may not do exactly what you require.

---
Tags: 7, theming
---


# Question
Title: Where is the setting saved when I modify a configuration setting?
When I modify a setting from a custom module, where is that saved? How can I get that setting without exporting the configuration?

# Answer
https://www.drupal.org/developing/api/8/configuration/simple

See the section on *Interacting with configuration* and *Reading configuration*.

E.g. `$config = \Drupal::config('system.performance');`

I'm assuming the saved settings are configuration.
> 2 votes

---
Tags: 8, configuration
---


# Question
Title: Custom block with configurable message inside it
When creating a custom block, how can we add a message and have it configurable by the user? Is this possible?

# Answer
> 1 votes
This is a good example for a Drupal 8 custom block that is configurable by the user

# Answer
> 0 votes
A trick could be creating a content type called blockMessage or whatever you want and then using Views you can build your desired output for block of this content type which only outputs the last entered one (including message body).

Then whenever a new content of type blockMessage is posted its body will shown in this block as a message.

# Answer
> -2 votes
Please check the example here. You'll need to create a hook\_block\_configure call.

https://api.drupal.org/api/examples/block\_example!block\_example.module/8

---
Tags: blocks, 8
---


# Question
Title: Implement hook_field_create_instance(), hook_field_delete_instance() and hook_field_attach_rename_bundle()
When creating a new field type (e.g. address or dimension), I am looking for the Drupal 8 equivalent of hook\_field\_create\_instance() and hook\_field\_delete\_instance() that are available in Drupal 7. The same goes for hook\_field\_attach\_rename\_bundle().

The hook\_field\_create\_instance() could be used e.g. for defining default values on existing entities. Let's say define the new field default value on existing Node instances after attaching (= creating a field instance) to a Content Type.

After digging around on the parent classes and interfaces of the classes that are involved in the definition of a new field type (FieldFormatter, FieldType, FieldWidget namespaces) + Field Types API, I found the PluginManagerBase::createInstance (and thus FieldTypePluginManager::createInstance) but didn't found a way to define custom code for these operations.

# Answer
These two drupal resources should get you there:

As an aside, here is how I found the changes: Drupal Changes
> 1 votes

---
Tags: 8, entities, hooks
---


title: How to merge 2 date fields

text:
# Question
Title: How to merge 2 date fields
I am working on a D8 instance and i would like to have 2 dates which are in different fields to be displayed at once when the month is the same i.e. : 21-22 december instead of 21 december 22 december.

What is the best way to do that ?

# Answer
This isn't a direct answer to your question, but is probably the best option to move forward.

Drupal 8.2.0 (due 2016/10/05) will include the new datetime\_range module, which provides date ranges in a single field.

I would wait until this is available, and then migrate your two datetime fields into a single daterange fields (one to the start value and the other to the end value).

Then, I would make a custom formatter for daterange fields that implements your logic to combine month/year when they are the same for start and end.

You can then configure your various vide modes to use this new formatter.
> 2 votes

# Answer
Add a hook\_preprocess\_node function to your theme to check if both dates are in the same month. If yes then the function should hide one date and alter the display of the other to display the range. Here is an example of it.

Alternatively, for views you can use pre\_render to alter fields conditionally.
> 0 votes

---
Tags: views, entities
---


# Question
Title: How do I add a variable for a Twig template in my preprocess function?
I'm using the following code to preprocess the variables for my template:

```
function template_preprocess_imagegallery_format(&$vars) {
  template_preprocess_image_formatter($vars);
  $vars['image']['#theme'] = 'igimage';
  $vars['image']['#thumbnail'] = ImageStyle::load('thumbnail')->buildUrl($vars ['image']['#uri']);
  $vars['image']['#fullimage'] = file_create_url($vars ['image']['#uri']);
}

```

The #uri variable is already present, and if I just modify it everything works fine. But I need to add additional variables here as I need two different styles of the same image. But simply adding those variables to the array doesn't work.

If I dump the available variables in my Twig template with `{{ dump(_context|keys) }}`, I don't see the variables I added there. If I try to use them in my template, nothing gets inserted.

I can see that the values are added to the array, when I dump the image variable in the theme that renders the entire field, I see my variables in the array. But they're still not available in the template that renders the image variable itself.

What else do I need to do to add a variable in my preprocess function that I can use in my Twig template?

# Answer
> 8 votes
I finally solved the problem, it turns out the problem was that I tried to add the variables in the wrong preprocessor. Editing the #theme works there, but to add variables I needed to preprocess the theme I set there:

```
function template_preprocess_imagegallery_format(&$vars) {
  template_preprocess_image_formatter($vars);
  $vars['image']['#theme'] = 'igimage';
}

function template_preprocess_igimage(&$vars) {
    $vars['thumbnail'] = ImageStyle::load('thumbnail')->buildUrl($vars['uri']);
    $vars['fullimage'] = file_create_url($vars['uri']);
}

```

# Answer
> 4 votes
For a theme whose machine name is *atvdirect*, create the *atvdirect.theme* file in the directory containing the *.info.yml* file for the theme, and add the following code.

```
function atvdirect_preprocess_page(&$variables) {
  $variables['logopath'] = '/'.drupal_get_path('theme','atvdirect') .'/logo.png';
}

```

Now you can use `{{ logopath }}` in the *page.html.twig* template file.

---
Tags: 8, theming
---


title: Custom classes for menu links

text:
# Question
Title: Custom classes for menu links
How can I add custom classes for links into main menu in Drupal 8. This is template for my main menu called `menu--main.html.twig`

```
{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
        <ul{{ attributes.addClass('main-nav') }}>

        {% for item in items %}
        <li{{ item.attributes.addClass('main-nav__item') }}>
            {{ link(item.title, item.url) }}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
            {% endif %}
        </li>
        {% endfor %}
    {% else %}
        <ul class="main-nav__sub js-nav-submenu ">

        {% for item in items %}
        <li{{ item.attributes.addClass('main-nav__sub-item') }}>
            {{ link(item.title, item.url) }}
            {% if item.below %}
                {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
            {% endif %}
        </li>
        {% endfor %}
    {% endif %}
    </ul>
  {% endif %}
{% endmacro %}

```

And I need to achieve this result:

```
<ul class="main-nav">
  <li class="main-nav__item"><a class="main-nav__link main-nav__link--active" href="index.html">Úvod</a></li>
  <li class="main-nav__item"><a class="main-nav__link js-nav-submenu-toggler" href="#">O škole</a>
    <ul class="main-nav__sub js-nav-submenu">
      <li class="main-nav__sub-item"><a class="main-nav__sub-link" href="#">Aktuality</a></li>
      <li class="main-nav__sub-item"><a class="main-nav__sub-link " href="pedagogovia.html">Pedagógovia</a></li>
      <li class="main-nav__sub-item"><a class="main-nav__sub-link" href="#">Dokumenty</a></li>
      <li class="main-nav__sub-item"><a class="main-nav__sub-link " href="historia.html">História</a></li>
    </ul>
  </li>
  <li class="main-nav__item"><a class="main-nav__link" href="#">Informácie o štúdiu</a></li>
  <li class="main-nav__item"><a class="main-nav__link" href="#">Fotogaléria</a></li>
  <li class="main-nav__item"><a class="main-nav__link " href="kontakt.html">Kontakt</a></li>
</ul>

```

My problem is that I don't know how to set custom class for `<a href="">` tags. Is there any way how can do it using `link()` function. In Drupal 7 is `l()` function but attributes aren't similar. `l()` has also third attribute with possibility to add options. Is it true, that `link($title, $url)` accepts only 2 parameters? Because I can't find the way how to send options for `link($title, $url)`. I don't insit on `link()` function, so if there is some better way please let me know. I'm open to new ideas :)

Thanks

# Answer
> 1 votes
I finally solved it using next syntax in Twig template

```
{{ link(item.title, item.url.setOptions({'set_active_class' : TRUE, 'attributes' : {'class' : 'main-nav__link'}})) }}

```

# Answer
> 2 votes
Just incase someone stumbles upon this, Martin's solve above breaks URL fragments as it overrides the URL options completely. The better approach is here:

```
{{ link(item.title, item.url.setOption('attributes', {'class' : 'main-nav__link'})) }}
```

# Answer
> 2 votes
Just replace

```
{{ link(item.title, item.url) }}

```

by

```
{{ link(item.title, item.url, { 'class':['main-nav__link']}) }}

```

# Answer
> 0 votes
file name /var/www/html/drupal/themes/theme\_name/templates/navigation/menu.html.twig

we are checking menu name in if condition {% if menu\_name ==’account’ %}

below is the whole code you may copy and replace it

```
  {#
  /**
   * @file
   * Theme override to display a menu.
   *
   * Available variables:
   * - menu_name: The machine name of the menu.
   * - items: A nested list of menu items. Each menu item contains:
   *   - attributes: HTML attributes for the menu item.
   *   - below: The menu item child items.
   *   - title: The menu link title.
   *   - url: The menu link url, instance of \Drupal\Core\Url
   *   - localized_options: Menu link localized options.
   *   - is_expanded: TRUE if the link has visible children within the current
   *     menu tree.
   *   - is_collapsed: TRUE if the link has children within the current menu tree
   *     that are not currently visible.
   *   - in_active_trail: TRUE if the link is in the active trail.
   */
  #}
  {% import _self as menus %}

  {#
    We call a macro which calls itself to render the full tree.
    @see http://twig.sensiolabs.org/doc/tags/macro.html
  #}
  {{ menus.menu_links(items, attributes, 0,menu_name) }}

  {% macro menu_links(items, attributes, menu_level,menu_name) %}
    {% import _self as menus %}
    {% if items %}

      {% if menu_level == 0 %}
            {% if menu_name =='account' %}
                <ul{{ attributes.addClass('') }}>
            {% endif %}

            {% if menu_name =='main' %}
                <ul{{ attributes.addClass('menu nav navbar-nav') }}>
            {% endif %}

      {% else %}
              <ul{{ attributes.addClass('menu nav navbar-nav') }}>
      {% endif %}
      {% for item in items %}
        {%
          set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
          ]
        %}
        <li{{ item.attributes.addClass(classes) }}>
          {{ link(item.title, item.url) }}
          {% if item.below %}
            {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
          {% endif %}
        </li>
      {% endfor %}
      </ul>
    {% endif %}
  {% endmacro %}

```

---
Tags: routes, 8, theming
---


title: My module form never submits

text:
# Question
Title: My module form never submits
I'm developing my first module in Drupal 8 to programmatically create nodes of a custom content type. The submission handler I add is never called.

This is the button to which the form submission handler is attached.

```
$form['addAds'] = array(
  '#type' => 'submit',
  '#value' => t('Save Your Ads'),
  '#attributes' => ['id' => 'addAdsBtn', 'class' => ['hiddenselect']],
  '#submit' => array('ajax_example_formSubmit'),
);

```

This is the submission handler.

```
function ajax_example_formSubmit($form, &$form_state) {
  $new_node = array();
  foreach ($form_state->getValues() as $key => $value) {
    $new_node[$key] = $value;
  }

  $entity_type = "node";
  $bundle = $form_state->getValue('level1');

  $entity_def = \Drupal::entityManager()->getDefinition($entity_type);

  $new_node[$entity_def->get('entity_keys')['bundle']] = $bundle;

  $new_post = \Drupal::entityManager()->getStorage($entity_type)->create($new_node);
  $new_post->save();
}

```

What is wrong in the code? this is my complete Form Code:

```
class Place_AdsForm extends FormBase {

public $classifiedForms;

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

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

    $this->types = Place_AdsController::getClassifiedContentTypes();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['depth'] = [
        '#type' => 'hidden',
        '#value' => '',
    ];
    $form['ajax_wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper', 'class' => ['shownselect']],
    ];

    $form['ajax_wrapper']['ajax_wrapper1'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper1', 'class' => ['shownselect', 'classified_cat']],
    ];
    $form['ajax_wrapper']['ajax_wrapper2'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper2', 'class' => ['shownselect', 'classified_cat']],
    ];
    $form['ajax_wrapper']['ajax_wrapper3'] = array(
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper3', 'class' => ['hiddenselect', 'classified_cat']],
    );
    $form['ajax_wrapper']['ajax_wrapper4'] = array(
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper4', 'class' => ['hiddenselect', 'classified_cat']],
    );
    $form['ajax_wrapper']['ajax_wrapper1']['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $this->types,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(

            'callback' => '::level1SelectedCallback',

            'wrapper' => 'ajax-wrapper2',
            'effect' => 'fade',

            'event' => 'change',
            'progress' => array(

                'type' => 'throbber',

                'message' => NULL,
            ),
        ),
    );

    $form['ajax_wrapper']['ajax_wrapper3']['level3'] = array(
        '#type' => 'select',
        '#description' => 'Please select level three term',
        //'#options' => '',
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => '::level3SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'wrapper' => 'ajax_wrapper4',
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    $form['ajax_wrapper']['ajax_wrapper4']['level4'] = array(
        '#type' => 'select',
        '#description' => 'Please select level four term',
        //'#options' => '',
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => '::level4SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'wrapper' => 'fields_wrapper',
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    foreach ($this->types as $key => $value) {
        if ($key !== 0) {
            $form[$key . '_fields_wrapper'] = [
                '#type' => 'container',
                '#attributes' => ['id' => $key . '-fields-wrapper', 'class' => ['hiddenselect']],
            ];
        }
    }
    foreach ($this->types as $key => $value) {
        if ($key !== 0) {
            $currFields = Place_AdsController::contentTypeFieldsAsFields($key);
            $node = \Drupal\node\Entity\Node::create(['type' => $key]);
            $myform = \Drupal::service('entity.form_builder')->getForm($node);
            $this->classifiedForms[$key] = $myform;

            foreach ($currFields as $field) {
                //$name = $field->id();
                $n = $field->getName();
                $form[$key . '_fields_wrapper'][$n] = $myform[$n];
            }
        }
    }

    if ($form_state->getValue('level1') != false) {
        //$form['#action'] = $this->classifiedForms[$form_state->getValue('level1')]['#action'];
        $form['ajax_wrapper']['ajax_wrapper2']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
            '#ajax' => array(
                // Function to call when event on form element triggered.
                'callback' => '::level2SelectedCallback',
                // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
                'wrapper' => 'ajax-wrapper3',
                'effect' => 'fade',
                // Javascript event to trigger Ajax. Currently for: 'onchange'.
                'event' => 'change',
                'progress' => array(
                    // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                    'type' => 'throbber',
                    // Message to show along progress graphic. Default: 'Please wait...'.
                    'message' => NULL,
                ),
            ),
        );
    }

    $form['addAds'] = array(
        '#type' => 'submit',
        '#value' => t('Save Your Ads'),
        '#attributes' => ['id' => 'addAdsBtn', 'class' => ['hiddenselect']],
        '#submit' => ['::ajax_example_formSubmit'],

    );
    /* $form['actions']['#type'] = 'actions';
      $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Add'),
      '#submit' => array("::submitForm"),
      '#button_type' => 'primary',
      '#attributes' => ['id' => 'addAdsBtn', 'class' => ['hiddenselect']],
      ); */
    return $form;
}

function ajax_example_formSubmit($form, &$form_state) {
    $new_node = array();
    foreach ($form_state->getValues() as $key => $value) {
        $new_node[$key] = $value;
    }

    //define entity type and bundle
    $entity_type = "node";
    $bundle = $form_state->getValue('level1');

    $entity_def = \Drupal::entityManager()->getDefinition($entity_type);

    $new_node[$entity_def->get('entity_keys')['bundle']] = $bundle;

    $new_post = \Drupal::entityManager()->getStorage($entity_type)->create($new_node);
    $new_post->save();
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
}

public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    $val = $form_state->getValue('level1');
    $terms = Place_AdsController::getsubCategory($val);
    /*
      foreach ($this->fields as $field) {
      $n = $field->getName();
      $ajax_response->addCommand(new HtmlCommand('#fields-wrapper', $form['fields_wrapper'][$n]));
      }
     */
    $form['ajax_wrapper']['ajax_wrapper2']['level2']['#options'] = $terms;

    $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper2', $form['ajax_wrapper']['ajax_wrapper2']['level2']));
    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper2', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper3', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#level2', 'change'));
    $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#ajax-wrapper3', 'shownselect', 'hiddenselect']));
    $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#ajax-wrapper4', 'shownselect', 'hiddenselect']));
    foreach ($this->types as $key => $value) {
        if ($key !== 0)
            $ajax_response->addCommand(new InvokeCommand(NULL, 'hideFields', [$key]));
    }

    $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#addAdsBtn', 'shownselect', 'hiddenselect']));

    $form_state->setRebuild(True);

    return $ajax_response;
}

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

    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    $terms = array();
    if ($form_state->getValue('level2') != false) {
        $val = $form_state->getValue('level2');
        $terms = Place_AdsController::getTerms($val);
    }

    if (count($terms) > 0) {
        $form['ajax_wrapper']['ajax_wrapper3']['level3']['#options'] = $terms;

        $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper3', $form['ajax_wrapper']['ajax_wrapper3']['level3']));

        // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
        $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper3', 'change'));
        $ajax_response->addCommand(new InvokeCommand('#level3', 'change'));
        $ajax_response->addCommand(new InvokeCommand('#edit-level3', 'change'));
        $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#ajax-wrapper3', 'hiddenselect', 'shownselect']));
    } else {
        $arg = [$form_state->getValue('level1')];
        $ajax_response->addCommand(new InvokeCommand(NULL, 'showFields', $arg));
        foreach ($this->types as $key => $value) {
            if ($key !== 0 && $key !== $form_state->getValue('level1'))
                $ajax_response->addCommand(new InvokeCommand(NULL, 'hideFields', [$key]));
        }
        $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#addAdsBtn', 'hiddenselect', 'shownselect']));
    }
    $form_state->setRebuild(True);
    return $ajax_response;
}

public function level3SelectedCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $terms = array();
    if ($form_state->getValue('level3') != false) {
        $val = $form_state->getValue('level3');
        $terms = Place_AdsController::getTerms($val);
    }

    if (count($terms) > 0) {
        $form['ajax_wrapper']['ajax_wrapper4']['level4']['#options'] = $terms;

        $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper4', $form['ajax_wrapper']['ajax_wrapper4']['level4']));

        // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
        $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper4', 'change'));
        $ajax_response->addCommand(new InvokeCommand('#level4', 'change'));
        $ajax_response->addCommand(new InvokeCommand('#edit-level4', 'change'));
        $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#ajax-wrapper4', 'hiddenselect', 'shownselect']));
    } else {
        $arg = [$form_state->getValue('level1')];
        $ajax_response->addCommand(new InvokeCommand(NULL, 'showFields', $arg));
        foreach ($this->types as $key => $value) {
            if ($key !== 0 && $key !== $form_state->getValue('level1'))
                $ajax_response->addCommand(new InvokeCommand(NULL, 'hideFields', [$key]));
        }
        $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#addAdsBtn', 'hiddenselect', 'shownselect']));
    }
    $form_state->setRebuild(True);

    return $ajax_response;
}

public function level4SelectedCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $arg = [$form_state->getValue('level1')];
    $ajax_response->addCommand(new InvokeCommand(NULL, 'showFields', $arg));
    foreach ($this->types as $key => $value) {
        if ($key !== 0 && $key !== $form_state->getValue('level1'))
            $ajax_response->addCommand(new InvokeCommand(NULL, 'hideFields', [$key]));
    }
    $ajax_response->addCommand(new InvokeCommand(NULL, 'changeClass', ['#addAdsBtn', 'hiddenselect', 'shownselect']));

    $form_state->setRebuild(True);

    return $ajax_response;
}

```

}

# Answer
> 0 votes
I finally figure it out... my proplem was so silly that every select must have '#options' set to null in Formbuild function even if it's hidden and not yet filled..

# Answer
> 2 votes
Try this one, attaching custom submit handler is a bit different in Drupal 8. change `'#submit' => array('ajax_example_formSubmit')` to `'#submit' => ['::ajax_example_formSubmit'],`

```
$form['addAds'] = array(
  '#type' => 'submit',
  '#value' => t('Save Your Ads'),
  '#attributes' => ['id' => 'addAdsBtn', 'class' => ['hiddenselect']],
  '#submit' => array('ajax_example_formSubmit'),
);

```

to

```
$form['addAds'] = array(
  '#type' => 'submit',
  '#value' => t('Save Your Ads'),
  '#attributes' => ['id' => 'addAdsBtn', 'class' => ['hiddenselect']],
  '#submit' => ['::ajax_example_formSubmit'],
);

```

Here is another working example

```
namespace Drupal\example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ExampleForm extends Formbase {

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

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

      $form['title'] = array(
        '#type' => 'textfield',
        '#title' => t('Title'),
      );

      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => ['::custom_submit_handler'], // Comment this to use submitForm instead of custom submit handler
      );
      return $form;
    }

    public function custom_submit_handler(array &$form, FormStateInterface $form_state) {
      drupal_set_message('Hello World 1');
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
      drupal_set_message('Hello World 2');
    }
}

```

---
Tags: nodes, forms, 8
---


# Question
Title: Difference between APC & Memcached and how both can be used for cache bins
I'm trying to understand the difference between Memcached and APC and why people talk about using one or the other or both. I can't understand why you wouldn't use both because I thought they had completely different roles. Here's my understanding:

**APC**

This caches chunks of PHP code and stores it in RAM. Then when you need to run that same piece of code again it's already cached and runs from memory lightning fast.

In my particular case of running PHP-FPM, this would reduce the load on that.

**Memcached**

*(I'll ignore the difference between the two php modules and treat them as the same thing for this purpose)*

This caches DB objects and stores them in RAM. Then when drupal needs to call the same database object all the information is sitting there and it doesn't need to go to the database.

In my particular case of running MySQL, this would reduce the load on that.

**Drupal Cache Bins**

There are a bunch of questions on Drupal Stack Exchange about caching and cache bins both which mention APC & memcached:

So several of the really informative questions in this area recommend just using Memcached and a couple other ones say there's not a huge difference to introducing both.

But I don't understand how this works. Aren't they caching completely different things?

Suppose I have a view which is used a lot. Isn't memcached caching the DB objects that are shown in the view and APC is caching the module code which calls them?

Is the difference that you can only use one cache for each Drupal cache bin, so you can either choose to cache DB objects or PHP code and in practice most Drupal cache bins have either little performance difference between the two or are too large to cache all the PHP so caching DB objects is the only reasonable option?

(And thus why most people suggest memcache as the default cache bin option i.e. `$conf['cache_default_class'] = 'MemCacheDrupal';`)

# Answer
APCu
Does not share the cache with other servers but is faster.

Memcached
Can be shared with other servers and is slower.

If you have 2 or more web servers (apache/nginx) for the same Drupal site you'll want Memcached. If you are running on a single machine then APCu will be the quickest. You'll want OPcache turned on no matter what.

LCache is a module designed to fix the issues with using APCu in a 2 or more web server environment.
> 2 votes

---
Tags: 7, caching
---


# Question
Title: Can my site's administrators bypass required profile fields during user creation?
I have two separate roles on my site, one for regular users, and one for site administrators.

The regular users must fill out more details about themselves than I need admins to do, such as name, gender and address.

How can I allow the site administrator to create new site administrators without needing to fill out these extra profile fields?

# Answer
The only easy way I can think of is to make this fields not required. Then the admins can leave it empty.

I'd just let the Admins enter the extra data, even if you don't really need it. Admins are specially trust worthy users. It's not likely that you have a lot of them.

If you must: Create your own form using Drupa FAPI and create a new user by calling user\_save in the submit function.
> 2 votes

# Answer
Use the module profile2\_regpath and provide different paths for each profile type.

Ensure that:

```
Show on all user account registration forms.
If selected, fields for this profile type will be added to the core user registration page and the administrative add user page.

```

Is unchecked.
> 0 votes

---
Tags: users
---


# Question
Title: Creating a new Form element in ajaxcallback function not affecting form state
I am trying to insert new form fields into exiting wrapper within ajax callback function.

I succeeded doing so, but trying to get those new fields values inside submit function failed because they are listed in the form state values array.

How can I make their values available to be used inside the submit function.

```
$form['test'] = array(
        '#type' => 'select',
        '#options' => array('- Please select -' => [1=>'one',2=>'two']),
        '#ajax' => array(
            'callback' => '::testSelectedCallback',
            'wrapper' => 'fields-wrapper',
            'effect' => 'fade',
            'event' => 'change',
            'progress' => array(
                'type' => 'throbber',
                'message' => NULL,
            ),
        ),
    );
$form['fields-wrapper'] = array(
        '#type' => 'container',
        '#attributes' => ['id' => 'fields-wrapper', 'class' => ['hiddenselect']],
    );

public function testSelectedCallback(array &$form, FormStateInterface $form_state) {
$form['fields-wrapper']['new_item']= array(
'#type' => 'textfield',
'#title' => 'My new item',
);
$form_state->setRebuild(True);
return $form['new_item'];
}

```

# Answer
> 3 votes
You cannot add fields in ajax callback functions - assuming that level2SelectedCallback() is your ajax callback (you named it something different in your form element defintion).

All form elements need to be added in the form definition. The ajax callback is only used for determining which elements need to be inserted into the page when the AJAX is returned.

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