title: How can I log variables to a txt file?

text:
# Question
Title: How can I log variables to a txt file?
In Drupal 7 I use devel's drupal\_debug() or its alias dd() to log a variable to a drupal\_debug.txt in the site's temp directory.

In the Drupal 8 version of devel this function has disappeared. It seems to be replaced by DevelDumperManagerInterface But it is not clear to me how it used.

How can I log variables to a txt file in Drupal 8?

# Answer
> 7 votes
The DevelDumperManagerInterface interface is implemented by DevelDumperManager. This class is in turn used as a service, 'devel.dumper'.

One way to use this function would be the following:

```
$ddumper = \Drupal::service('devel.dumper');
$ddumper->debug($variable_name, NULL, 'default');

```

That would log the variable `$variable_name` to `drupal_debug.txt` located in the temp folder directory. See DevelDumperManager::debug() docs for more information.

Good luck!

---
Tags: 8, debugging
---


# Question
Title: File in /sites/default/files/ gives 404 error
my page is trying to load this file /sites/default/files/languages/it\_Et3NQJm4afZYHEnSM9oq5ylZkAw2ExqC8PQtEYrxXDU.js but it gives 404 error. This error is spamming my log page with errors messages. If i check the ftp the file is there but if i try to load it from the url it gives 404 error. Is it a permission issue? How can i fix? Thanks

# Answer
Yes, it is a permission issue. Did you move the website to a different server? Sometimes, after you change the server (maybe from localhost to production) some files can have permissions issue.

That's a Drupal generated file, so you can make a backup of it, remove it, flush all caches, cross your fingers and load the page again. Hopefully Drupal will create the file with the correct permissions and the issue is solved.

If this doesn't work, check the watchdog again and check what's the problem again. Maybe there is a different problem... like that your Temporary directory is not writable.

If you still receive the same error. Try to flush all caches. Then, try to flush CSS and JS cache (this can be done with administration menu module in the first link in the left).

If that doesn't work, you must check the file permissions directly, so lets check if the user and group are configured to what they should be.

Then lets check if the file is accesible, maybe modify the permissions to 644 and check again. If this doesn't work, then change it to 664, If still doesn't work, 666; it should work now, but the user and group of the file are not well configured.

EDIT: Permissions updated as suggested by @Clive.
> 0 votes

---
Tags: theming, i18n-l10n, log-messages, javascript
---


title: cannot track view with features

text:
# Question
Title: cannot track view with features
I'm using `Features` to create a feature called `foo` which tracks content types and views so they can be described in code, committed to my repository and eventually pushed into the staging and production servers.

Some modules (e.g http://drupal.org/project/nodequeue, http://drupal.org/project/views\_bulk\_operations, http://drupal.org/project/admin\_views) create some views as part of their functionality. The problem is that I can't include those views into my `foo` feature. So for those specific views I have to repeat (by hand) any customization I did locally to the staging and production servers.

Any ideas?

**What I've tried:**

1) I tried manually adding the view name in the `foo_features.info` file:

```
features[views_view][] = admin_content_node

```

but when I do `drush fu foo_features -y` that line is removed and the `.info` file and the view definition is not being included in the `foo_features.views_default.inc` file.

2) I had a look into the database:

```
mysql> select vid, id, display_title, display_plugin, position from views_display;
+-----+----------+---------------+----------------+----------+
| vid | id       | display_title | display_plugin | position |
+-----+----------+---------------+----------------+----------+
|   3 | default  | Master        | default        |        1 |
|   3 | page     | Page          | page           |        2 |
|  30 | block    | Block         | block          |        2 |
...
|  46 | default  | Defaults      | default        |        1 |
|  46 | system_1 | System        | system         |        2 |
+-----+----------+---------------+----------------+----------+

```

That last row (vid: 46, display\_plugin: system) seemed suspicious so I've changed (directly via SQL) `system` to `page`. I then did `drush cc all` and retried the process at \[1\] for including the view into the feature but without luck. I tried this because I thought that "system view displays" (whatever that means) cannot be included in features.

# Answer
This is bypassable by cloning the views you need from the four views that the module provides, disabling the original views, and doing all your work in your clones which are 100% trackable.
> 9 votes

# Answer
As suggested by magtak, this is circumventable by cloning the Views. They will need to be stored under a different name for this to work; exporting and importing a View (as suggested by Varshith) will only work if you do so while changing the machine name of the View. Cloning will have the same result as export/import, except that it will enforce the machine name change, and encompasses less actions.

The reason you need to do this is that these modules add Views not by entering them into the database, but adding them through code, much like what happens when you add a View to a Feature. Features will check if a View already exists in code and will not offer it for adding it to your Feature if it does. (Incidentally, what happens when you change a View that is defined by code through the interface, is that Views takes a copy of the View and enters it into the database. That's where it stores your changes. This is why you might find Views defined by modules in the database anyway; this would happen the moment you make changes to them. This is also what happens when you revert an overriden View, either from Views itself or from Features; the copy in the database is ditched and Views defaults back to the code).

One downside to the clone approach is that from that moment on, you are on your own maintaining the View that was originally added by the module; your clone is completely independent of the original, so if there are module updates that add nifty new features, you'd probably not find out. If you did, you'd have to add those changes to your clone by hand. An alternative is using hook\_views\_default\_views\_alter() to add your additions in code. However, this is completely unsupported by Features (you *can* add this code to a Feature; if you do so in the .module file for the Feature, Features will leave it alone when regenerating the feature). You will need to know what you are doing defining Views in code by hand. You can get a long way by comparing an export of your customized View with the original code in the module (which would be found in themodule.views\_default.inc), but it is still not for the faint hearted (and may turn out to be less maintainable than just doing the clone thing).

As an aside, for Nodequeue you can certainly use the Views it adds by default, but it is hardly worth the effort to go and clone a nodequeue View. All it is is a View of Nodes, with a mandatory relation on the nodequeue, sorted by the nodequeue weight. It is probably about the same effort starting from scratch as it is cloning the default View and then making your changes.
> 2 votes

# Answer
I am having a similar issue too. What I am doing currently is exporting the views I need one by one and import it back and then create the feature so that you can include them as well.
> 0 votes

# Answer
I'm a little late to the party, but FYI, you may have luck getting it in Features if you uncheck "Automatically create one view per queue" on the Nodequeue settings page /admin/structure/nodequeue/settings then go back to Features and try to Recreate again.

Also, track that you unchecked that checkbox in Features. If you forget to uncheck it on prod, it won't work right.
> 0 votes

---
Tags: 7, features, views
---


# Question
Title: form_set_error message delayed one page refresh
I'm making a custom validation in a form I'm making but my error message is always delayed by one page refresh.

```
$form['submit']['#validate'][] = 'asap_sollicitation_form_validate';

function asap_sollicitation_form_validate($form, &$form_state)
{
    if(strlen($form_state['values']['pass']) < 6){
        form_set_error('pass', t('Must be longer than 6'));
    }
}

```

It successfully marks the field in red but the message is delayed. If I use only `drupal_set_messsage` without the form\_set\_error I do get a message displayed in time. I render my form in a node template:

```
$arr = drupal_get_form('asap_sollicitation_form');
print drupal_render($arr);

```

How can I get my message to display after form submit?

# Answer
> 3 votes
I had the same, here is the solution and explanation: The key of this problem is the drupal\_get\_form('FOO') is called in theme layer. For example \_preprocess\_WHATEVER or directly in BAR.tpl.php

The messages are prepared in \_process\_page() After that it's unchangeable in deeper theme functions, like FOO\_preprocess\_node. (That's not exactly true, but it's out of scope of this topic.)

I bet, you prepared a variable by drupal\_get\_form('FOO') in \_preprocess\_node, maybe later.

You should use hook\_entity\_view\_alter or hook\_node\_view\_alter, maybe hook\_page\_alter if necessary, anything else than theme hooks.

Just for the record: The last time you are able to set a message by drupal\_set\_message() is \_preprocess\_page

# Answer
> 0 votes
This might be relevant to you, or if not maybe it will help someone else who comes across this.

If you're calling the form through a block, which is rendered in a tpl.php as opposed to with drupals block system, context or panels, then the messages will be delayed a page. (Presumably because you call the block too late in the generation process? not quite sure why.)

My workaround was to place the block on the page with context so it appeared naturally, then hide that and have people use the correctly placed block.

i.e. You need a block to be generated inside the HTML of a template (perhaps for jquery tabs) so you might call it template.php and then render it in your tpl.php.

Example code that would cause this problem.

**Template File**

```
function theme_preprocess_entity_profile2(&$vars, $hook) {
  //profile2 preprocess function
  //invoking the block from the correct module and storing it
  //to be accessible in the tpl.php
  $vars['my_form_module_var'] = module_invoke('form_module', 'block_view', 0);
}

```

**Tpl.php file**

```
<div class="my-class"><?php print render($my_form_module_var['content']); ?></div>

```

# Answer
> 0 votes
I ran into this issue as well. I had an unthemed tpl.php file in a custom module. I was outputting a webform using the following code

```
$objMessages = drupal_get_messages();
...error output code...

webform_node_view($node,'full');
print theme_webform_view($node->content);

```

I could not get the validation error messages to output until the following page. After reading the above answers, I realized that I need to rearrange the code as such

```
//process the form first to send
//error messages to the session vars
webform_node_view($node,'full');

$objMessages = drupal_get_messages();
...error output code...

print theme_webform_view($node->content);

```

# Answer
> -3 votes
If drupal\_set\_message() is working for you then you should use it. You can pass a second parameter to the function to control which type of message drupal will display.

> string $type: (optional) The message's type. Defaults to 'status'. These values are supported:
>
> 'status'
>
> 'warning'
>
> 'error'

Also, form\_set\_error() calls drupal\_set\_message() with a $type = 'error' so it may be that there is something else causing 'error' type messages to be suppressed.

---
Tags: 7, forms
---


title: PCI compatible recipe?

text:
# Question
Title: PCI compatible recipe?
I've struggled to find a really straight answer that makes me super comfortable to this question after searching SE, PCI basics, drupal.org, AWS resources, and reading the Drupal PCI Compliance White Paper.

I think I am just looking for some confirmation or denial from folks who have set up eCommerce environments before. Perhaps this is because I am overthinking it (I really don't want to expose a small business to unnecessary liability), and perhaps because environments are all different so it's difficult to say.

I'd like to be sure to create a PCI compatible environment using Drupal Commerce with an onsite payment gateway (Authorize.net). In our MOU it will be up to the site owner to ultimately write down their business processes and take the SAQ (recommended, as they should qualify for level 4 from Visa/Mastercard) to say they are PCI compliant, but since I am building the site out I would like to make sure they don't have any trouble with that piece of it.

As long as we are...

* Hosted in a PCI compliant environment (AWS EC2 in this example)
* Have firewall properly configured
* Serving all relevant (but ideally all) pages over SSL
* Use good passwords, no users are shared
* All security updates are made for Drupal and modules promptly

Is that a recipe for a PCI compatible environment? Have I forgotten any pieces?

My second but related question is - Does using Drupal Commerce with Authorize.net (onsite processing) mean the business should use:

* SAQ-A (Card-not-present merchants: all payment processing functions fully outsourced, no electronic cardholder data storage)

or

* SAQ-EP (E-commerce merchants re-directing to a third-party, PCI compliant service provider for payment processing, no electronic cardholder data storage)

I know Drupal Commerce provides the 'no cardholder data storage' by design, but i'm very unclear on the definition difference between 'all payment processing functions fully outsourced' and 'merchants re-directing to a third-party compliant service provider for processing'.

Thanks for your thoughts!

# Answer
> 1 votes
Disclaimer: Keep in mind I am neither a lawyer nor a PCI QSA.

After doing more research - I'm convinced that using Drupal Commerce with authorize.net AIM (which is the method used by the authorize module that comes with the commerce kickstart profile) should land you directly into SAQ-D in almost all cases (do not pass go, do not collect $200).

This means you need all the things above plus much more management and policy on your end (or your clients end). It wouldn't be feasible for a small company without a huge budget for a custom project.

Here is the best/most robust explanation i've found of which SAQ to use in one place.

To reduce the scope of the CDE using Authorize.net, one would need to integrate with SIM (offsite form generation) to use SAQ-A, or DPM (direct post) to use SAQ-EP. This assumes you can say yes to the entire list of qualifications i.e. only take payment online, no POS etc. The latter option offers more customization but is more work.

This module looks like it will allow you to do so with Drupal Commerce, but I have done no testing or verification.

Looks like smaller budget clients should be briefed on PCI (always) and plan to use the off-site methods such as Authorize.net SIM or Paypal WPS where the form is generated by the CC processing organization's servers, and never touches your environment. This way your environment should be out of scope with proper configuration.

Here is a (albeit pretty old) thread from authorize.net development forum that has some general and scalable config insights I found very useful.

Here is another (1 year old) white paper that sets forth a framework for PCI compliance on AWS in general. Some of these pieces are not applicable to just a Drupal Commerce server, but still interesting and good.

Any more thoughts still welcome.

---
Tags: commerce, security
---


# Question
Title: Can I use Feature for development and CMI only for deployment?
As a developer working in team I don't like using CMI to synch config from/into development server at all (cim/cex) in local development machine. Instead I'd like to use Feature. What I wanted to achieve is on below diagram.

Basically I want to use Features for development in first tier and use CMI only for deployment to PRD/IGR. Does it make sense? What do you think?

# Answer
Some comments according to the limited experience i have on CMI myself.

I believe that what you ask is pretty much logical, due to the fact that local dev envs usually end up being different than the actual remote Dev instance. Testing modules, code, configuration e.t.c is pretty much the reason for that. This makes default CMI functionality unusable as you dont want to move the whole configuration into your actual deployment process (DEV-\>IGR-\>PROD).

This problem is addressed quite well using Features, however it could also be tackled by some CMI related modules such as Config partial export or Configuration Split

One more argument in favour of Features might be that you are able to have totally different local dev envs than the remote Dev (Dest site UUID != Source site UUID) which i guess would make CMI unusable.
> 1 votes

---
Tags: 8, features, configuration, staging
---


# Question
Title: Conditional Fields module with Google Maps
I'm trying to initially hide a geofield created with Geofield module using Conditional Fields that uses the Geolocation Field Google Maps Input Widget.

If I click on one of my conditional fields to show the Google Map Input Widget, it shows the Google Map Input with a grey background. If you resize the browser, the map tiles show again.

Does anyone know of a way to hook into the javascript somehow to reinitialize the Google Map when it is shown?

# Answer
> 0 votes
I added a possible solution at https://www.drupal.org/node/1277888#comment-11680473. Hope that helps someone.

---
Tags: 7, javascript, google-maps, entities
---


title: How do I get a simple template to work?

text:
# Question
Title: How do I get a simple template to work?
I have a Drupal module where I want to separate the html from the logic by placing it in a template file. You'd think this would be easy but I can't figure out how it's supposed to work within Drupal. When I google it I come upon massive guides on making Drupal themes or articles on focusing on a single aspect of the templating process. I downloaded and installed the Examples for Developers module which has a section for templating, but even that does not do exactly what I want and breaks as soon as I make any significant change.

I made a simple module called blob to try to get this to work. I have the following template file called blob-stuff.tpl.php:

```
<div class="container-inline">
    Hi <?php  print $myname; ?>
</div>

```

In blob.module I have

```
function blob_menu() {
  $items['blob1'] = array(
    'title' => 'Blob1',
    'page callback'    => 'blob_stuff',
    'access arguments' => array('access content'),
  );
  return $items;
}

function blob_theme() {
  return array(
    'blob_stuff'  => array(
      'template' => 'blob-stuff',
    ),
  );
}

function template_preprocess_blob_stuff(&$variables) {
  $variables['myname']='Bob';
}

function blob_stuff(){
  return 'Bob';
}

```

Which of course doesn't work, because at this point I'm just guessing.

Can anyone give me a simple, *working* example of this, following Drupal best practices?

# Answer
> 8 votes
You're on the right track, the only thing you need to do is call your theme function in your page callback, blob\_stuff(). There are two ways to do this, the preferable way is using a render array:

```
function blob_stuff(){
  $page = array
  (
    '#theme' => 'blob_stuff',
  );

  return $page;
}

```

You could also directly call your theme function, but this is not the preferable way to do it:

```
function blob_stuff(){
  return theme('blob_stuff');
}

```

But to go further with this, you've hard-coded the name Bob into your code. Usually you'll want something dynamic, pulled from the path in the URL. You can define a dynamic path with a wildcard in hook\_menu()

```
function blob_menu() {
  $items['blob1/%'] = array(
    'title' => 'Blob1',
    'page callback' => 'blob_stuff',
    // Pass the 1st index of the path (the wildcard) to your page callback
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $items;
}

```

In hook\_theme(), you'll add a variable:

```
function blob_theme() {
  return array(
    'blob_stuff'  => array(
       'variables' => array(
         'name' => FALSE,
       ),
       'template' => 'blob-stuff',
     ),
  );
}

```

Now in your page callback, you can pass the wild card to your theme function, which will output it in your template:

```
// $name comes from the wildcard in the URL
function blob_stuff($name){
  $page = array
  (
    '#theme' => 'blob_stuff',
    '#name' => $name,
  );
  return $page;
}

```

Your template will now look like this:

```
<div class="container-inline">
  Hi <?php  print $name; ?>
</div>

```

---
Tags: 7
---


title: How do I write a left join query?

text:
# Question
Title: How do I write a left join query?
I want to get the value of "vid" knowing the node ID, and get the value of "name" for those rows where "vid" is equal to 2.

If it were a plain query, I would not know how to write it; I don't know how to write a left join query.

The "plain" SQL query in Drupal is the following:

```
$result = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid'=>$nid));

```

The equivalent raw SQL query is the following:

```
SELECT did, name FROM taxonomy_index as ti LEFT JOIN taxonomy_term_data AS ttd ON ti.tid = ttd.tid WHERE vid = 2 and nid = $nid

```

# Answer
> 11 votes
You do not need to use db\_select() for a static query like this. You shouldn't, actually, see Given that db\_select is much slower than db\_query, why would I want to use it?.

You just need to pass that to db\_query(), the only thing that changed is how you add placeholders.

```
$result = db_query('select tid,name from {taxonomy_index} as ti left join {taxonomy_term_data} as ttd on ti.tid=ttd.tid where vid=2 and nid=:nid', array(':nid' => $nid));
foreach ($result as $term) {
  // $term contains the object for the taxonomy term.
}

```

See http://drupal.org/developing/api/database for more information and my blog post for generic Drupal 6 to 7 database syntax conversion information.

# Answer
> 25 votes
```
$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute();

while ($term = $terms->fetch()) {
  // $term contains the object for the taxonomy term.
}

```

# Answer
> 0 votes
```
        $catalog_pagination = db_select('taxonomy_index', 'ti')
          ->fields('pimg',array('uc_product_image_target_id','entity_id'))
          ->fields('fm',array('fid','filename'))
          ->fields('ti', array('nid', 'tid'));
        $catalog_pagination->leftJoin('node__uc_product_image', 'pimg', 'pimg.entity_id = ti.nid');
        $catalog_pagination->leftJoin('file_managed', 'fm', 'fm.fid = pimg.uc_product_image_target_id');
        $catalog_pagination->condition('ti.tid', $term_id);
        $catalog_pagination->orderBy('ti.nid', 'DESC');
        $catalog_pagination = $catalog_pagination->execute();
        $total_pages = $catalog_pagination->fetchAll();

```

# Answer
> -1 votes
//Don't forget "fetchAll()" function:

```
$terms = db_select('taxonomy_index', 'ti')
  ->fields('ti', array('tid', 'name'));
$terms->leftJoin('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
$terms->condition('vid', 2)
  ->condition('nid', $nid)
  ->execute()
  **->fetchAll();** // an array of objects

**$i = 0;
while ($i < count($terms)) {
  $terms[i]->...
  // $terms[i] contains the object for the taxonomy term.
  $i++;
}**

```

---
Tags: 7, database
---


title: Get nid of nodes which contains FPP

text:
# Question
Title: Get nid of nodes which contains FPP
I have some fieldable panel pane and I can attach this FPP in diferent nodes with panelizer functionality.

How can I get nid of nodes which contains(attach) this FPP programmatically ?

I have fpid but how can I check in which nodes use this FPP ?

# Answer
I'm looking for a similar solution, I work on a site with thousands of fieldable panel panes and need to find all the nodes that contain a certain fpid. The most promising lead I've found is: Find node programmatically by field value so if you've found a better solution (maybe using views) I'd like to hear about it.
> 0 votes

---
Tags: 7, panels
---


title: Display {{pager}} to twig file

text:
# Question
Title: Display {{pager}} to twig file
i am kinda new to drupal 8 so don't judge to hard... i have made template for drupal, that is in plain html,css and js... than i imported it to drupal correctly as drupal documentation says whit his info.yml, libraries.yml and etc files at this moment everything is OK... i have one page--front.html.twig file, that i have placed my main html mark-Up with correct regions and so on. On other hand i have views-view.html.twig file that it has:

```
 set classes = [
    dom_id ? 'js-view-dom-id-' ~ dom_id, ]%}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  {{ exposed }}
  {{ attachment_before }}

  {{ rows }}
  {{ empty }}
  {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}
</div>

```

the code of ***{{ pager }}*** is in pager.html.twig and i contains this information:

```
{% if items %}
  <nav class="pager" role="navigation" aria-labelledby="pagination-heading">
    <h4 id="pagination-heading" class="visually-hidden">{{ 'Pagination'|t }}</h4>
    <ul class="pager__items js-pager__items">
      {# Print first item if we are not on the first page. #}
      {% if items.first %}
        <li class="pager__item pager__item--first">
          <a href="{{ items.first.href }}" title="{{ 'Go to first page'|t }}"{{ items.first.attributes|without('href', 'title') }}>
            <span class="visually-hidden">{{ 'First page'|t }}</span>
            <span aria-hidden="true">{{ items.first.text|default('« First'|t) }}</span>
          </a>
        </li>
      {% endif %}
      {# Print previous item if we are not on the first page. #}
      {% if items.previous %}
        <li class="pager__item pager__item--previous">
          <a href="{{ items.previous.href }}" title="{{ 'Go to previous page'|t }}" rel="prev"{{ items.previous.attributes|without('href', 'title', 'rel') }}>
            <span class="visually-hidden">{{ 'Previous page'|t }}</span>
            <span aria-hidden="true">{{ items.previous.text|default('‹ Previous'|t) }}</span>
          </a>
        </li>
      {% endif %}
      {# Add an ellipsis if there are further previous pages. #}
      {% if ellipses.previous %}
        <li class="pager__item pager__item--ellipsis" role="presentation">…</li>
      {% endif %}
      {# Now generate the actual pager piece. #}
      {% for key, item in items.pages %}
        <li class="pager__item{{ current == key ? ' is-active' : '' }}">
          {% if current == key %}
            {% set title = 'Current page'|t %}
          {% else %}
            {% set title = 'Go to page @key'|t({'@key': key}) %}
          {% endif %}
          <a href="{{ item.href }}" title="{{ title }}"{{ item.attributes|without('href', 'title') }}>
            <span class="visually-hidden">
              {{ current == key ? 'Current page'|t : 'Page'|t }}
            </span>
            {{- key -}}
          </a>
        </li>
      {% endfor %}
      {# Add an ellipsis if there are further next pages. #}
      {% if ellipses.next %}
        <li class="pager__item pager__item--ellipsis" role="presentation">…</li>
      {% endif %}
      {# Print next item if we are not on the last page. #}
      {% if items.next %}
        <li class="pager__item pager__item--next">
          <a href="{{ items.next.href }}" title="{{ 'Go to next page'|t }}" rel="next"{{ items.next.attributes|without('href', 'title', 'rel') }}>
            <span class="visually-hidden">{{ 'Next page'|t }}</span>
            <span aria-hidden="true">{{ items.next.text|default('Next ›'|t) }}</span>
          </a>
        </li>
      {% endif %}
      {# Print last item if we are not on the last page. #}
      {% if items.last %}
        <li class="pager__item pager__item--last">
          <a href="{{ items.last.href }}" title="{{ 'Go to last page'|t }}"{{ items.last.attributes|without('href', 'title') }}>
            <span class="visually-hidden">{{ 'Last page'|t }}</span>
            <span aria-hidden="true">{{ items.last.text|default('Last »'|t) }}</span>
          </a>
        </li>
      {% endif %}
    </ul>
  </nav>
{% endif %}

```

here is mu question... when i put the ***{{ pager }}*** to my page--front.html.twig than nothing happens... why? why dose views-view.html.twig can execute the ***{{ pager }}*** and it can't views-view.html.twig? what am I doing wrong? thanks in advance

p.s: I forgot to say that in the front page i have activated the pager... and it shows correctly but i want it to be on aver location than it is right now

# Answer
If you take a look in `/core/themes/stable/templates/views`

In **views-view.html.twig** at the top, there is a commented out part that says:

* **Available variables:**
* attributes: Remaining HTML attributes for the element.
* css\_name: A css-safe version of the view name.
* css\_class: The user-specified classes names, if any.
* header: The optional header.
* footer: The optional footer.
* rows: The results of the view query, if any.
* empty: The content to display if there are no rows.
* **pager: The optional pager next/prev links to display.**
* exposed: Exposed widget form/info to display.
* feed\_icons: Optional feed icons to display.
* more: An optional link to the next page of results.
* title: Title of the view, only used when displaying in the admin preview.
* title\_prefix: Additional output populated by modules, intended to be
* displayed in front of the view title.
* title\_suffix: Additional output populated by modules, intended to be
* displayed after the view title.
* attachment\_before: An optional attachment view to be displayed before the
* view content.
* attachment\_after: An optional attachment view to be displayed after the
* view content.
* dom\_id: Unique id for every view being printed to give unique class for
* Javascript. *
* @see template\_preprocess\_views\_view()

> As you can see **pager** is listed under Available variables

---

While in `/core/themes/bartik/templates`

**page.html.twig**

* **Available variables:**
* General utility variables:
* base\_path: The base URL path of the Drupal installation. Will usually be
* "/" unless you have installed Drupal in a sub-directory.
* is\_front: A flag indicating if the current page is the front page.
* logged\_in: A flag indicating if the user is registered and signed in.
* is\_admin: A flag indicating if the user has permission to access
* administration pages. *
* Site identity:
* front\_page: The URL of the front page. Use this instead of base\_path when
* linking to the front page. This includes the language domain or prefix. *
* Page content (in order of occurrence in the default page.html.twig):
* node: Fully loaded node, if there is an automatically-loaded node
* associated with the page and the node ID is the second argument in the
* page's path (e.g. node/12345 and node/12345/revisions, but not
* comment/reply/12345). *
* Regions:
* page.header: Items for the header region.
* page.pre\_content: Items for the pre-content region.
* page.breadcrumb: Items for the breadcrumb region.
* page.highlighted: Items for the highlighted region.
* page.help: Dynamic help text, mostly for admin pages.
* page.content: The main content of the current page. *
* @see template\_preprocess\_page()
* @see html.html.twig

> As you can see **pager is NOT** listed under Available variables

---

The correct solution is that you need to modify/create the **views-view--frontpage.html.twig** and not the page--front.html.twig

So go to `core/modules/views/templates` and copy views-view.html.twig and rename it to views-view--frontpage.html.twig and make changes that you need. The views-view--frontpage.html.twig needs to go in `/theme/yourtheme/templates` folder.
> 0 votes

---
Tags: views, theming, paging
---


# Question
Title: Where are css injector files stored on the server?
I'm using this module:

https://www.drupal.org/project/css\_injector

In the backent, the files show up at this path:

```
public://css_injector/css_injector_20.css

```

But in FTP I look in public.html and I can't find theme

They are not in here either:

```
/home/vincoixt/public_html/xuzo.com/sites/all/modules/css_injector

```

So where are they?

# Answer
CSS Injector stores it's files in the files directory under:

```
'public://css_injector/css_injector_' . $crid . '.css';

```

as defined in `_css_injector_rule_uri`

This often maps to the following folder:

*sites/default/files/css\_injector*

See also: `css_injector_init` for how the files are added by that module.
> 1 votes

---
Tags: theming
---


title: Create proof of purchase codes

text:
# Question
Title: Create proof of purchase codes
I've made an Ubercart store for our schoolwear. We can't do online purchasing because we're not set up for it.

What happens right now is that when someone buys something from the catalog, they have to go to the office to pay for it. Then, the receipts get sent to the class running the store as proof the order has been paid for.

Here's what I'd like to do with our ubercart:

1. I create random codes somehow for proof of purchase in the ubercart system. Print them out, and give to the office.
2. Customer pays at the office for their item (e.g. a sweatshirt) and receives a random code from the office after purchase.
3. Customer goes to the online catalog and places their order (e.g. sweatshirt size, color, etc).
4. Customer goes to cart checkout and cannot complete checkout until they type in the random code they got from the office.
5. The class running the store gets the order through ubercart, and sees the random code as proof that the order has been paid.

I know it's a dumb system, but it's all we have. Is there a way to generate these random codes and have the customer put theirs in at the checkout?

# Answer
> 1 votes
You can create a new node type "vouchers" and use UUID module to add uuids to these nodes. When the office creates a new voucher it will automatically be assigned a uuid which you can then use as your code to give the student.

When the student shows the store their code the store can lookup that voucher in a Vouchers view using the uuid filter. Then the store can mark the voucher with a boolean "Used" custom field to show they are redeemed.

---
Tags: 7, ubercart
---


# Question
Title: Change formset default from collapsed to exanded?
I'm working with the Support Ticketing System module in Drupal 7. My clients would like to be able to see at a glance who is subscribed to notifications on a ticket. The Subscribed field is collapsed by default, meaning the client has to click on the Subscribed link to expand the field to see the users subscribed.

How can I change this so that the field is expanded when the page loads, and save my clients a click?

EDIT: The node is variable--when creating a new support ticket, it will be /node/add/support-ticket. After the ticket has been created, it could be anything.

But the particular fieldset I want to target will always have the id "edit-subscribed".

# Answer
> 2 votes
A simple `hook_form_BASE_FORM_ID_alter()` invocation can alter the default properties of the form. If you inspect the form array you'll see that the fieldset is stored in `$form['subscribe']['subscribed']`. By setting the `#collapsible` element to `FALSE`, the or `#collapsed` element to `FALSE` (if you want to retain collapsibility), the default behavior will be to keep the fieldset open.

For example:

```
function MYMODULE_form_support_ticket_node_form_alter(&$form, &$form_state, $form_id) {
  // Replace #collapsible with #collapsed to retain collapsibility.
  $form['subscribe']['subscribed']['#collapsible'] = FALSE;
}

```

---
Tags: forms
---


# Question
Title: How to register a new PHP function in Twig?
I am trying to create a theme for Drupal 7 with Twig. If I wanted to register a new PHP function, I should implement "hook\_twig\_function()" as the module explains.

My simple question is: where should I implement my functions? If I write code - as usual - inside my "template.php", I have this alert: "*Unknown "my\_module\_coolfunction" function in "sites/all/themes/abc/templates/page.tpl.twig*"

If I edited the "Extension.php" file, after every update, I would lost all my custom functions.

# Answer
> 1 votes
In the docs it says:

> ### Functions
>
> To register a new filter you should implement **hook\_twig\_function()** and return an indexed array with unique keys and new Twig\_SimpleFunction as value.
>
> ```
> function my_module_twig_function(){
>
> ```

To answer your question:

> My simple question is: where should I implement my functions?

Notice how it uses "my\_module", so clearly in your custom module **.module** file is where these function(s) should be added. If you don't have a custom module yet, then you will need to create one.

So if your custom module is named Hello Kitty, then in **hello\_kitty.module**

```
function hello_kitty_twig_function(){
    $functions = [];
    $functions['coolfunction'] = new Twig_SimpleFunction('coolfunction','hello_kitty_coolfunction');
    return $filters;
}

function hello_kitty_coolfunction($param_1,$param_2...){
    // do what you need to do, and return something.
}

```

---
Tags: 7, theming
---


# Question
Title: How to replace the Secondary menu title with the current Username?
**Secondary menu** \- this is the system secondary menu title. I need to replace it with current username, the same as the User menu block has it.

I do not want to use the User menu block because of some reasons. I would like to use the deafault system menu:

```
<?php if ($secondary_menu): ?>
  <div id="secondary-menu" class="navigation">
    <?php print theme('links__system_secondary_menu', array(
      'links' => $secondary_menu,
      'attributes' => array(
        'id' => 'secondary-menu-links',
        'class' => array('links', 'inline', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Secondary menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )); ?>
  </div> <!-- /#secondary-menu -->
<?php endif; ?>

```

Should I use token \[current-user:name\]? If so, then where (file name) and how?

**Note**: I can not do it directly at `/admin/structure/menu/manage/user-menu/edit` because Menu name field is inactive.

# Answer
I think you can simply do this by making change in `page.tpl.php` file.

Just replace,

```
'text' => t('Secondary menu'),

```

with,

```
'text' => t($user->name),

```

save and clear cache.

**Image-1:** Before changing code *(I have deleted line `'class' => array('element-invisible'),` so text can be visible)*

**Image-2:** After change,

Final code,

```
<?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            //'text' => t('Secondary menu'),
            'text' => t($user->name),
            'level' => 'h2',
            //'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>

```
> 4 votes

---
Tags: 7, users, navigation
---


# Question
Title: Why don't content changes appear on front end?
I'm new to Drupal and have been asked to update a page's content. Thought this would be easy, but I'm having trouble.

I login, click on Content, find the page I want to edit and click Edit. I make changes to the content (just text) and click 'Save'. I navigate to the page I changed and refresh but nothing has changed.

I tried clearing both my browser's cache and Drupal's to no affect.

I double checked the URL and it matches.

I reloaded the page(node?) on the back end to confirm it had saved my changes, which it did.

How do I actually update the content of a page?

# Answer
Found I was saving it as a **draft**, not as **published**.
> 1 votes

---
Tags: nodes
---


# Question
Title: Redirect users to different page after a login failure in d7
I want to redirect the users to different page if they enter the wrong login details, for that I am using following code but it is not working.

```
function bartik_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user-login")
    {
        $form["#validate"][] = "bartik_validate_login";
    }
}

function bartik_validate_login($form, &$form_state)
{
    // on successful login, the uid is set in form_state.
    if (empty($form_state["uid"]))
    {
        $_GET["destination"] = "some url goes here";
        drupal_goto("some url goes here");
    }
}

```

# Answer
> 2 votes
Please try with the correct form\_id for user login.

i.e: `if ($form_id == 'user_login') {`

The form\_id can be found in the HTML source hidden element

`<input type="hidden" name="form_id" id="edit-user-login" value="user_login">`

# Answer
> 1 votes
in form validation or form submit handler try to change 'redirect\` to go to another url, So Try

```
$form_state['redirect'] = 'some_url';

```

and Also as @David Thomas mentioned, you are some mistakes in your form alter replace `user-login` with `user_login`, but I don't think your problem is there, **I think your main question is about how to redirect to another page on your validator function.**

---
Tags: 7, users
---


# Question
Title: Is it mandatory to clear cache for each and every change made?
It takes more time to clear caches and it also needs to be done more frequently for the each CSS or functionality wise changes.

Are there any alternatives available?

# Answer
# **Disable Drupal 8 caching during development**

> When you are developing a module or a theme you have to clear Drupal's cache (render cache, dynamic page cache, Twig cache) very often to see the changes being applied. You can disable caching for development.

## Steps

1. Copy and rename the file `sites/example.settings.local.php` to `sites/default/settings.local.php`:

```
$ cp sites/example.settings.local.php sites/default/settings.local.php

```
2. Uncomment these lines in `sites/default/settings.php`:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
    include __DIR__ . '/settings.local.php';
}

```
3. **If you want to keep CSS and JS aggregation and preprocessing**, change these lines in `sites/default/settings.local.php` to `TRUE`:

```
$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;

```
4. Uncomment these line in `sites/default/settings.local.php`:

```
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = cache.backend.null';

```
5. Add the following lines to `sites/development.services.yml`:

```
parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

```

---

(source: drupal.org)
> 7 votes

# Answer
The easier way to "**Disable Drupal 8 caching during development**" is using DrupalConsole.

```
drupal site:mode dev

```

Source - Debugging compiled Twig templates
> 5 votes

# Answer
Depend on your working area.

**Steps 01)**

a) You can disable cache from /admin/config/development/performance

b) You can copy a file from sites/example.settings.local.php to sites/default/example.settings.local.php then replace by settings.local.php. For this file you have comment out the following codes from settings.php.

```
/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

Then you have to comment out the following section from /sites/default/settings.local.php

```
/**
 * Disable the render cache (this includes the page cache).
 *
 * Note: you should test with the render cache enabled, to ensure the correct
 * cacheability metadata is present. However, in the early stages of
 * development, you may want to disable it.
 *
 * This setting disables the render cache by using the Null cache back-end
 * defined by the development.services.yml file above.
 *
 * Do not use this setting until after the site is installed.
 */
$settings['cache']['bins']['render'] = 'cache.backend.null';

```

If you may get an error. Do not worry. Just enter in your browser address bar your\_site\_domain.com/rebuild.php.

**Steps 02)**

Specially for Drupal 8 there is a nice tools is called Drupal Console. Installation and documentation is great. You can see using the site http://www.drupalconsole.com/.

When you will finish the installation, I hope you will be more happy for the command line features. Like you can clear cache using the following command-

```
$ drupal cache:rebuild

```

OR

```
$ drupal cr all

```
> 2 votes

# Answer
Source Disable Drupal 8 caching during development

Steps

> 1. Copy and rename the sites/example.settings.local.php to be sites/default/settings.local.php

$ cp sites/example.settings.local.php sites/default/settings.local.php

> 2. Open settings.php file in sites/default and uncomment these lines:
>
> if (file\_exists(**DIR** . '/settings.local.php')) { include **DIR** . '/settings.local.php'; }

This will include the local settings file as part of Drupal's settings file.

> 3. Open settings.local.php and uncomment this line to enable the null cache service:
>
> $settings\['container\_yamls'\]\[\] = DRUPAL\_ROOT . '/sites/development.services.yml';

NOTE: Do not create development.services.yml. It exists under /sites

> 4. In settings.local.php change the following to be TRUE if you want to work with enabled css- and js-aggregation:
>
> $config\['system.performance'\]\['css'\]\['preprocess'\] = FALSE; $config\['system.performance'\]\['js'\]\['preprocess'\] = FALSE;
>
> 5. Uncomment these lines in settings.local.php to Disable the render cache and Disable Dynamic Page Cache
>
> $settings\['cache'\]\['bins'\]\['render'\] = 'cache.backend.null'; $settings\['cache'\]\['bins'\]\['dynamic\_page\_cache'\] = 'cache.backend.null';

If you do not want to install test modules and themes, set following to FALSE

> $settings\['extension\_discovery\_scan\_tests'\] = TRUE;
>
> 6. Open development.services.yml in the sites folder and add the following block (to disable twig cache)

parameters: twig.config: debug: true auto\_reload: true cache: false

> 7. Afterwards you have to rebuild the Drupal cache. Otherwise your website will encounter an unexpected error on page reload. This can be done by with drush:
>
> drush cr

or by visiting the following URL from your Drupal 8 website:

http://yoursite/core/rebuild.php

> 8. Finished! Now you're able to develop in Drupal 8 without manual cache rebuilds on a regular basis.
> 1 votes

---
Tags: 8, caching
---


title: How to add colorbox in views gallery

text:
# Question
Title: How to add colorbox in views gallery
> I follow these steps to achieve the gallery thumbnail in footer https://www.drupal.org/node/1497058 and now my thumbnails shows like below
>
> but only thing left is when i click thumbnail image its open the next page and show the big image but i want when i click the thumbnail the big page open on colorbox when i click on thumbnail its shown like below

# Answer
Install and enable colorbox module. And add place colorbox library in sites/all/library and rename folder to colorbox

1. Goto to admin/structure/views
2. Click edit on your views, here my view name is "Colorbox"

3. Click on your image field, eg., content:Image

4. select Formatter as **`colorbox`** and click "apply"

5. Save the view and clear the cache.

Hope it works
> 2 votes

---
Tags: views, javascript, media
---


title: unset description in user_profile_form

text:
# Question
Title: unset description in user_profile_form
I try to remove descriptions of language, files (avatar) and timezone in user profile form:

```
function bartik_form_alter(&$form, $form_state, $form_id) {

if ($form_id == 'user_profile_form') {
    unset($form['account']['mail']['#description']);
    unset($form['account']['pass']['#description']);
    unset($form['account']['language']['#description']);
    unset($form['account']['files']['#description']);
    unset($form['account']['timezone']['#description']);
   }
}

```

This code removes mail and password descriptions but it does not removes language, files and timezone descriptions.

Please, what is wrong with this code?

Thank you

# Answer
It is better to increase weight of your custom module for removing description of `timezone field`. Your code should be like below:

```
if($form_id == 'user_profile_form'){
  unset($form['account']['mail']['#description']);
  unset($form['account']['pass']['#description']);
  unset($form['locale']['language']['#description']);
  unset($form['picture']['picture_delete']['#description']);
  unset($form['picture']['picture_upload']['#description']);
  unset($form['timezone']['timezone']['#description']);
}

```
> 2 votes

# Answer
Try form after build.

```
if ($form_id == 'user_profile_form') {
   $form['#after_build'][] = 'my_module_user_profile_form_after_build';

   }
}

function my_module_user_profile_form_after_build($element, &$form_state) {
  unset($element['timezone']['timezone']['#description']);
}

```

Similarly try for language and file fields. In $element you will find language and file elements. Clear cache the cache.
> 0 votes

---
Tags: users
---


# Question
Title: How to use the LOWER function in a Drupal query?
I want the query like below:

`select * from tbl where LOWER(name) = $name`

My current query is:

```
$resultArr = db_select('adbanner', 'n')
    ->fields('n')
    ->condition(LOWER('n.blog_title'), $page, '=')
    ->execute()
    ->fetchAll();

```

But it doesn't work.

How should I write this type of query?

# Answer
> 3 votes
You can use `LIKE` instated of `LOWER`.

OR write something

```
$query->where('LOWER(n.blog_title) = :page', array(':page' => $page));

```

Refer Using SQL functions in conditionals in Drupal 7 db\_select()

---
Tags: 7, database
---


title: Can't find block

text:
# Question
Title: Can't find block
I have created a view in Drupal 8 that produces a block display. The block does not appear on the block layout page or custom block list.

In the block settings, it identifies the "Block category" as "Lists (Views)" and claims that this is "The category this block will appear under on the blocks placement page." but it isn't there at all.

I wish I had more detail to include here but this seems really straightforward and I don't know what else to add. It simply isn't there. The preview on the block display in views is fine, everything is saved. I just can't find the block to add it to a region.

# Answer
Click on the "Place Block" in the desired region and find it from there. More on block in D8 here.
> 9 votes

# Answer
View block will show up under "Disabled" section,on clicking "Place Block" we can find block we created using view and specify the region u want to show it.
> 1 votes

---
Tags: views, blocks
---


# Question
Title: Is it possible to configure read count from Statistics module?
I am using Blogs in my website, so I want to display the read count of each blog when user viewed the blog. For this I used core module called Statistics. But my requirement is differ from this available feature of Statistics module.

I want to Pre-set the read counter, So that I can manually enter the number of read counter. For example if I enter 100, next count should start 100 onward like 101,102... So how can I achieve this, Please suggest any module or programmatic way to achieve this.

# Answer
You can add a count field to your blog content type, ban access of editing or creating this field using Field Permissions for other users (they just can read) now you can set its starting value.

Then using Rules module you can create an action in a way that with each viewing of blog posts this fields value increase by one.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Redirecting user-login-form on certain page
The scenario is :

I've implemented a menu using hook\_menu and in that page it checks if user have access to creating certain content type (called request) if he/she does have access it will load content creation page using drupal\_get\_form else it checks if user is not logged in, in this case it loads user\_login\_block, again with drupal\_get\_form function, finally if user is logged in and still does not have access to create content type, it shows a message about that.

the problem is : I want user redirect to this same page after login, it redirects to user/uid by default.

This is the code for my page provider function :

```
Global $user;
$content = "";
if(user_access('create request content')){
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'request';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form("request_node_form", $node_form);
$content .= drupal_render($form);
}
else
if($user->uid == 0) {
  $login_form = drupal_get_form('user_login_block');
  $login_form['redirect'] = drupal_get_destination();//What I did to get form redirected, but no chance
  $content = '<p>For better controlling on your project flow consider signing in before submitting your file.</p>';
  $content .= drupal_render($login_form);
}
else
  $content = "Unfortunately only user of role customer can submit a request.report any problem by sending email to --------";
return $content;

```

I also tried Login Destination but it neither worked.

# Answer
There are several methods to redirect user to specified url after login

You can use Rules

```
Events: User has logged in.<br/>
Condition: User has role<br/>
Actions: Page redirect<br/><br/>

```

Another one with drupal api:

```
   function hook_user_login(&$edit, $account) {
     $edit['redirect'] = 'yourpath';
  }

```

**if it not worked** try to change `$GLOBALS['destination']` with

```
function hook_user_login(&$edit, $account)  {
  $GLOBALS['destination'] = 'yourpath';
}

```

Also you can use Login Redirect module

> Overview A simple module providing a method to redirect users according to an URL-defined parameter after logging in. Allows redirects toward non-Drupal location.
>
> Features
>
> ```
> Lightweight and minimal configuration. No module dependencies!
> Allows custom URL parameter name
> Filters XSS URL input
>
> ```
> 2 votes

---
Tags: 7, forms, redirection
---


# Question
Title: Commerce - how to set no payment for free orders when 100% coupon applied
I'm working with a one-page checkout process, where cart contents, account info, billing, payment, and coupon information are all under Checkout. Coupons are handled by commerce\_coupon.

This has worked fine, but now I want to allow free orders using 100% discount coupons, and I'm having trouble getting the right payment method selected when the coupon is applied.

To handle order totals being \<= 0 because of coupons applied, I've added additional conditions to two payment methods as follows:

Stripe - commerce-order:commerce-order-total \> 0.00

No Payment - commerce-order:commerce-order-total \<= 0.00

Here's what happens:

When the order arrives at checkout. Stripe is selected as the payment method. When the 100% coupon is applied, the order total drops to zero as expected (through an AJAX refresh), but stripe stays selected as the payment method and the no payment option is not visible. If I reload the page manually, Stripe goes away and the No payment option is selected.

What I want:

Ideally, when a user applies a 100% coupon to the order at checkout, Stripe would disappear from available payment methods and "No payment required" would be automatically selected. Even better would be to also remove the billing information if the order total is \<= 0, since there is no reason to collect it.

How can I achieve this?

I'm happy to work directly in code if that's a better approach.

# Answer
Looking at your conditions, both of them match at $0.00. You'd at least need to switch Stripe to \> 0 for it to work. However, simply adding a coupon on the checkout form doesn't trigger a refresh of the entire page. By that time, the form has already been built with the payment methods shown, and the only AJAX functionality on the pane is to switch out what payment details form elements may be visible.

You're either going to need review / payment on its own step (not a bad idea since you're using coupons anyways) or else write your own code to Ajax refresh the payment options as other elements on the form are updated.
> 2 votes

# Answer
A solution to this occurred to me. I just experimented with a setup and it appears to work.

Use the Commerce Checkout Pages module: https://www.drupal.org/project/dc\_co\_pages

Add an extra page to the checkout sequence and move the Payment piece out of Review page to the new page you create that comes after Review. This gives us the page refresh we need.

It adds an extra page/step to the checkout process but it solves the problem.

Dan
> 0 votes

# Answer
The solution I ended up at, which keeps the whole thing on one page was to edit the $form\_state before it gets to the submit handler of the checkout pane.

I did this in the submit handler of a custom pane that was earlier in the form.

```
/**
 * Custom pane: submit callback.
 */
function custom_pane_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {

  // This fixes our one page AJAX issue for full price loyalty discount
  if ($order->commerce_order_total[LANGUAGE_NONE][0]['amount'] == 0) {
    unset($form_state['values']['commerce_payment']);
  }
}

```

There's probably a more elegant way to update what's in the $form\_state but this works.
> 0 votes

---
Tags: commerce
---


title: Active user account after fill form

text:
# Question
Title: Active user account after fill form
Hi all my client wants like Dont activate user accounts instantly Upon vendor or Client submitting the form, send an email to Administrator notifying them send an email to vendor / client to confirm the registration. on drupal 8

# Answer
You can achieve that functionality by setting the config variable:

```
USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL

```

e.g: `$config->set('register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)->save();`

For example, via the admin user config page at:

*/admin/config/people/accounts*

setting *"Who can register accounts?"* to *"Visitors, but administrator approval is required"*
> 1 votes

---
Tags: 8
---


title: Contact form node integration

text:
# Question
Title: Contact form node integration
I have content type and I want to add contact button at the bottom of node page, but

I've problem so how I can add easy contact form that add node title at the message and When anonymous user goes node page called "Example 12" and after body text there is "Contact" or "Ask more" button and it goes form page.

After user left the message it goes admin content list and admins knows page where he/she goes that contact form.

Example I check page named "Example12" and there is ask more button.. I press that and I goes Ask more form and there is some fields and "You want to know more about example12" (example12 page title) and then I send that and it goes admin content list page so admins can contact me because I left mail in mail field.

So what is the best way to do it? Is there any good modules for that?

# Answer
> 0 votes
It sounds like a case for the Webform module.

> Webform is the module for making forms and surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features. Some good examples could be contests, personalized contact forms, or petitions.

https://www.drupal.org/project/webform

---
Tags: 7, nodes, forms, emails
---


# Question
Title: Where can I find the code for the user menu block?
I'm trying to code a custom user menu, but I would like to see the original code of the built-in user menu block. Where can I find it?

# Answer
> 1 votes
In user.module, all functions with prefix `user_block_` in name.

---
Tags: 7, blocks
---


# Question
Title: "Convert Media tags to markup" in CKEditor is not working
I have a strange problem when trying to add an image by 'Add media' in CKEditor 4.3.1. I know that this topic is very frequent. In most cases the resolution is to check "Convert Media tags to markup" in Text formats configuration... but I have checked this and it's still not working.

I can add an image to media library, after this I can choose an image format, but finally when I try to add the image it's not showing neither in the editor window nor on front.

Seems that no code is adding or the media tags are not converted to markup.

Do you have any ideas?

# Answer
This is most often caused by the order of the filters. Try to set this filter as the last (or first) one.

Another alternative is CKeditor's ACF (advanced content filter). This should be fixed in the latest Wysiwyg module release.
> 3 votes

# Answer
Well, @vegardjo's anwer is quite good but in case that you don't want to reorder your filters, for some reason, and the `Correct faulty and chopped off HTML` filter is afer the `Convert Media tags to markup` filter, make sure that all double quotes (`"`) are properly opened and closed in the node's body field, otherwise you wiil get unrendered items: `[[{"type":"media","view_mode":"media_original","fid":"995"}}]]`.

Perhaps this is a media's module bug.
> 0 votes

---
Tags: wysiwyg, media
---


# Question
Title: How to Display children on the Taxonomy term page?
I think my problem is quite simple but I don't manage to find the solution on the internet (I found solution for Drupal 7, but they don’t apply to Drupal 8).

I have a taxonomy like :

* Fruits
+ Red fruits
- Strawberry
- Raspberry

+ Black fruits

* Vegetables

Using Views in Drupal 8, with the preconfigured Taxonomy term, I'd like that when I click on a parent, it displays all the children terms and the nodes within these children terms. *(eg. when I click on Fruits, it display all nodes in Fruits, Red Fruits, Strawberry, Raspberry and Black fruits ; and when I click on Red fruits, it displays all nodes within Redfruits, Strawberry and Raspberry).*

Indeed, by default, when you click on a parent term, it only shows nodes within this parent term, but not those who belong to children. *(eg. when I click on Red fruits, it only display nodes within Red fruits, but not those in Strawberry or Raspberry)*

# Answer
> 6 votes
I finally found the solution. My Drupal is in french, I tried to translate, but my translation may not match the exact words :)

Go to *View* and edit the default *Taxonomy term (content)* page. In *Contextual filters* :

1. select "possède l’identifiant de terme de taxonomie (avec profondeur)" and configure like this :
    * depth : choose the depth you want
    * check *Allow multiples values*
    * check *Provide a default value* and choose *Taxonomy term (ID) from URL*
    * select *Filter by elements that share all terms*
    * check *Override title* and write *{{arguments.tid}}* in the field
    * check *Specify selection criterion* and choose *Taxonomy term (ID)*
2. select "possède l’identifiant de terme de taxonomie avec modification de profondeur"

Now, if you have a complex taxonomies, go on a taxonomy term page may display the same result several times. To prevent this, in your *View*, go to *Other* section (under Contextual filters) and click on *Query parameters*. Then check *Distinct*.

Enjoy !

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


# Question
Title: How to override theme() part in page.tpl.php file?
This question is extension of this question: Current Username title instead Secondary menu title, but it is different.

I would like to how can I override the following part of code `theme('links__system_secondary_menu',............)` which is in `page.tpl.php`

For example, if I want to change `text => t('Secondary menu')` to `text => t('Any new text')`.

*One way to do this, which I think is just change that part in `page.tpl.php` and it works perfectly.*

## OR

*Is there any other way like hook-way to do this, so we can write function in `template.php` and that override only that part?*

*from page.tpl.php*

```
<?php if ($secondary_menu): ?>
      <div id="secondary-menu" class="navigation">
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Secondary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#secondary-menu -->
    <?php endif; ?>

```

Thanks,

# Answer
You can override theme\_links\__system\_secondary\_menu() in template.php. You will name it MODULENAME\_links\__system\_secondary\_menu(), and the original code can be seen here: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_links/7.x

Copy that code, and modify it as necessary.
> 2 votes

---
Tags: 7, theming, hooks
---


# Question
Title: How to loop through fields from the Field Collection?
Here below is the code loading data present in the field collection.
$field\_collection = entity\_load('field\_collection\_item', $ids = FALSE);

In each field collection, there are many fields, i would like to loop through each fields is there a way to do it? Any help?

# Answer
I'm current "fighting" width this module, too. I don't know if it is the correct/easiest way, but it works (for me).

First you have to load the ids of the field collection fields of the node:

```
$fc_fields = field_get_items('node', $node, 'field_image_teaser');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
    $ids[] = $fc_field['value'];
}

```

I found the code above at Accessing a field collection (a related question).

To iterate over all fields you can use the following code:

```
//Get the entities
$collections = field_collection_item_load_multiple($ids);

//Loop over the array - if you have more than one entity
for ($i = 1; $i <= sizeof($collections); $i++) {
    $collection = $collections [$i];

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (isset($value['und']) && is_array($value ['und']) && isset($value['und'][0]['value'])) {
                print "Field ".$key." ".$value['und'][0]['value'];
            }
        }
    }
}

```
> 9 votes

# Answer
```
$fc_fields = field_info_instances('field_collection_item', $field_name);

```

This will probably help.
> 3 votes

# Answer
The second iteration need to be in the below way. Because of the following reasons,

* The result of `field_collection_item_load_multiple` will not be 0 based array.
* For images the url will not be in the index **\['und'\]\[0\]\['value'\]**

```
//Get the entities
$collections = field_collection_item_load_multiple($ids);
$loadedValues;
//Loop over the array - if you have more than one entity
$i = 0;
foreach ($collections as $collection) {

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (is_array($value) && isset($value['und']) && is_array($value ['und']) && (isset($value['und'][0]['value'])||isset($value['und'][0]['uri']))) {
                // print "Field ".$key." ".$value['und'][0]['value'];
                if(isset($value['und'][0]['value']))
                {
                    $loadedValues[$i][$key] = $value['und'][0]['value'];
                }
                else if($value['und'][0]['uri'])
                {
                    $loadedValues[$i][$key] = $value['und'][0]['uri'];
                }
            }
        }
    }
    $i++;
}

```
> 0 votes

# Answer
That code by @AlxVallejo will give you the field collection structure (an array of field definitions). You can use that to loop through your entity after that. So, developing on is suggestion:

```
$fc_fields = field_info_instances('field_collection_item', $field_name);
$field_list = array_keys($fc_fields);

foreach ($field_list as $key) {
  // access your current field using $field_collection_entity->{$key}
}

```
> 0 votes

---
Tags: 7, entities
---


title: Rewrite URL to routing URL

text:
# Question
Title: Rewrite URL to routing URL
I have created a routing URL like

```
login.compnay_login_form:
  path: '/u/{company_name}/login'
  defaults:
    _controller: '\Drupal\login\Controller\LoginController::login_form'
    _title: 'Login'
  requirements:
    _permission: 'access content

```

This works with http://example.com/u/testcompany/login

But I want the URL like http://example.com/testcompany/login for that I write the below routing

```
login.compnay_login_form:
  path: '/{company_name}/login'
  defaults:
    _controller: '\Drupal\login\Controller\LoginController::login_form'
    _title: 'Login'
  requirements:
    _permission: 'access content'

```

but it's not working.

Please let me know if any other way to achieve this.

http://example.com/testcompany/login

should call to

http://example.com/u/testcompany/login

may be through htaccess or any other way?

# Answer
If there is a node for each company, you can insert an alias when the node is saved. Set up the alias created for each company to start with '/company/{company\_name}', then when the alias is inserted, you can add a secondary alias for login:

```
/**
 * Implements hook__path_insert().
 */
function mymodule_path_insert($path) {
  if (preg_match('/company\/(.*)/', '/company/xyz', $matches) && preg_match('/node\/(\d+)$/', $path['source'])) {
  $company_name = $matches[1];
    \Drupal::service('path.alias_storage')->save("/u/$company_name/login", "$company_name/login" $path['langcode']);
  }
}

```

This way, the visible path will be /{company\_name}/login, but the machine name as far as Drupal is concerned with be /u/{company\_name}/login.

You could instead do this on entity\_insert and entity\_update.
> 1 votes

---
Tags: 8, .htaccess
---


title: Different views with unique pagination?

text:
# Question
Title: Different views with unique pagination?
I have 2 block (column) with 2 different content type. I need to do a unique pagination. How can I do?

Thx

# Answer
You must disable ajax on both blocks, in the view advanced options.

In the pager settings of each block you must be sure that both blocks are using the same pager ID.

As both blocks are using the same pager ID, and the page is sent through the URL (not ajax), each block will asume that that is the page it has to show.
> 1 votes

---
Tags: 7, views
---


title: Add Images in WebForm Dropdown list

text:
# Question
Title: Add Images in WebForm Dropdown list
Using Drupal 7 and WebForm Module (version 7.x-4.2). How would I go about adding images, next to text, in a dropdown listbox?

Is this even possible?

I have a dropdown with a list of products and I'd like to add an image next to the name.

# Answer
It would probably be better to have that form coded by hand where you can turn your list into a set of divs with a jQuery library, eg. http://designwithpc.com/Plugins/ddSlick

Or, you can set a background image to each option with CSS (which kinds of takes a bit of time depending on how much options you have in your select list):

```
select option[value="your_value"] {
  background-image: url(your_image.png);
}

```
> 0 votes

---
Tags: webforms
---


title: Views and QuickTabs Layout

text:
# Question
Title: Views and QuickTabs Layout
I have a view that filters based on classes (ie., 2015, 2016, 2017, etc). I want to use QuickTabs to create a tab for each class. Is this possible?

# Answer
> -1 votes
Views Better Exposed Filters did the trick. :)

---
Tags: views, blocks
---


# Question
Title: Debugging a custom module with XDebug and PHPUnit
How can I debug a custom module in Drupal 7 using Xdebug and PHPUnit? That is, I would like to debug and perhaps write some unit tests to eliminate some basic potential problems.

This is a code I inherited that is misbehaving. I am relatively new to Drupal but have some PHP skills.

Any advice is appreciated.

# Answer
> 4 votes
xdebug must be added in the PHP env. Acquia Dev Desktop, DrupalVM, Vlad and other VMs come with it out of the box. As for setting the connection up, IDEs like PHPStorm, Atom and VSCode have walkthroughs on how to do that.

For PHPUnit in Drupal 7, it is doable, but not easy. There are a few articles out there that can show you how, but they may be dated. There are two paths, using SimpleTest, and using PHPUnit on it's own.

See:

To be honest, I got going with the articles from 2008 and 2012 respectively. It requires a bootstrap file (that requires and bootstraps Drupal) that you can require in your unit test classes - this allows you to use PHPUnit bare metal.

However, you should really evaluate the tests you are doing. If they truly are unit tests and you're familiar and comfortable with PHPUnit, go for it. But if you can achieve it via SimpleTest, that may be an easier road in Drupal 7. DrupalUnitTestCase is meant for that.

---
Tags: 7, debugging
---


# Question
Title: Translation mess up with fields which are not translatable used in views
Example set up:

Content type news with fields

* Body (translatable)
* date (another date field beside node published date - translatable)
* type of news (list field - not translatable, the news should be of the same type in every language)

View with filters:

* Published: yes
* Content type: news
* Content language: currently activated interface language
* field "type of news" -\> exposed to the user

Default language in the project is German.

When I go to the view in German and choose a type of news in the exposed filter there is no problem - the expected news are listed. The problem appears when I enter the page in English and I choose a type of news -\> no results are found although the same nodes are translated into English.

I found out that this is due to the fact that the "type of news" values in the fields table are saved with the language id of the original node which is 'de' but the full view query expects the field value to have a language code 'en' (like the currently activated language has).

See this query and especially the INNER JOIN:

`SELECT node__field_date.field_date_value AS node__field_date_field_date_value, node_field_data.nid AS nid, node_field_data.langcode AS node_field_data_langcode
FROM
{node_field_data} node_field_data
INNER JOIN {node__field_news_typ} node__field_news_typ ON node_field_data.nid = node__field_news_typ.entity_id AND (node__field_news_typ.deleted = '0' AND node__field_news_typ.langcode = node_field_data.langcode)
LEFT JOIN {node__field_date} node__field_date ON node_field_data.nid = node__field_date.entity_id AND (node__field_date.deleted = '0' AND node__field_date.langcode = node_field_data.langcode)
WHERE (( (node__field_news_typ.field_news_typ_value = 'press') )AND(( (node_field_data.langcode IN ('en')) AND (node_field_data.status = '1') AND (node_field_data.type IN ('news')) )))
ORDER BY node__field_date_field_date_value DESC
LIMIT 10 OFFSET 0`

You may see that the inner join expects the langcode field in node\__field\_news\_typ to be the same value as node\_field\_data.langcode which is 'en' when I enter the view in English. But looking into the table of node\__field\_news\_typ I do not find one entry with 'en' as the field is not set to be translatable and all the nodes are originally written in German.

Maybe I did not get some basics of the multilanguage architecture in Drupal 8 but I find it a little bit strange that fields which are not translatable filter out nodes in views where a filter is set to "current active language". Is there not UNDEFINED\_LANGUAGE ('und') anymore? Why do fields get a fix languagecode when they are not translatable? How can I avoid this behavior?

It seems to me that there is no other way as setting the field to translatable although I want to assure that translated nodes have the same value?!

# Answer
> 3 votes
This is known core bug, see https://www.drupal.org/node/2451657. The patch there should work well.

---
Tags: 8, entities, views, i18n-l10n
---


# Question
Title: D8 Migration: Can 'Default Bundle in Destination Plugin be dynamic?
My goal is to take an existing D6 content type ('mini') and migrate it into one of two specific D8 content types based on its current D6 URL Alias (either 'course' or 'page') and where this alias falls in the hierarchy.

I've have successfully written a simple source plugin that adds the alias into RowSource.

How do I control the destination plugin so I can migrate into the appropriate bundle - either 'page' or 'course'? Is there any property of $row that can be adjusted to do so?

Or is this process more involved?

I know that nodes use the 'entity:node' destination plug-in, but how can I extend this per above? It's unclear to me what exact class the destination plug 'entity:node' represents

Any insight would be much appreciated.

Thanks!

# Answer
In your config, use a row instead of the default value plugin.

Instead of this:

```
process:
  type:
    plugin: default_value
    default_value: course
  title: title
  etc.

```

use this:

```
process:
  type: target_bundle
  title: title
  etc.

```

Then you can set the target\_bundle dynamically in your source class's prepareRow function.

```
$row->setSourceProperty('target_bundle', $target_bundle);

```
> 2 votes

---
Tags: 8, migrations
---


# Question
Title: how to use user_save with custom column?
I added custom column in users table, i would like to use user\_save to create new user programmatically. How can i do that? This code doesn't work for custom columns:

```
$new_user = array(
                        'name' => 'Foo',
                        'pass' => $pwd,
                        'mail' => $email,
                        'signature_format' => 'filtered_html',
                        'status' => 1,
                        'language' => 'en',
                        'timezone' => 'Europe/Berlin',
                        'init' => $email,
                        'custom' => $custom_string,
                        'roles' => array(
                            DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                            $role->rid => $role->name,
                        ),
                    );

                    $new_account = user_save(NULL, $new_user);

```

Everything except custom gets inserted, if i am not wrong it's default drupal columns for each user's table. Thanks

# Answer
Manually adding extra columns in tables will rarely work for Drupal as there are dependencies and references that have to be honoured.

The correct way would be something along the lines of this case.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Allign block content next to title - CSS
My goal is to display a button group to the right of the page title. Currently it resides in *region-content*, which wastes space. I tried adding my own class to the *div* that contains *btn-group* class and use *margin-top* to move it up, but as soon as I save content, I get system help message that overlaps with the button group.

I also tried to add the block to other regions and get same thing if, say, I use breadcrumbs.

What's the best way or what are the classes I should use to position my block with button group to the right of the page title in *main-container* instead of *region-content*?

# Answer
Okay, so after looking at your demo, there's a couple things you can do.

The easiest method is to simply float `#block-block-16` right, float `.page-header` left, set `#block-system-main` to `clear: both`, and be done with it.

But that's not great because we are kinda circumventing `div.region.region-content` by doing that. It'd be better if the header and the buttons actually shared a common parent. That seems to be what you truly want to do here. We can accomplish that with some JavaScript. That will also help with the minor problem the first solution introduces of having your gray underline not stretch across the page.

```
$(function() {

  $('#block-block-16').insertAfter($('h1.page-header'));
  $('#block-block-16, h1.page-header').wrapAll('<div id="top-container" class="clearfix"></div>');

});

```

From here, again we'll just float the buttons right and the page header left as before.

We can also take care of some details and clearfix the new div (included in the JS) and perhaps change our bottom border from being set on the h1 to being set on our new div, so that it stretches across the page, below the header and buttons.

You may also choose to remove the 9px padding-bottom on the h1 and instead change that to a 9px padding-top on `div.region.region-content`.

Hope that helps!
> 0 votes

---
Tags: theming, bootstrap-theme
---


# Question
Title: How can I return the selected radio button text on a form
I have two radio buttons on a form for example as below:

() Paul

() James

When I use the follwoing code, I am getting the values 0 or 1 depending on my selection. How can I get **Paul** or **James**? Thanks for your help.

```
$chosen =$form_state['values']['name_options'];

```

# Answer
> 1 votes
If the value you want is not in `$form_state` you can check in the `$form` parameter for the original form definition.

e.g:

```
$chosen = $form['name_options']['#options'][$form_state['values']['name_options']];

```

---
Tags: forms
---


title: How do I override the view field?

text:
# Question
Title: How do I override the view field?
I want to override taxonomy term view views-view-field.html.twig to style the list of taxonomy term content.

I can't seem to find what the correct override is. My debug suggestions are not suggesting anything.

I have tried:

```
views-view-fields--taxonomy-term--%.html.twig
views-view-fields--taxonomy-term.html.twig

```

What is the correct template name to target the views-view-fields of the taxonomy term view?

# Answer
> 1 votes
```
views-view-fields--taxonomy-term.html.twig

```

This is the correct template suggestion. For it to work however, the default taxonomy view must be configured to render the content as fields rather than as the content its self.

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


# Question
Title: Drupal Commerce does not allow any payment if payment pane is not in review order page
If I do not put the *Payment* pane in the *Review Order* page, then no payment method works and it just goes to checkout complete. Even if I check *Require a payment method at all times* it makes no difference.

Is this a bug or is it something I'm missing?

The attached image works but not when payment is in **payment** when it is it skips payment entirely.

# Answer
I guess 'payment' means 'choose payment method'
> 0 votes

# Answer
I see this is a very old question, but I think that since the Payment page is normally not shown (it's only for redirecting to offsite payment), moving the Payment pane there (which as charlesd mentions, is where you choose the payment method) just never shows up and skips directly to the Checkout Complete page.

It's possible to move the Payment pane to another page earlier in the checkout sequence, just not to the Payment page.
> 0 votes

---
Tags: commerce
---


# Question
Title: Infinit loop when I submit a form and redirect to this form with an additionnal parameter
I created a form. When the form is submitted, I want redirect to the form page and pass an additional parameter.

I do this :

```
public function buildForm(array $form, FormStateInterface $form_state, $results = null)
{
  if ($results) {
    customlog($results, "RESULTS !!!"); // write in a log file
  }
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit'),
  ];
  return $form;
}

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

public function submitForm(array &$form, FormStateInterface $form_state) {
  $results = array();
  // do some work ...
  // ...
  // $results is a simple associative array
  customlog("I pass here !", __FUNCTION__); // write in a log file
  return \Drupal::formBuilder()->getForm('Drupal\mycustommodule\Form\MyCustomForm', $results);
}

```

My issue is when I submit this form, the page indefinitely load. When I check my log file, I realize that the "I pass here !" log is repeated indefinitely.

Where is my mistake ? When the form is submitted, how can I redirect to the same form with an additional parameter without this infinit loop ?

Thank you :)

# Answer
If you want to redirect to the form page you need to do something like this in your submit handler:

```
$form_state->setRedirect('NAME_OF_THE_ROUTE_OF_YOUR_FORM', $route_paramters, $options);

```

Maybe you can insert your results by query parameters?! Or save them in a session so that they can be used again. But the $form\_state-\>setRebuild seems to be smarter to me.
> 1 votes

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


# Question
Title: Setting a field on an entity form to be required
I have a multi-value entity reference field on a content entity that I am displaying using a custom form class that extends ContentEntityForm, which extends EntityForm, which extends FormBase.

I'd like to set the field to be required: when using this form, you must select at least one entity to reference. I don't want to make this an entity level constraint however, as it's not absolutely required in all circumstances.

In a form alter hook (as well as in my custom form class) I've tried setting things like

```
  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['0']['#required'] = TRUE;

```

Some of these show up when I kint the form after saving it, some are set back to FALSE, but none of these prevent the form from saving when there is no value in my field. But regardless of that, I don't see anything in FormBase, EntityForm or ContentEntityForm that will validate a required element anyway.

Do I really need to create my own validation handler? Or is it something else that I'm missing?

# Answer
> 3 votes
It is really annoying... I struggled with that several times as well. The important key is places deeper in the array. Take a look on

```
$form['field_ref_download']['widget'][0]['target_id']['#required']

```

---
Tags: forms, 8
---


# Question
Title: Date time formats: October not correctly written in German
I created a time format in Drupal administration (admin/config/regional/date-time) with the following settings in EN/ DE:

```
DE: d. F Y -> 05. October 2016
EN: dS F Y -> 05th October 2016

```

The problem is that "October" is written in German like "Oktober" ("k" instead of "c"). The strange thing is that the translation works fine with every other month ("May" for example becomes "Mai" in German) but just the October is written wrong. This appears to be an issue no matter where the date field is rendered, in views or node detail page.

Additionally this seems to be an issue with the PHP date format as it the same problem when using date('d. F Y', $timestamp). Can anyone give me a hint how to solve this issue?

# Answer
The name of the month can be change via interface translation - see comment of Drupaler
> 1 votes

---
Tags: 8, i18n-l10n, datetime
---


# Question
Title: How to install patched Paypal module in Drupal Commerce?
I am not an expert of Drupal, but I am trying to configure a site with Drupal Commerce, and in particular, the PayPal module.

I need the following two patches: https://www.drupal.org/node/2415489 https://www.drupal.org/node/2415501 that, if I understood correctly they are not merged into the paypal module yet.

So, what I did is to manually download the PayPal module, manually apply the patches (unfortunately they conflict each other, so I applied one with the `patch` command and the other by manually diff the files) and I tar.gz everything.

The resultant module is here: https://dl.dropboxusercontent.com/u/7968745/commerce\_paypal-7.x.2.3.tar.gz

Now, if I try to install this module I get the following error:

```
Unable to create directory 'temporary://update-extraction-bde81194/.'

```

But if I try to install any other module, it works.

BTW: I don't know if this is relevant or not. Before installing my custom-made module, I disabled and uninstalled the PayPal module, but if now I look for the modules in my Drupal installation I still find the PayPal module (but disabled)

# Answer
> 1 votes
You have to make sure that the temporary directory is configured at `admin/config/media/file-system` is writable.

In my case `/tmp` is writable, as per the settings in the screenshot below.

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


# Question
Title: How to grant access to specific nodes to anonymous users?
My site has a front page, an 'about us' and 'T&C' pages which are all created as 'basic page' types, and I want to allow anonymous users to access them. I have tried this hook below, but it does not seem to work because I am always redirected to the login page (using LoginToboggan if that matters).

```
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'basic page' && $op == 'view') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}

```

# Answer
> 1 votes
If you need content access to roles by content types, you can try using Content Access module.

> This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

# Answer
> 0 votes
Type is the machine name of the content type and content type name with space is replaced by _ . And drupal default basic page machine name is page . Please try the below code :

```
function mymodule_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($type == 'page' && $op == 'view') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }
  return NODE_ACCESS_IGNORE;
}

```

---
Tags: nodes, hooks
---


# Question
Title: How do I programatically create a context?
I'm using the migrate module to move content into a Drupal site. Some of this content needs to be created as blocks and added to a region using contexts. I have the creation of blocks (actually, boxes) working using a purpose-built module, but I don't know where to begin on the context side of things - looking for something like `add_block_to_context()` but I cannot find anything. Any ideas?

# Answer
> 6 votes
After checking the code used in the context test units for Drupal 6:

```
ctools_include('export');
$context = ctools_export_new_object('context');
$context->name = 'testcontext';
$context->conditions = array('path' => array('values' => array('admin')));
$context->reactions = array('debug' => array('debug' => TRUE));
$saved = context_save($context);

```

You can easily code your reactions or conditions then save the context.

BTW to get all context you can use context\_context\_list().

# Answer
> 3 votes
The easiest way to do this, is to actually create the full context with all blocks first and then export it, using the built in export option or features.

# Answer
> 0 votes
I have fixed this issue using below codes.

Before that use context to export all values to check blocks array format or some structure.

```
$context = new stdClass();
$context->disabled = FALSE;
$context->api_version = 3;
$context->name = 'name-of-context';
$context->description = 'Description';
$context->tag = '';
$context->conditions = array(
'path' => array(
  'values' => array(
    'node/120' => 'node/120',
  ),
),
);
$context->reactions = array(
'block' => array(
  'blocks' => call_function_to_generate_block_array(),
),
'theme_html' => array(
  'class' => 'myclass',
),
);
$context->condition_mode = 0;
context_save($context);

```

***Note:*** you can save all these values into one script file & can use`drush scr script.php` command to execute it.

---
Tags: blocks, migrations, 7
---


title: How to use custom tables in any views?

text:
# Question
Title: How to use custom tables in any views?
I have created a custom table in drupal database. I need to use this table data in views . For this I have used schema module but its displaying only new views. But I need to use these table data in all views in our site.

Any suggestions?

# Answer
You can use `hook_views_query_alter` and alter the views query by merging your custom query with the views SQL query itself.

Also there is an option in "advanced" section - theme suggestions There you can write your custom query to fetch results into tabular format.
> 1 votes

# Answer
While `hook_views_data()` definitely allows to expose the custom table to the Views module, I would recommend you to use one of the following modules, so that you don't have to write code every time you create a custom table.
> 1 votes

---
Tags: 7, views
---


title: How do I access update.php using nginx?

text:
# Question
Title: How do I access update.php using nginx?
I would like to use Drupal 8 (beta) with nginx. It works correctly, except update.php. It doesn't find it.

After analysing .htaccess (which is not processed by nginx) I realized that there is no real update.php file; it is served by index.php.

Does anyone have a working nginx configuration (with php5-fpm) which works with Drupal 8 beta, and that makes also update.php work?

# Answer
> 1 votes
I had the same issue. This change worked for me (Taken from https://www.drupal.org/node/2353907#comment-10567306)

```
location ~ ^/(index|update)\.php(/|$) {
    fastcgi_pass unix:/var/lib/php5-fpm/web1.sock; # might be different
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    fastcgi_intercept_errors on;
  }

```

Hope that helps

# Answer
> 0 votes
You need to set your nginx config file to rewrite 404 error to index.php

Just added this:

```
error_page 404 = @rewrite;
location @rewrite {
  rewrite ^ /index.php;
}

```

# Answer
> 0 votes
You need to do the rewrite in your vhost for nginx. (nginx does not use .htacces and .htacces should be disabled in your config!

but here you go

```
    location ~ ^/(install|rebuild)\.php$ {
   # Are now present in the core location and need to be accesed directly so rewriting them. -- Lawri van Buël
    if (!-e $request_filename) {
        rewrite  ^/(.*)$  /core$uri last;
        break;
    }
}

```

I have tested it in a broken D8 (It had some module error) but tested the rewrite parts using nginx and its debug log.

-- Removed update as I could not find it in the latest beta (I build it against an old version of d8 I now realize)

# Answer
> 0 votes
The change matters to Nginx config is that Drupal 7 update.php URL is like

```
/update.php?op=info or /update.php?op=selection

```

while Drupal 8 update.php URL pattern is like

```
/update.php/selection or /update.php/result

```

So, what we need to change in the existing configuration is very simple. Look for your matching condition like

```
location ~ \.php$ {...}

```

then, change it to

```
location ~ \.php$|^/update.php {...}

```

For more details, please see my blog: https://insready.com/en/blog/update-your-nginx-config-support-drupal-8

---
Tags: 8
---