# Question
Title: Does CAPTCHA Module still disallow page caching?
I'm trying to manage spam entries into my websites' contact forms. Currently using the Drupal Captcha module for Drupal 6. http://drupal.org/project/captcha

Based on this report: http://3dg.me/web/drupal-caching-incompatible-with-captcha \- I learned that page caching can interfere with the operation of the module. Is this still relevant? Does this apply to allow image captcha based modules?

# Answer
> 5 votes
Yes, the Captcha module is still incompatible with Drupal's caching. In fact, once it is installed, it gives you a nice warning on Drupal's performance settings page.

> The CAPTCHA module will disable the caching of pages that contain a CAPTCHA element.

Most challenge/response modules like this will disable caching. The Honeypot module, which helps in deterring spam bots from completing forms, does that too.

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

If you need to avoid spam bots fill forms too quickly, you can use the Honeypot, which disable caching when *Honeypot time limit* is set. Using only the honeypot field, caching is not disabled.

# Answer
> 2 votes
It depends on the challenge and the module version: If you are using the ReCaptcha module for providing the captcha you may use the current dev version which enables caching, see also issue Add support for cacheable captcha's (recaptcha).

---
Tags: caching, captcha
---


title: How to load all aliases of a domain

text:
# Question
Title: How to load all aliases of a domain
I'm using the modules domain and domain\_alias on Drupal 8.

I need to load all the aliases of a given domain.

I have tried the following without success:

```
$aliases = \Drupal::service('entity_type.manager')->getStorage('domain_alias')->loadByHostname('my.domain.com');

$aliases = \Drupal::entityTypeManager()->getStorage('domain_alias')->loadByProperties(['hostname' => 'my.domain.com']);

```

# Answer
Got it.

The 'hostname' is not a property of the alias. The way to get the aliases is:

```
$aliases = \Drupal::entityTypeManager()->getStorage('domain_alias')->loadByProperties(['domain_id' => 'my_domain_id']);

```

Note that 'my\_domain\_id' is specific to the domain that you are trying to get the alias for.
> 1 votes

---
Tags: domain-access
---


# Question
Title: How to make role field on approval in the Edit Profile page by Admin
This website has over 1000 users with different profiles. Each user choose their profile on registration. On their Edit Profile page, the authenticated users can change or add more profiles to themselves. This was achieved by using the Role Delegation module and by changing some permissions.

Now, I would like to add another feature, namely, the *role changing* has to be **approved by the administrator**. This question is actually proposing what I'm looking for, but I cannot select the Role field, only the standard fields, such as First Name, or Last Name, or Email.
How can I achieve this additional feature?

Thanks!

**UPDATE 1**

I can try to narrow the question.
What I'm looking for is a **rule**, which notifies the *Admin* when a normal user changes its role, by sending an email. If possible, the rule should keep this edit unsaved until the Admin approves the change. Is it possible to achieve this kind of action?

# Answer
You can't allow the users to change the role/profile directly, if this is what you want. What you'll need instead is another field to act as a proxy for the roles, so you would have a checkbox for each one.

Then you can use a rule to detect a change to the user and if there is a difference in the old and new values of this field, send an email to the admin.

I think this can probably all be done with contrib modules though it will not be a trivial matter, and would be easier to build and maintain with a little custom code acting as glue.
> 0 votes

---
Tags: users, rules
---


title: fast saving single field value

text:
# Question
Title: fast saving single field value
I've got around 70k nodes of specified type on my site. I need to run an update on them. Some operations and setting one field to desired value. `node_save` is really slow and it causes crashes (too long callstack mayby). Is there faster way to write info on this one particular field?

There was `field_attach_update` mentioned in one post, but it isn't much faster.

EDIT: There is quite complex view built on this node type, but is not working on this field which I want to update.

# Answer
I'd definitely go for `field_attach_update`.

The idea is simple. Just load the node and save it using field\_attach\_update.

Ex:

```
$node = node_load($nid);
$node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
field_attach_presave('node', $node);
field_attach_update('node', $node);
  // Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

```

This will not changed any timestamp or any other hook that node\_save usually invokes. Loading the node will also invoke some hooks so probably it's not that efficient.

If you have the nid and if the node structure is dead simple, you can do it like this as well:

```
 $node = new stdClass();
 $node->nid = $nid; // Enter the nid taken. Make sure it exists.
 $node->type = 'article';
 $node->field_name[LANGUAGE_NONE][0]['value'] = 'New value';
 field_attach_presave('node', $node);
 field_attach_update('node', $node);
  // Clear the static loading cache.
 entity_get_controller('node')->resetCache(array($node->nid));

```

Anyways, if you are trying to update anything other than than fields, this will no work (comment status, published status, etc). Also If you are using node\_save, cache for the particular node will be cleared automatically for different methods we need to clear it with 'entity\_get\_controller'.

**Update:** It appears that you should also call `field_attach_presave()` to let other modules process the field input properly. File module, for example, uses it to set the file status to permanent using this hook. I have updated my 2 examples above.
> 31 votes

# Answer
Having tried all the approaches mentioned in the other answers I got very slow update times (about 7 days for 700.000 nodes of a node type with 20+ fields) until I found this article: http://www.drupalonwindows.com/en/blog/only-update-changed-fields-or-properties-entity-drupal .

After implementing something like the below code in a hook\_update I reduced the update time to 2 hours, which I think is manageable.

```
if (!isset($sandbox['storage']['nids'])) {
    $sandbox['storage']['nids'] = [];
    $query = 'SELECT {nid} FROM node WHERE type = \'article\';';
    $result = db_query($query)->fetchCol();
    if ($result) {
      $sandbox['storage']['nids'] = $result;
      $sandbox['storage']['total'] = count($sandbox['storage']['nids']);
      $sandbox['storage']['last_run_time'] = time();
      $sandbox['progress'] = 0;
    }
  }

  $amount = 300;
  $nids = array_slice($sandbox['storage']['nids'], 0, $amount);

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids, [], TRUE);
    foreach ($nodes as $node) {
      // Lets manipualte the entity.
      $article_wrapper = UtilsEntity::entity_metadata_wrapper('node', $node);
      // Eventual logic here.

        // Field to update
        $article_wrapper->my_field = 'my_value';
        $article_wrapper->save();

    $sandbox['progress']++;
    }
    $sandbox['message'] = 'Runs left: ' . (($sandbox['storage']['total'] - $sandbox['progress'])/$amount) . ' Progress: ' . (($sandbox['progress'] * $amount)/$sandbox['storage']['total']) . '%';
    $sandbox['storage']['last_run_time'] = time();
    unset($nids);
  }
  $sandbox['storage']['nids'] = array_slice($sandbox['storage']['nids'], 100, count($sandbox['storage']['nids']));
  if (!empty($sandbox['storage']['total'])) {
    $sandbox['#finished'] = ($sandbox['storage']['total'] - count($sandbox['storage']['nids'])) / $sandbox['storage']['total'];
  }
  return $sandbox['message'];

```
> 3 votes

# Answer
I suggest `field_attach_update` too, and not a direct SQL query, because sql doesn't update the node cache object, and in your next `node_load` you wont load the updated field value, you will load the old value

`field_attach_update` is much better than direct SQL query.
> 2 votes

# Answer
If you don't want to save field data without causing the standard events and actions to happen then you can use drupal\_write\_record.

Here is an example to insert Hello World into the body field for a node of type article with an id of 1.

```
$values = array(
  'entity_type' => 'node',
  'bundle' => 'article',
  'entity_id' => 1,
  'revision_id' => 1,
  'language' => 'und',
  'delta' => 0,
  'body_value' => 'HELLO WORLD',
  'body_summary' => '',
  'body_format' => 'filtered_html',
);
drupal_write_record('field_data_body', $values);
drupal_write_record('field_revision_body', $values);

```

If your site is multlingual then you will want to use 'en' or the language of your content instead of 'und'.

If you are doing revisioning, you will have to be careful to insert the right revision id, otherwise you can simply insert the same value as the entity\_id.

Note how this data is inserted into two tables field\_data\_\* and field\_revision\_\*. You should insert into both to make sure the site works as desired.

After running this you will then need to clear the caches for the fields to show up depending on how your caching is setup.
> 2 votes

# Answer
For a simple update like this where lots of nodes need to be updated, I always use a MySQL update statement. Yes, caching needs to be taken into consideration but you can just flush the cache after you're done and it is all good. You, of course, need to be familiar with the data structure but it is relatively simple in Drupal 6. (although horrendous in Drupal 7)
> 2 votes

# Answer
I even had the same requirement of updating a field for all the nodes of a particular content type. I used node\_load\_multiple and field\_attach\_update.

```
$nodes = node_load_multiple(array(), array('type' => 'content_type_name'));
foreach ($nodes as $node) {
  $node->field_name['und'][0]['value'] = 'field value';
  field_attach_update('node', $node);
}

```

I ran it through drush and it was pretty quick.
> 1 votes

# Answer
Have you considered doing these updates directly into the database using mySQL? It's probably the simplest & fastest way to achieve what you want.

Here is a simple example. You can execute such a command from the 'SQL' tab in phpMyAdmin. Imagine you have a content type called Member Profile. In it you have a field named 'Type of member' (e.g. company, individual, organisation). Let's say you want to update all occurrences for 'COMPANY' to 'company'. The following command will do just that.

UPDATE content\_type\_member\_profile SET `field_type_of_member_value` = 'company' WHERE `field_type_of_member_value` = 'COMPANY';

Also, checkout Get Started with MySQL
> 0 votes

---
Tags: 7, entities, nodes
---


# Question
Title: Use image field in an entity query condition
How to use image field in a condition of an entity query?

To get X nodes which have no image as value of field\_image I've tried this:

```
$nids = \Drupal::entityQuery('node')
->condition('type','X')
->condition('field_image',NULL , '=')
->execute();

```

it doesn't work I got always empty result.

# Answer
You could try: $query-\>notExists('field\_image');
> 4 votes

---
Tags: 8, entities
---


title: How to override node content in Twig

text:
# Question
Title: How to override node content in Twig
I have created no of nodes as content type as Article in my website(techladder.in). But I am not getting the right file where I can override the content of the file.

For example, I need to display author information above the Disqus comment section.

I was able to override the node file in my theme at following path: theme/templates/content/node--article.html.twig as following:

```
     {%   set classes = [
        'node',
        'node--type-' ~ node.bundle|clean_class,
        node.isPromoted() ? 'node--promoted',
        node.isSticky() ? 'node--sticky',
        not node.isPublished() ? 'node--unpublished',
        view_mode ? 'node--view-mode-' ~ view_mode|clean_class,   ] %} {{ attach_library('classy/node') }} <article{{ attributes.addClass(classes) }}>

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

      {% if display_submitted %}
        <footer class="comment-submitted">
          <div{{ author_attributes.addClass('node__submitted') }}>
            {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
            {{ metadata }}
          </div>
        </footer>   {% endif %}

      <div{{ content_attributes.addClass('node__content') }}>
        {{ content }}   </div>

    </article>
{% if teaser %} <div class="section-divider"><hr class="section-divider"></div> {% endif %}

```

But here, I am not able to find a file where I can override the `content` of the node.

Does anyone has suggestions how can I do it in Drupal 8.

# Answer
`content` is just the render array composed of renderable elements.

If you want to break up the fields, then you need to not use `{{ content }}` and instead call each field where you want them:

`{{ content.field_MYFIELD }}`

Those fields are controlled by their field templates.

An improvement on your code would be to not check for view modes in one template, but just make each view mode a template like `node--article--teaser.html.twig`, `node--article--full.html.twig`, `node--article--some-other-mode.html.twig`. It will make your code cleaner.

So you'll need to debug and find what the `content` variable has, and just start outputting it where you want them to render in the template.
> 2 votes

---
Tags: theming
---


# Question
Title: Redirect module does not allow redirection for existing node's path alias
I installed fresh Drupal 8 and after that the Redirect module with proper settings. After adding the redirect rule for a path alias it does not work but it saves data properly into the database.

But it works if I add internal path like `node/{id}`. In this case it works for internal path as well as path alias.

I just wanted to redirect it on the basis of path alias only. Is it possible to add only path alias for the redirection?

# Answer
> 0 votes
I just ran into this also. You may want to look at https://www.drupal.org/project/url\_redirect to see if it fits your needs.

---
Tags: 8, redirection
---


# Question
Title: How can I link to a specific comment on drupal.org?
I'm aware that you can use `[#1234]` syntax in posts on drupal.org issue pages.

However, is there any syntax to point to the specific comment, like: `[#1234:12]`?

I was using it before, but I forgot the syntax and I can't find it anywhere.

# Answer
> References to project issues in the form of `[#1234]` (or **`[#1234-2]` for comments**) turn into links automatically

That is from the very bottom of compose tips.

So just replace the colon with a hyphen and your guess would have been perfect.
> 7 votes

---
Tags: community-official-site
---


title: Dependency Injection if service exists

text:
# Question
Title: Dependency Injection if service exists
Is there any way to use dependency injection in a conditional way, i.e. only if a service exists similar to \Drupal::hasService().

I have a created a service in module A and in module B I have an EventSubscriber that should use the service from module A, but only if present of course.

Static I would do sth. like: if (\Drupal::hasService('module\_a.my\_service')) { \Drupal::service('module\_a.my\_service')-\>mymethod(); }

Is there any possibility to do this when injecting the service?

# Answer
One possible way to handle this situation is for your Module B to define a default, stub service with the same type signature (ie, `Interface`) as the one you need). Use that in the YAML. Then, in your Module A, you can alter the service to the one that the module provides.

That said, I do agree with the comments that you may be bypassing one of the benefits of DI, and creating a tight coupling between your two modules. Read the linked article to see when it is appropriate. Core uses it for the language and workspaces subsystems.
> 2 votes

---
Tags: 8, services, dependency-injection
---


# Question
Title: Does the summary area support input filters?
I have noticed that text filters placed in the summary area don't seem to work, that the raw text appears in the summary info when posted in Twitter, Facebook and the like.

Is that some inherent problem in the summary area, or is it something like the Metatag filter that sends the unfiltered text directly to Twitter and Facebook?

I will check whether the Metatag output can be filtered in the mean time.

# Answer
~~Text filters should definitely work in the Summary. You can test this by creating a View that uses the formatter "Summary" or "Summary or Trimmed" and using an input format like Plain Text in the Summary. HTML tags should be stripped from your View.~~

~~It sounds like something else is at play here.~~

~~Edit your Content Type (Structure \> Content Types \> Your Content Type) and look for the field in question (probably the Body field.)~~

~~Make sure Text Processing is set to "Filtered Text (user selects text format)" and the "Summary input" box is checked.~~

~~In the "DEFAULT VALUE" fieldset, select the desired Text format (e.g., Full HTML).~~

**EDIT:**

I'm sorry, you are correct. The built-in summary is just a summary and it does not support text filters. HTML in that field will be stripped.

This thread on Drupal.org says this won't be fixed until Drupal 9:

https://www.drupal.org/project/drupal/issues/1529188

The workaround is to create a new field called "Summary" and set its text format to the desired WYSIWYG format:

Then, manage the display of your content type to hide the new field from the **Default** view mode.

In the **Teaser** view mode, hide the Body field and show the Summary field instead.

The other solution is to edit the "Filtered HTML" text format to allow the `<span>` tag and other HTML that you require.

Honestly, it's a bit ridiculous that you have to do this to get what you want. I guess it's just one more reason to look forward to Drupal 9!
> 1 votes

---
Tags: 7, input-formats, meta-tags, entities
---


# Question
Title: How to get the node ID in jQuery/JavaScript
Is there a definitive, universal way to do this? For example using some environment variable that comes with `Drupal.behaviours`?

I have done some research and there seems to be no common answer.

# Answer
> 14 votes
As mentioned above, Drupal core has no use for the node ID on the client side so it doesn't pass it through. if you want access to it you'll need to add it manually:

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full') {
    $setting = array('MYMODULE' => array('currentNid' => $node->nid));
    $node->content['#attached']['js'][] = array(
      'data' => $setting,
      'type' => 'setting',
    );
  }
}

```

Then on the client side you'll have access to it through `Drupal.settings`:

```
var currentNid = Drupal.settings.MYMODULE.currentNid;

```

# Answer
> 6 votes
As mentioned by MPD in his answer, working with the default css-classes Drupal generates for the element is a easy solution which works without custom PHP code.

Here is our implementation:

```
(function($) {

  /**
   * Find Drupal Node ID based on <body> element classes.
   *
   * @return Node ID or false
   **/
  function getCurrentNodeId() {
    var $body = $('body.page-node');
    if ( ! $body.length )
      return false;
    var bodyClasses = $body.attr('class').split(/\s+/);
    for ( i in bodyClasses ) {
      var c = bodyClasses[i];
      if ( c.length > 10 && c.substring(0, 10) === "page-node-" )
        return parseInt(c.substring(10), 10);
    }
    return false;
  }

  /**
   * Example usage...
   *
   **/
  Drupal.behaviors.yourModuleNameHere = {
    var nodeId = getCurrentNodeId();
    if ( nodeId ) {
      // Node ID found.
      // ...do something with it.
    } else {
      // Node ID not found. Guess we are not on a node page
      // ...handle this case with care too.
    }
  }

}(jQuery);

```

# Answer
> 3 votes
The default `template_preprocess_html()` has this bit of code in in

```
if ($suggestions = theme_get_suggestions(arg(), 'page', '-')) {
  foreach ($suggestions as $suggestion) {
    if ($suggestion != 'page-front') {
      // Add current suggestion to page classes to make it possible to theme
      // the page depending on the current page type (e.g. node, admin, user,
      // etc.) as well as more specific data like node-12 or node-edit.
      $variables['classes_array'][] = drupal_html_class($suggestion);
    }
  }
}

```

This will stick on classes to the `<body>` element line `page-node-123`. If you don't want to use your own code in a custom module, you can get the classes via jQuery, find the one that matches `page-node-`, and then parse out the nid.

# Answer
> 1 votes
What has worked for me is adding the following line to my `page.tpl.php` template. This adds the node ID to `window.Drupal.settings.nid` which you can use at will in JavaScript.

```
drupal_add_js(array('nid' => $node->nid), 'setting');

```

---

As suggested in the comments, here's the code for adding the node ID from `template.php`:

```
function MYTHEME_preprocess_page(&$variables, $hook) {

  if ($node = menu_get_object()) {

    drupal_add_js(array('nid' => $node->nid),'setting');
  }
}

```

---
Tags: 7, nodes, javascript
---


# Question
Title: Webform Build Tab not displaying correctly
We just installed the Webform module, but as I'm going in to create and edit a new form, the "Build" tab is only allowing me to enter Elements with YAML code (pic one below). In the module description, it shows a preview of the Form Builder (pic two below), which doesn't look anything like what we have.

Is there an add-in that makes it looks like the module description...and therefore easier to use?

# Answer
> 0 votes
You need to enable the Webform UI module.

---
Tags: webforms
---


# Question
Title: How to pre-populate paragraphs when creating a page
I have tried for some time to find out a way to populate a new page with a few paragraphs to save time on most of the pages (but which might change position or even get dropped for some pages) but so far haven't found a way to do.

I think I have found out how to do the paragraph adding part, but what I am missing is how to fire the code when a new node of relevant content type is created.

I have tried hook THEME\_node\_create and THEME\_node\_insert, but they seem not to be fired when a new node is requested. I read that not all hooks are implemented for a theme but how then to achieve this functionality?

I probably (as most of the times) am missing something trivial, but please, help me find the light.

wbr

hank

# Answer
Actually I found a solution using a module. It was not the first time to find the solution after asking it here so it was not in vain - even if I found it myself...

To help possible otrhers, here is my solution from my module's .module file

```
function acme_pre_populate_node_create(\Drupal\node\NodeInterface $node) {
  $i=0;
  if ($node->getType() == 'acme_basic_page') {
    $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([
        'title' => 'Paragraph ' . $i,
        'type' => 'hero_image',
      ]);
      $node->field_paragraph_list[] = $paragraph;
      $i++;
      $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([
          'title' => 'Paragraph ' . $i,
          'type' => 'one_column_text',
          'field_one_column_text' => "<h1>Change title here</h1><p>And contents here</p>",
    ]);
        $node->field_paragraph_list[] = $paragraph;
       $i++;
  }
}

```
> 1 votes

---
Tags: theming, nodes, paragraphs
---


# Question
Title: Programatically insert field value of for a taxonomy term
I have a taxonomy vocabulary called, school and the machine name is field\_school\_name. The vocabulary has a field called school id (machine name:field\_school\_id). I am able to add a verb successfully using the following code. How do I add the field value programatically? I want to add '1234' as the school id associated with the verb 'ABCD' I created.

```
$new_term = \Drupal\taxonomy\Entity\Term::create([
    'vid' => 'field_school_name',
    'name' => 'ABCD',
]);

$new_term->enforceIsNew();
$new_term->save();

```

# Answer
> 0 votes
Should just need to do:

```
$new_term = \Drupal\taxonomy\Entity\Term::create([
 'vid' => 'field_school_name',
 'name' => 'ABCD',
 'field_school_id' => '1234'
]);

```

---
Tags: taxonomy-terms
---


# Question
Title: Creating nodes with cURL that have multiple tags and a content moderation transition
I've enabled the `rest restui serialization hal` and `basic_auth` modules and enabled and configured the Content resource like this:

I'm able to create nodes with:

```
X_CSRF_TOKEN=$(curl http://d8.local.org/session/token)
curl --include \
--request POST \
--user test:"test" \
--header 'Content-type: application/hal+json' \
--header "X-CSRF-Token: $X_CSRF_TOKEN" \
--insecure \
--data-binary '{"_links":{"type":
{"href":"http://d8.local.org/rest/type/node/article"}},
"title":[{"value":"Test"}],
"body":[{"value":"Body text."}],
"field_tags":[{"target_id":1}],
"type":[{"target_id":"article"}]}' \
http://d8.local.org/entity/node?_format=hal_json

```

How do I add multiple terms to field\_tags? Every combination I try, like

```
"field_tags":[{"target_id":1,2,3}],

```

returns a `400 Bad Request`

Also, how do I add a content moderation transition to the new node?

# Answer
> 1 votes
You need to map `target_id => [id]` as key/value pairs:

```
"field_tags":[{"target_id":"1"},{"target_id":"2"},{"target_id":"3"}]

```

---
Tags: 8
---


# Question
Title: Is there a way to tell if the current page is a node?
Without checking the URL I would like to know if the current page is a node page. We plan on using URL aliases so we would like to not rely on the '/node/\*' structure.

Is there some page variable or something that will indicate a node page?

# Answer
> 18 votes
```
\Drupal::request()->attributes->get('node');

```

Taken from here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3Arequest/8

Now the docs say to never use this function, but I have used this to determine what kind of page I am on.

There is another function, but I am not sure it applies in your case:

https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node\_is\_page/8

At the very least, if you do not have an entity, you could mimic that in your code:

```
  $route_match = \Drupal::routeMatch();

  if ($route_match->getRouteName() == 'entity.node.canonical') {
    return true;
  }

```

# Answer
> 13 votes
In your own module I think the recommended way is

```
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // It's a node!
}

```

# Answer
> 7 votes
In the page template a variable for the node is already available, which you can use in twig.

To tell, if the current page is a node, you can check, if `node` exists:

**page.html.twig**

```
{% if node %}
  <h1>This is a node</h1>
{% endif %}

```

This is possible, because this code is in core:

```
core/includes/theme.inc:
function template_preprocess_page(&$variables) {
  ...
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }
}

```

This will work on /node/\[id\] and url aliases.

# Answer
> 1 votes
The current answers don't work for previews or revisions. But normally you'd like that piece of logic to be fired on previews or revisions as well. Especially on the theming level where you at best should see how the node will look like after it got saved and/or published.

So here's is a snippet that gets the current node no matter if you view the full node or its preview or its revision. This may be placed inside a helper function under `MYMODULE/src/Utils` to be accessed as is or to make it a service.

```
$node = FALSE;
$route_match = \Drupal::routeMatch();

if ($route_match->getRouteName() == 'entity.node.canonical') {
  $node = $route_match->getParameter('node');
}
elseif ($route_match->getRouteName() == 'entity.node.revision') {
  $revision_id = $route_match->getParameter('node_revision');
  $node = node_revision_load($revision_id);
}
elseif ($route_match->getRouteName() == 'entity.node.preview') {
  $node = $route_match->getParameter('node_preview');
}

return $node;

```

---

BTW the same applies for the `node_is_page()` function that currently doesn't work on revisions or previews. I already opened an issue and provided a patch on https://www.drupal.org/project/drupal/issues/3005029.

---
Tags: 8, nodes
---


title: How do I get emails about core update?

text:
# Question
Title: How do I get emails about core update?
I'm not talking about updates within your site, I'm talking about waking up in the morning, checking your email and seeing an email sent to you from Drupal.org that new core version is out.

7.58 critical update just came out and I found out about it from a buddy.

I clicked follow at https://www.drupal.org/project/drupal but I get no email notification about any core versions coming out. I get only notifications for module issues that I'm subscribed to, I expected the same when clicking Follow in the modules page.

# Answer
1. Log in on your drupal.org account (or create one)
2. Go to My Account \> Edit \> My Newsletters (https://www.drupal.org/user/\[uid\]/edit/newsletter where \[uid\] is your user ID)
3. Check "Security announcements" and click "Save"
> 5 votes

# Answer
I cannot comment due to reputation, but i would like to precise the marcvanged choosen answer.

I know it's old, but it's important to understand that his answer regards security updates only, if the drupal core update is not a security update you do not receive any email notification.
> 1 votes

---
Tags: community-official-site
---


title: Site is slow when visiting admin pages

text:
# Question
Title: Site is slow when visiting admin pages
I turned on Devel query log and at the bottom of my pages it shows the log with the number of executed queries and ms. When i visit any admin page for example /admin/appearance i have following entries in my query log:

```
 _update_cache_clear 73ms DELETE FROM cache_update WHERE (cid = :db_condition_placeholder_0)

DrupalDatabaseCache::clear 81.9ms DELETE FROM cache_bootstrap WHERE (cid = :db_condition_placeholder_0)

```

As i know, it shouldn't be more than a 5ms. I am using Xcache on my server with 16gb RAM. What's the culprit?

PS when i am visiting non-admin pages they all are loading very fast.

# Answer
> 0 votes
by default drupal cache pages for anonymous user, and it is usual that visiting page bye anonymous user be faster than login users,also in admin page we have more load that front-end page The is a property of durpal. admin pages have more forms and more proccess.

# Answer
> 0 votes
Some times when admin pages do not render correctly or slow it helps to increased the memory\_limit in php.ini

---
Tags: 7, database
---


title: How to execute ajax into block view

text:
# Question
Title: How to execute ajax into block view
I'm in Drupal 7. I would like to execute an ajax function in my front-page. I've defined the block view in my ".module" file. When I change the selected option, the log gets two errors:

1.

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'test\_services\_search\_form' not found or invalid function name in drupal\_retrieve\_form() (line 842 of /var/www/html/test/html/includes/form.inc).

2.

> Notice: Undefined index: test\_services\_search\_form in drupal\_retrieve\_form() (line 807 of /var/www/html/test/html/includes/form.inc).

### `test.module`

```
function test_services_block_info() {
  $blocks['test_services_search_form'] = [
    'info' => t('Plan your trip'),
  ];
  return $blocks;
}

function test_services_block_view($delta = '') {
  $block = [];
  switch ($delta) {
    case 'test_services_search_form':
      module_load_include('inc', 'test_services', 'includes/test');
      $form             = drupal_get_form('test_services_search_form');
      $block['content'] = render($form);
      break;
  }
  return $block;
}

```

### `test.inc`

```
<?php

/**
 * @file
 * TEST - File search inc.
 */

/**
 * Implements hook_form().
 */
function test_services_search_form($form, &$form_state) {
  $form['search'] = [
    '#type' => 'container',
  ];

  // Transfer.
  $form['search']['transfer'] = [
    '#ajax'       => [
      'callback' => 'test_services_search_transfer_callback',
    ],
    '#attributes' => [
      'class'    => ['js-select2', 'cancel'],
      'required' => TRUE,
    ],
    '#title'      => t('Transfer'),
    '#options'    => [
      0 => t('Direct trip'),
      1 => t('Stopover trip'),
    ],
    '#type'       => 'select',
  ];

  return $form;
}

/**
 * Callback handler for the direct/transfer trip select.
 */
function test_services_search_transfer_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

/**
 * Callback function.
 */
function test_services_search_form_callback($form, &$form_state) {
  return $form;
}

```

The point is disable three fields if option two is selected, It's possible execute AJAX into a block view, and if so, what is going on? Why Drupal is not going into the function of the AJAX callback?

# Answer
> I've defined the block view. When I change the selected option, the log gets two errors.

It seems the error happens after you submitting the block. So the file loads fine on view, but not when the form is processed which should have information where to look for it.

So you should define your form using `hook_forms`.

> By default, when `drupal_get_form()` is called, the system will look for a function with the same name as the form ID, and use that function to build the form. If no such function is found, Drupal calls this hook.

Also, when you working with the forms, instead of `drupal_get_form($form_id)`, you can consider using `form_load_include()` to make sure the include file is loaded whenever the form is processed.

> Use this function instead of `module_load_include()` from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using `module_load_include()` directly, `form_load_include()` makes sure the include file is correctly loaded also if the form is cached.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: How can I allow HTML links in translated strings?
I created a custom D8 module with all text strings declared in English, either via this-\>t(), t() or in various configuration (YML) files.

I am now in the process of translating those strings in French so that I can then extract them and package them with the module.

My issue: some strings for the interface contain HTML links (mostly refering to other Drupal admin pages); they display and work fine in English, but when I try to translate those strings via the Drupal UI, I get an error saying *"The submitted string contains disallowed HTML"*. If I remove the `<a>` then the error disappears.

Here's an example of a string containing several links:

```
$this->t('<p>Some explanations here. You can find a more information
  <a href=@hhelp>on the help page</a>.<br>Note: after changing this value,
  you may have to <a href=@hperformance>clear the cache</a> for this setting
  to take effect.</p>', array(
  '@hhelp' => '../../help/mymodule',
  '@hperformance' => '../development/performance',
)),

```

Is it possible to translate those strings while keeping the links in the translation? How should I proceed?

# Answer
> 2 votes
the problem is the absence of the quotes. I try to insert this traslation on a drupal site and it work!

```
<p>Some explanations here. You can find a more information
 <a href='@hhelp'>on the help page</a>.<br>Note: after changing this
  value,you may have to <a href='@hperformance'>clear the cache</a>
  for this setting to take effect.</p>

```

It also work with `"`

# Answer
> 0 votes
Have you tried split the string as below

```
$text = t('Some explanations here. You can find a more information
<a href="@hhelp">on the help page</a>.', array('@hhelp' =>'../../help/mymodule',));

$text.= t('<br>Note: after changing this value, you may have to <a href="@hperformance">
clear the cache</a> for this setting
to take effect.', array('@hperformance' => '../development/performance',));

```

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


title: Content type disappears in content list

text:
# Question
Title: Content type disappears in content list
I created a taxonomy with the same name as a content type. Now the list shows with no content type on the nodes with that type. I have since renamed the taxonomy, but there is still an issue.

When trying to edit the node from the admin menu I get the following error:

> Notice: Undefined index: case\_studies\_node\_form in drupal\_retrieve\_form() (line 750 of C:\wamp\www\ppi\includes\form.inc).
>
> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'case\_studies\_node\_form' not found or invalid function name in drupal\_retrieve\_form() (line 785 of C:\wamp\www\ppi\includes\form.inc).

I checked the database and the nodes have the correct type in the content table, and the content types table still has the "Case Studies" type.

# Answer
Suggestions:

1. Make sure the module handling custom node type exists and is enabled.

Based on `case_studies_node_form` callback, it's most likely `case_studies` module.

If you don't know type of the node, you can load it using `drush`, e.g.

```
drush ev "var_dump(node_load(123));"

```
2. Make sure the module which handles custom node type defines `hook_node_info()` in its `.module` file.
3. Clear caches (`drush cc all`, restart Memcached/Redis if present).
> 0 votes

---
Tags: nodes
---


# Question
Title: Custom template for each profile2 profile type edit form
I am working on a Drupal 7 site and for a few days now, I've been struggling with this problem: I am trying to create a custom template for the edit profile form, but there are more profile types. I managed to create the template but it does not work properly. I am able to save all the fields except the image field. When I hit remove button, the filed disappears completely, then I have to hit save two times for the image to be actually removed. Also, if I add an image, then press upload, I get a warning:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'profile2\_form' not found or invalid function name in drupal\_retrieve\_form() (line 841 of /var/www/html/hxl\_drupal/includes/form.inc).)

If I hit save twice, the image gets saved.

I tried a lot of websites, including these:

I should also mention that the form is submitted through AJAX and that I use ctools module to open it in modal.

Below you can see the code.

### `template.php`

```
/*
* Implements hook_form_alter()
*/

function customtheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    if ($form['#user_category'] === 'partner_user') {
      $form['#theme'] = 'profile2_partner_user_edit_form';
    } else if ($form['#user_category'] === 'advisor_user') {
      $form['#theme'] = 'profile2_advisor_user_edit_form';
    }
  }
}

/*
*implements hook_theme()
*/

function customtheme_theme() {
  return array(
    'profile2_partner_user_edit_form' => array(
      'arguments' => array(
        'form' => NULL,
      ),
      'template' => 'templates/profile2--partner-user-edit',
      'render element' => 'form',
    ),
    'profile2_advisor_user_edit_form' => array(
      'arguments' => array(
        'form' => NULL,
      ),
      'template' => 'templates/profile2--advisor-user-edit',
      'render element' => 'form'
    ),
  );
}

```

### `custom_module.module`

```
/**
* hook_menu
*/
function custom_module_menu() {
$items['profile/user-advisor_user_edit/%user/%ctools_js'] = array(
  'page callback' => 'profile_advisor_user_edit',
  'page arguments' => array(2,3),
  'type' => MENU_CALLBACK,
  'access callback' => TRUE,
  'file path' => drupal_get_path('module', 'user'),
  'file' => 'user.pages.inc',
);

$items['profile/user-partner_user_edit/%user/%ctools_js'] = array(
    'page callback' => 'profile_partner_user_edit',
    'page arguments' => array(2,3),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'file path' => drupal_get_path('module', 'user'),
    'file' => 'user.pages.inc',
  );

    return $items;
}

```

I will post only the code for this profile type, because except the key word advisor\_user.

```
function profile_advisor_user_edit($user, $js = FALSE ){
  if ($js){

   ctools_include('user.pages', 'user', '');
   ctools_include('modal');
   ctools_include('ajax');

   $form_state = array(
   'ajax' => TRUE,
   'title' => t('Edit Profile'),
   'user_id' => $user,
    );

   $form_state['build_info'] = array(
   'args' => array($user),
   );

   $output = ctools_modal_form_wrapper('profile2_advisor_user_edit_form', $form_state);

    if (!empty($form_state['executed'])) {
      $output = array();
      $output[] = ctools_modal_command_dismiss();
    }

  print ajax_render($output);
  exit;
}else{
  module_load_include('inc', 'user', 'user.pages');
  $user_edit_form =     drupal_get_form('profile2_advisor_user_edit_form',$user);
  return drupal_render($user_edit_form);
}

```

}

The `profile2--advisor-user-edit.tpl.php` file I will post the code only for this profile type because they are pretty much the same.

```
 module_load_include('inc', 'profile2_page', 'profile2_page'); // Include profile2_page module

$profile2 = profile2_by_uid_load($user->uid, 'advisor_user');
$entity_form = entity_ui_get_form('profile2', $profile2, 'edit'); // Or 'add'
print render($entity_form['profile_advisor_user']['field_picture']);
print render($entity_form['profile_advisor_user']['field_first_name']);
print render($entity_form['profile_advisor_user']['field_last_name']);
print render($entity_form['profile_advisor_user']['field_role']);
print render($entity_form['profile_advisor_user']['field_bio']);
print render($entity_form['profile_advisor_user']  ['field_interest_topics']);
print render($entity_form['profile_advisor_user']['field_interest_areas']);
unset($entity_form['extra_fields']) //here I unset the fields that I don't want to appear in the form
print render($entity_form);

```

# Answer
Loading form using `module_load_include()` isn't advised, you should use `form_load_include()` instead, so the include file is loaded whenever the form is processed. That's why you've issues on form submit.

> Use this function instead of `module_load_include()` from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using `module_load_include()` directly, `form_load_include()` makes sure the include file is correctly loaded also if the form is cached.

Otherwise define your form using `hook_forms`, so Drupal knows where to find it (in which file).

> By default, when `drupal_get_form()` is called, the system will look for a function with the same name as the form ID, and use that function to build the form. If no such function is found, Drupal calls this hook.
> 0 votes

---
Tags: 7, theming, forms, ajax
---


# Question
Title: FACETS : Add "Apply" button that will apply all filters in one query
Is it possible in D8 to add an "Apply" button that will apply all facet filters in one query and not having an ajax reload on each option changed ?

i find this for D7 :

https://www.drupal.org/project/ajax\_facets/issues/2700063

i am not quite sure what's been the issue of that issue.

# Answer
> 1 votes
i have created an issue on the facet module and the situation is :

Not soon in the drupal 8 version. This would be a big refactor of the way queries are built right now.

https://www.drupal.org/project/facets/issues/3013702

---
Tags: 8, search
---


title: How to add Chosen JS library to theme?

text:
# Question
Title: How to add Chosen JS library to theme?
We are attempting to figure out how to properly add Chosen library to our custom theme. The main reason for doing this is to be able to add the Chosen JS files, but use a custom css file where we can control the output.

After reviewing Chosen Module we found that it adds a lot of bloat that we don't necessarily need and have found it difficult to override the css that is used.

Here is what we tried, but cannot get it to use the chosen.min.css and need help to see how it can be done.

mytheme.libraries.yml file

```
chosenjs:
    version: 1.x
    css:
       theme:
          css/chosen.min.css: { minified:true }
    js:
      js/chosen.min.js: { minified:true }

```

The chosen.min.js has the necessary settings to get the functionality we needed.

# Answer
If the code posted above is correct, the indentation is off. It should look something like this:

```
search:
  version: VERSION
  js:
    extras/js/drupal/search/sort.js: {}
    extras/js/drupal/search/filter.js: {}

```

See how `js` is not indented under `version`?

The second part of it is you have to tell Drupal to load it either sitewide, or on demand:

Sitewide, you need to declare this in your theme info yaml:

```
libraries:
  - mytheme/search

```

If you want to do it on demand, something like:

```
/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  $current_path = \Drupal::service('path.current')->getPath();

  // We really want to minimize the loading of these two libraries
  // for anonymous users. so far, we only need it on any /search* path.
  if (preg_match('/\/search+/', $current_path)) {
    $attachments['#attached']['library'][] = 'core/drupal';
    $attachments['#attached']['library'][] = 'core/jquery';
    $attachments['#attached']['library'][] = 'mytheme/search';
  }
}

```

Or you can put it in a specific twig template i.e. `node.html.twig` like this

```
{{ attach_library('mytheme/search') }}

```
> 2 votes

# Answer
Do you want to use the un-compressed versions? Because after enabling Drupal aggregation for JavaScript, this will then compress and minify everything. In your example, you are using the minified versions. I also need to add Chosen and Select2. Chosen 1.8.7 is located on https://github.com/harvesthq/chosen/releases/tag/v1.8.7.

I need the 5 files listed below.

```
chosen.jquery.js
chosen.proto.js
chosen.css
chosen-sprite.png
chosen-sprite@2x.png

```

My libraries file is the following.

```
global-styling:
  css:
    theme:
      css/style.css: {}

  js:
    js/chosen.jquery.js: {}
    js/chosen.proto.js: {}
    js/datatables-init.js: {}
    js/datatables.js: {}

```

Then inside the sass directory, I place chosen.css and use import so it gets compiled into the main CSS file. We already did this with the datatables, but it came with SCSS instead of CSS.

Where do the 2 images go? I place the 2 png image files inside /assets/images/. This is where all of the theme images go. chosen-sprite.png will not work in this folder because chosen.css is pointing to this image in the root directory the way it comes in the original library.

Also, it will be difficult to upgrade this library because the files are in 3 different places.
> 0 votes

---
Tags: 8, theming, javascript
---


# Question
Title: Deleted the Content Type now cannot delete or edit node of that type, but it is visible on site
I have a node that I can see on my site, but when I try to edit it I get the error:

```
Notice: Undefined index: my_node_name_node_form in drupal_retrieve_form() (line 763 of /home/sites/my-site-url/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'my_node_name_node_form' not found or invalid function name in drupal_retrieve_form() (line 798 of /home/sites/my-site-url/includes/form.inc).

```

I cannot see the node by going to 'content'.

I believe that what has happened is: I deleted a Content Type that was redundant on my site without realizing that there was a node of that type on the site. I guess that now the node doesn't its content type this is stopping it from being deleted.

I would like to know how to delete this node, or failing that unpublish it.

I know the NID of the node to be deleted.

I guess that one way of doing this would be manually using phpmyadmin. For this approach I would need some guidance on how to go about this as I am not very familiar with either how nodes are spread across the tables in the database or working in phpmyadmin.

# Answer
Ideally you should re-enable module which supports that custom node type, so the node can be properly removed.

Otherwise, you can load, edit or delete the node programmatically.

For example, to load the node using Drush, you can run:

```
drush ev "var_dump(node_load(1234));"

```

To delete it, try:

```
drush ev "node_delete(1234);"

```

Alternatively, you can delete these nodes from the *node* table.

To find all other references, check your database, for example with `drush sql-dump --ordered-dump | grep my_node_name`.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Why block with add node form returnes errors?
To show add node form in particular place I created a new block on the Block page with content:

```
<?php
global $user;
module_load_include('inc', 'node', 'node.pages');
$node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'foto', 'language' => LANGUAGE_NONE);
$form = drupal_get_form('foto_node_form',$node);
print drupal_render($form);
?>

```

Then I go to my page with this block and try to add content within this block. When I fill only text fields or checkboxes everything is OK. But I receive a lot of errors when try to upload an image to image field.

```
•Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'node_form' was given in function drupal_retrieve_form() (line 800 in file D:\sites\mytheme\www\includes\form.inc).
•Notice: Undefined index: #node in function comment_form_node_form_alter() (line 1194 in fileD:\sites\mytheme\www\modules\comment\comment.module).
•Notice: Trying to get property of non-object in function comment_form_node_form_alter() (line 1211 in fileD:\sites\mytheme\www\modules\comment\comment.module).
•Notice: Undefined index: #node in function menu_form_node_form_alter() (line 629 in file D:\sites\mytheme\www\modules\menu\menu.module).
•Notice: Trying to get property of non-object in function menu_form_node_form_alter() (line 629 in fileD:\sites\mytheme\www\modules\menu\menu.module).
•Notice: Undefined index: #node in function menu_form_node_form_alter() (line 630 in file D:\sites\mytheme\www\modules\menu\menu.module).
•Notice: Trying to get property of non-object in function menu_form_node_form_alter() (line 630 in fileD:\sites\mytheme\www\modules\menu\menu.module).
•Notice: Undefined index: field_image in function file_ajax_upload() (line 271 in file D:\sites\mytheme\www\modules\file\file.module).
•Notice: Undefined index: #suffix in function file_ajax_upload() (line 280 in file D:\sites\mytheme\www\modules\file\file.module).

```

What I'm doing wrong? Thanks in advance

# Answer
Instead of custom code, you can use Form Block module for that. It provides node creation forms in blocks.
> 0 votes

# Answer
Try the following code:

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('foto');
$output = drupal_render($form);

```

Source: How to display node/add/sometype form on another page?
> 0 votes

---
Tags: 7, nodes, forms, blocks
---


title: Programmatically a create content form

text:
# Question
Title: Programmatically a create content form
I want to implement the create content form programmatically. In `hook_menu()` I have the following code.

```
$items['create/content/video'] = array(
  'title' => 'Create Video',
  'page callback' => 'create_content_video',
  'access arguments' => array('create video'),
  'type' => MENU_LOCAL_TASK,
  'weight' => 1
);

```

In `hook_init()`, I have the following code.

```
if (arg(0)=='node' && arg(1)=='add') {
  drupal_goto('create/content/'.arg(2));
}

```

In `hook_theme()`, I have the following code.

```
'video_node_form' => array(
  'arguments' => array(
    'form' => NULL,
  ),
  'template' => 'my_theme_video_form',
  'render element' => 'form',
),

```

In the page callback, I have the following code.

```
function create_content_video() {
  module_load_include('inc', 'node', 'node.pages');
  return node_add('video');
}

```

In the template file, I render form element correctly. My problem is with the the AJAX uploader in the form. Without, I use the upload button to upload the file, and the node is correctly saved; when I use the AJAX uploader, it returns an error.

> **Warning**: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'node\_form' not found or invalid function name in drupal\_retrieve\_form() (line 795 of /var/www/mysite/includes/form.inc).
> **Notice**: Undefined index: #node in comment\_form\_node\_form\_alter() (line 1193 of /var/www/mysite/modules/comment/comment.module).
> **Notice**: Trying to get property of non-object in comment\_form\_node\_form\_alter() (line 1210 of /var/www/mysite/modules/comment/comment.module).
> **Notice**: Undefined index: #node in menu\_form\_node\_form\_alter() (line 629 of /var/www/mysite/modules/menu/menu.module).
> **Notice**: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 629 of /var/www/mysite/modules/menu/menu.module).
> **Notice**: Undefined index: #node in menu\_form\_node\_form\_alter() (line 630 of /var/www/mysite/modules/menu/menu.module).
> **Notice**: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 630 of /var/www/mysite/modules/menu/menu.module).
> **Notice**: Undefined index: #node in translation\_form\_node\_form\_alter() (line 135 of /var/www/mysite/modules/translation/translation.module).
> **Notice**: Trying to get property of non-object in translation\_form\_node\_form\_alter() (line 135 of /var/www/mysite/modules/translation/translation.module).
> **Notice**: Undefined index: type in xmlsitemap\_node\_form\_node\_form\_alter() (line 136 of /var/www/mysite/sites/all/modules/xmlsitemap/xmlsitemap\_node/xmlsitemap\_node.module).
> **Notice**: Undefined index: nid in xmlsitemap\_node\_form\_node\_form\_alter() (line 136 of /var/www/mysite/sites/all/modules/xmlsitemap/xmlsitemap\_node/xmlsitemap\_node.module).
> **Notice**: Undefined index: field\_news\_attachment in file\_ajax\_upload() (line 276 of /var/www/mysite/modules/file/file.module).
> **Notice**: Undefined index: #suffix in file\_ajax\_upload() (line 285 of /var/www/mysite/modules/file/file.module).

When I create content without this method, it works fine.
I am using Drupal 7.14.

# Answer
I agree with Clive, that this seems like a great deal of trouble, but what you should be doing generally, is calling field\_attach\_form(), and more specifically for nodes, node\_form(), which calls the former. The arguments it expects are

You can see an example on the first here: Is displaying a working Field Widget Form on its own possible?
> 1 votes

# Answer
If you are just trying to theme the edit form for the "video" content type, then you can simply use the following code.

```
function mymodule_form_video_node_form_alter(&$form, &$form_state) {
  $form['#theme'] = 'mymodule_video_form';
}

```

Your hook\_theme() implementation needs to be changed, as:

* *arguments* is a property that is not used in Drupal 7; you should use *variables*.
* As reported in the documentation, "each information array must contain either a 'variables' element or a 'render element' element, but not both."

If you are implementing that code just to be able to use create/content/video, instead of node/add/video, then I would suggest not to implement such code.
From the code you are showing, I see there is something wrong: You define a callback for create/content/video, but your `hook_init()` implementation is redirecting the users also for other content types, as it is not checking the value of `arg(2)`.
> 1 votes

# Answer
As per this post, if you've a file upload widget, you should add the following lines th the menu array (`$items`):

```
'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

```
> 0 votes

---
Tags: forms, nodes
---


# Question
Title: Adding node into search api solr programatically
We are importing large number of data into our drupal website with custom script and we are using Search api and Search api solr module into our website to index and search large number of data.

When we import data using custom script, Search api solr is not fetching this data and new nodes are not indexing into Solr,

If we update the node, its indexing successfully into solr.

I am trying to adding node programatically into solr but its did not work for us.

```
search_api_track_item_change($type, array($id));

```

Can anyone suggest me?

# Answer
> 3 votes
Two things first. These two items are purely a suggestion and have no impact on the code samples bellow:

* You should post the code that saves your nodes. The Solr API module should automatically pick up nodes when you save and update them (the search\_api module code runs when you call "node\_save"). It is odd that it doesn't for you.
* You should think about running your solr re-indexing operation **after** you import all of your data. This will speed up your bulk imports and you can schedule the solr re-index via cron or run it via drush.

The following information comes straight from the search\_api module.

These are the pre-conditions for the code examples bellow:

* You need to run these after you call the *node\_save* function.
* The *$type* variable refers to the entity type (node, user, term, etc..). In your case it sounds like *$type='node'*
* the *$entity* variable refers to the node object you're saving. You would pass this object to the *node\_save($entity)* function during the bulk import operation.

If you're **inserting** nodes:

```
  $type='node';
  list($id) = entity_extract_ids($type, $entity);
  if (isset($id)) {
    search_api_track_item_insert($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_insert('multiple', array($combined_id));
  }

```

If you're **updating** nodes:

```
$type='node';
list($id) = entity_extract_ids($type, $entity);
if (isset($id)) {
    search_api_track_item_change($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_change('multiple', array($combined_id));
}

```

# Answer
> 1 votes
To simply index a single node, you can:

```
$index = search_api_index_load('default_node_index');
search_api_index_specific_items($index, [$node_nid]);

```

Find the name of your index by opening Search API index in admin. In my example : /admin/config/search/search\_api/index/default\_node\_index

Keep in mind there's still probably a delay while Solr processes the submission. Then, depending on what you're doing within Drupal, there may be cache flushes required on the Drupal side in order for you to see the results there.

As mentioned in other answers, this could be a pretty intensive operation (after all that's why it's normally done via cron), so use sparingly, possibly in a PHP shutdown function.

# Answer
> 0 votes
I had a similar symptom, even on node update events and solved it by adding this code after your track item change request to Search API

```
search_api_track_item_change('node', array($node->nid));
$index = search_api_index_load('product');
search_api_index_items($index);

```

The ID you have to give as an argument to search\_api\_index\_load can be found by opening your Search API index in admin. In my example : admin/config/search/search\_api/index/product

To index new nodes, you might need to add this line in between :

```
$index->reindex()

```

This will pickup all items to reindex, so keep in mind that the reindexing will take more time to complete, and preferably done in batch.

---
Tags: 7, search
---


title: Render form node add in page

text:
# Question
Title: Render form node add in page
I have these code that render form right:

```
<?php
// we have to access the content of the global-scope variable $user
global $user;
//Checking if the user is registered
if(($user->uid == 0) && (arg(0) != 'user')){
drupal_goto('user/register');
}else{
module_load_include('inc', 'node', 'node.pages');
$form = node_add('MY_CONTENT'); return drupal_render($form);}
?>

```

but when upload some images in form widget return some errors:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 806 of /Users/umbilu/Sites/bedmyboat/includes/form.inc).
Notice: Undefined index: #node in comment_form_node_form_alter() (line 1206 of /Users/umbilu/Sites/bedmyboat/modules/comment/comment.module).
Notice: Trying to get property of non-object in comment_form_node_form_alter() (line 1223 of /Users/umbilu/Sites/bedmyboat/modules/comment/comment.module).
Notice: Undefined index: #node in i18n_node_form_node_form_alter() (line 434 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_node/i18n_node.module).
Notice: Undefined index: actions in i18n_node_form_node_form_alter() (line 448 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_node/i18n_node.module).
Warning: array_search() expects parameter 2 to be array, null given in i18n_node_form_node_form_alter() (line 448 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_node/i18n_node.module).
Notice: Undefined index: #node in maxlength_form_alter() (line 188 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/maxlength/maxlength.module).
Notice: Trying to get property of non-object in maxlength_form_alter() (line 188 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/maxlength/maxlength.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /Users/umbilu/Sites/bedmyboat/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /Users/umbilu/Sites/bedmyboat/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /Users/umbilu/Sites/bedmyboat/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /Users/umbilu/Sites/bedmyboat/modules/menu/menu.module).
Notice: Undefined index: #node in translation_form_node_form_alter() (line 135 of /Users/umbilu/Sites/bedmyboat/modules/translation/translation.module).
Notice: Trying to get property of non-object in translation_form_node_form_alter() (line 135 of /Users/umbilu/Sites/bedmyboat/modules/translation/translation.module).
Notice: Undefined index: #node in i18n_menu_form_node_form_alter() (line 786 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_menu/i18n_menu.module).
Notice: Trying to get property of non-object in i18n_menu_form_node_form_alter() (line 787 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_menu/i18n_menu.module).
Notice: Trying to get property of non-object in i18n_menu_form_node_form_alter() (line 792 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_menu/i18n_menu.module).
Notice: Undefined index: #node in _i18n_node_form_node_form_alter() (line 501 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_node/i18n_node.module).
Notice: Trying to get property of non-object in _i18n_node_form_node_form_alter() (line 520 of /Users/umbilu/Sites/bedmyboat/sites/all/modules/i18n/i18n_node/i18n_node.module).
Notice: Undefined index: field_boat_images in file_ajax_upload() (line 271 of /Users/umbilu/Sites/bedmyboat/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Users/umbilu/Sites/bedmyboat/modules/file/file.module).

```

I have tried with these:

```
<?php
if (!function_exists('node_add')) {
module_load_include('inc', 'node', 'node.pages');
}
print drupal_render(node_add('on_board'));
?>

```

return these error:

> Strict warning: Only variables should be passed by reference in eval() (line 5 of /Users/umbilu/Sites/bedmyboat/modules/php/php.module(80) : eval()'d code).

# Answer
> 1 votes
This problem is probably due to the fact, that `node_add` is registered as a menu callback in the node module, and in this menu item definition the include `node.pages.inc` is defined. When you use your own code (like you do) then this automatic inclusion of `node.pages.inc` is not done, so that the necessary API functions are missing, resulting in the error messages that you see.

Therefor, as a general remark, it is usually advisable to create custom modules (or adding functions to template.php, though no buisness logic should be processed there) and implement hooks like `hook_preprocess_page` or even define custom blocks in order to place functional elements in a page.

Anyway, for a solution to your problem, have a look at this question: Embed a "node add" form in a page

# Answer
> 0 votes
Try using Form Block module which provides user registration and node creation forms in blocks.

---
Tags: nodes, forms
---


# Question
Title: How do I place the registration form in the front page?
I am using Drupal 7.

I clicked on Structure \> Block \> Add Block; I filled in the block title and block description. In the block body, I put in this code.

```
<?php
  $_GET['q'] = 'user/register';
  print drupal_get_form('user_register');
?>

```

I set the text format to PHP (PHP wasn't in the drop down options of text formatting so I added PHP to it), and I clicked on save block.

The block is now created but it's just empty. I can't see any sign up form.

Can someone please put me through? I'm new to Drupal.

I just discovered that I had to activate PHP Filter in core modules (administration \> modules). So when I activated PHP Filter module, the registration block I created now shows the word "Array", and also some error in the log.

> Notice: Undefined index: user\_register in drupal\_retrieve\_form() (line 764 of C:\xampp\apps\drupal\htdocs\includes\form.inc).
> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'user\_register' not found or invalid function name in drupal\_retrieve\_form() (line 799 of C:\xampp\apps\drupal\htdocs\includes\form.inc).
>
> Notice: Array to string conversion in eval() (line 3 of C:\xampp\apps\drupal\htdocs\modules\php\php.module(80) : eval()'d code).

However, the "create new account and login" menu is now showing; it is only not showing in the block I created for it. What is showing in the block is "Array"; when I click on either "register" or "log in," it takes me away from the front page (to the register page).

# Answer
The user register form id is `user_register_form`. Please try it like:

```
$form = drupal_get_form('user_register_form');
print render($form);

```
> 2 votes

# Answer
You should use Form Block module which provides user registration and node creation forms in blocks.
> 0 votes

# Answer
Use the following code.

```
print(drupal_render(drupal_get_form('user_register_form')));

```
> -1 votes

---
Tags: blocks
---


# Question
Title: Author image not rendering in node twig file
I have created node for a Article content type. And I am trying to extract out author information in `node--article.html.twig` file.

I am sucessfully able to fetch out Author name `{{ author_name }}`, author bio `{{ node.Owner.field_bio.value}}`.

But I am facing issue to find out author image. When I tried to print `{{ kint(author_picture) }}` it returned me null. But when I vistited link: http://drupal-site.com/user/2, I can see author image there. I am bit consfused on need help on showing author image in node.

Any help is appriciated.

# Answer
> 0 votes
To get the image `uri` value, try the following:

```
{{ node.Owner.user_picture.0.entity.uri.value }}

```

---
Tags: theming
---


# Question
Title: How to filter by language in default search
On a D7 (7.60) site, we're currently using the default search tool for a little search form block on the page. Our site has multiple language versions, dependent on url.

Right now, content in 4 languages is giving 4 search results. I want to filter this to just current user's language. But when I go into the view (admin/structure/views/view/search/edit), I'm not seeing "current user's language" as a filter.

# Answer
Ah heck.. nevermind. I wasn't understanding how to get that setting. All good now. Filter by content language, and 'current user's language' is one of the checkbox options within it.
> 2 votes

---
Tags: 7, search
---


title: How to do a redirect in node.html.twig?

text:
# Question
Title: How to do a redirect in node.html.twig?
I'm trying to do a redirect on my `node.html.twig` template based on the content type because I'm using views for my content.

I tried this:

```
{% do redirect('/example') %}

```

or this:

```
{% redirect '/example' %}

```

but nothing works. Any idea?

# Answer
Don't do it in the Twig file. This is not where that logic belongs. It should be in an Event.

See this similar question: EventSubscriber called on specific node type or path

All that is left is checking the node type and sending a `RedirectResponse`.

Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

So your code would fill in something like:

```
  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
  protected function redirectApplies(NodeInterface $node) : bool {
    $redirect_types = ['type_1', 'type_2', 'type_3'];
    return in_array($node->getType(), $redirect_types);
  }

```

But if you go to different urls for different types, you will need to adjust it a little more.
> 4 votes

# Answer
Where did you see the redirect functionality? I dont think it's part of standard twig or anything drupal provides: https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

You'd be better of doing the redirect in a proprocess function maybe. This might help Redirect basic page to external url when visiting page
> 0 votes

# Answer
As @Kevin suggested i created a custom module based on Gabe Sullice code: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

My final code redirect to custom url by content type:

```
    namespace Drupal\redirect_node_module\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\node\NodeInterface;
use Drupal\Core\Cache\CacheableRedirectResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
 * Class ResponseSubscriber.
 *
 * @package Drupal\redirect_node_module
 */
class ResponseSubscriber implements EventSubscriberInterface {
  /**
   * Drupal\Core\Routing\CurrentRouteMatch definition.
   *
   * @var Drupal\Core\Routing\CurrentRouteMatch
   */
  protected $routeMatch;
  /**
   * Constructor.
   */
  public function __construct(CurrentRouteMatch $current_route_match) {
    $this->routeMatch = $current_route_match;
  }
  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events['kernel.response'] = ['handle'];
    return $events;
  }
  /**
   * This method is called whenever the kernel.response event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function handle(Event $event) {
    $route_name = $this->routeMatch->getRouteName();
    switch ($route_name) {
      case 'entity.node.canonical':
        $node = $this->routeMatch->getParameter('node');
        if ($this->redirectApplies($node)) {
          $event->setResponse(new RedirectResponse($this->getRedirect($node)));
        }
    }
  }
  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
   protected function redirectApplies(NodeInterface $node) {
    // One should have logic here returning TRUE or FALSE for whether we should redirect this response.
    $redirect_on = ['programas', 'servicios', 'aliados', 'testimonios', 'nosotros', 'nuestro_equipo', 'datos_de_contacto', 'banner', 'seccion'];
    return (in_array($node->getType(), $redirect_on));

  }
  protected function getRedirect(NodeInterface $node) {
    // We can cache this response when this is fixed: https://www.drupal.org/node/2573807
    // $response = CacheableRedirectResponse::create($url);
    // $response->addCacheableDependency($node);
    // return $response;

    switch ($node->getType()) {
      case 'nuestro_equipo':
        $url = "/profesionales";
        break;

      case 'datos_de_contacto':
        $url = "/contacto";
        break;

      case 'nosotros':
        $url = "/nosotros";
        break;

      case 'banner':
        $url = "/";
        break;

      case 'testimonios':
        $url = "/testimonios";
        break;

      case 'aliados':
        $url = "/aliados";
        break;

      default:
        $search_chars = array('á','é','í','ó','ú','ñ','Á','É','Í','Ó','Ú','Ñ',' ');
        $replace_chars= array('a','e','i','o','u','n','a','e','i','o','u','n','-');
        $node_title = str_replace($search_chars, $replace_chars, strtolower( $node->getTitle() ));
        $url = "/".$node->getType()."/".$node_title;
        break;
    }
    return $url;
  }
}

```
> 0 votes

---
Tags: 8, redirection
---


# Question
Title: Custom blocks not rendering for anonymous users
I recently deployed an update to Drupal 8.6.3 from 8.6.2 on our Drupal-specific managed web host (Pantheon).

Unfortunately, I noticed after the update that our site's footer was missing, but only for anonymous users. This footer is made of custom blocks placed in a footer region.

The footer is only missing for anonymous users. When you are logged in, the footer blocks appear properly. I've tried clearing the cache, running cron, clearing the cache again, etc. There are no errors in the watchdog logs that look like they would relate to this problem.

I've tried several, escalating troubleshooting steps to fix the error. Here they are, in more or less the order that I tried them:

* I created new custom blocks (using the "basic block" type) in the footer region. For these new blocks, I left them to display the title. The content of the new custom blocks were not rendered for anonymous users, but the title of the block was rendered. To further test, I edited the existing custom blocks in the footer region to display the title. The title displayed, but not the content. This tells me that Drupal is aware of the custom blocks in the region, but not rendering their content for anonymous users.
* I then added the built-in login block into the footer. This rendered properly for the anonymous user. This tells me the problem is limited to custom blocks
* I then added new custom blocks, and existing custom blocks, with titles, to the content region. I wanted to disprove the idea that there was a problem with the footer region. Like earlier, content was rendered for logged in users, but not for anonymous users. This tells me that the problem is with the content of custom blocks for anonymous users, regardless of the region they're placed in.

At this point, I decided that the problem probably just wasn't my particular config, and I did some googling to see if others had encountered this issue.

I found a number of issues regarding updating from 8.3.x to 8.5.x, and certain update hooks not running. We had been a little behind on updates, and had updated from 8.5.6 to 8.6.2 about a month ago, and then to 8.6.3 last night. So I didn't think these would apply to my situation, but I looked at their fixes and tried them if I could, anyway.

When I looked at the databse, all of my block content and revision statuses already had the value `1`. For testing's sake, I did the update anyway. Still no blocks.

A commenter linked this from the first issue I looked at, so I checked it out. I didn't thing it applied, since we already had been running 8.5.6 for a while with no problem with our blocks. I didn't have these fields in my `block_content_revision` table, but when I added them, it didn't fix the problem.

This seem to relate to schema update hooks for block revisions not having been run. For troubleshooting's sake, I set my block\_content revision level to 0 to trigger a re-run of all the update hooks. This didn't resolve the issue.

In the issue queues that I looked at, there was also talk about the translation module. We don't have that enabled on our site.

So my site has a major issue, and it's kind of ruining my holiday. Any help would be appreciated!

**Edit** We rolled our site back to 8.6.2, restoring from a backup. custom blocks still not rendering. So, it seems that the core update was not causing the issue.

If anyone knows where to start adding debugging code into core to debug on local, please chime in.

**Edit 2** I've recreated the problem both on my home and work computers.

**Edit 3** As suggested in two separate comments, I've tried switching the theme to Bartik, and also disabling both the Page Cache modules (and clearing the cache afterwards). After creating and placing a brand new custom block (for a clean-ish test) with the title showing in two separate page sections, I still get the same behavior: for logged in users, I see the custom block title and content. But for the anonymous users, I see only the title of the block.

**Edit 5** At Kenorb's sugggestion, I looked to see if we were running any block permission modules. We are running `block_content_permission` and `block_region_permission` (however we are not running the `block_access` module). I looked into these, and they seem to only provide permissions for administration and editing of blocks. There was one permission that looked relevant-- `View restricted block content`. I enabled it for the anonymous user, but that didn't fix the problem. To test more robustly, I disabled both of those modules on my local, and again, no fix.

**Edit 6** regarding more suggestions: `updb` has been run. I tested this on a fresh local backport, `No database updates required.` Text filter format for blocks is `Full HTML`.

**Edit 7** re: Block visibility: there doesn't appear to be any restrictions on the problematic blocks. (Also, when I test by adding new custom blocks, I'm not adding any restrictions to them, and their title is displaying anyway). This is a screenshot:

**Edit 8** I also tried the patch, again on a new fresh backport, that kenorb suggsted:

```
$ git apply -vv 2997898-21.patch
Checking patch core/modules/block_content/block_content.install...
Applied patch core/modules/block_content/block_content.install cleanly.

$ drush @local.ccad updb
The following updates are pending:

block_content module :
  8601 -   Set 'reusable' field to '1' where it is NULL.

Do you wish to run all pending updates? (y/n): y
Performing block_content_update_8601

```

But sadly, again no luck : (

# Answer
So it turns out that I misconfigured permissions on the body field of my basic block block type. I had meant to restrict permissions for it on another block type. Unfortunately, I didn't notice this when I first rolled out the configuration export to production.

*Edit* thanks to everyone who commented with suggestions. It feels good to know that people were trying to lend a hand and I wasn't alone in trying to figure this out.
> 4 votes

---
Tags: blocks, updating
---


# Question
Title: hook_theme_suggestions_HOOK vs. hook_theme_suggestions_HOOK_alter
Let's say some people are working on a contrib module (link) to provide some obvious template suggestions which are not covered by the default Twig Template naming conventions. View mode for fields, region for blocks etc.

Out of habit I'd use `hook_theme_suggestions_HOOK_alter`. I simply add my suggestions following some logic, done.

> This hook allows any module or theme to provide alternative theme function or template name suggestions and *reorder* or *remove* suggestions provided by `hook_theme_suggestions_HOOK()` or by earlier invocations of this hook.

Then I see there's `hook_theme_suggestions_HOOK` which more or less does the same except for *reordering* or *removing* suggestions. But basically looking at its description it does *exactly* what that contrib module is supposed to do.

> This hook allows modules to provide alternative theme function or template name suggestions.

And now I'm wondering which one of these hooks should be used at best? Is it totally up to us? Do there arise any disadvantages of using the `*_alter` hook? Do we better use the mere suggestion `*_HOOK` to allow other modules to intervene later in the process?

# Answer
> 3 votes
The linked module should try to add suggestions in `hook_theme_suggestions_HOOK` as long as it doesn't depend itself on existing suggestions, so that other modules still have the option to override these suggestions in an alter hook.

Hooks don't have priorities, which having two hooks, one main and one alter hook, is trying to compensate. This is like a priority system with only two levels. If you add something on the second level there is no third level for other modules, unless they resort to unusual solutions like module weights.

---
Tags: theming, hooks
---


title: Loop through entity in a template

text:
# Question
Title: Loop through entity in a template
I have a Site with a Twig Template. I have an multiple entity references which I want to loop trough and print out the name, description of each entity.

In my template I'm using the following code to loop through entities.

```
{% for item in node.field_workers %}
 {{ item.entity.field_name.value }}
{% endfor %}

```

This loops trough all my entities but won't output any value whatsoever. I tried using kint() to debug the process. When I try kint(item.entity) it shows me the following structure:

```
protected fields --> field_name

```

When I try kint(item.entity.fields) it redirects me to 'drupal/install' page when I try to load the page.

What am I doing wrong?

# Answer
> 1 votes
As Kevin says in his comment, Drupal will do most of the work for you if you use view modes on the referenced content type:

`/admin/structure/types/manage/{referenced-content-type}/display`

In your case, you might want to modify the Teaser view mode so that it hides all fields except for Name and Description. (If you are already using the Teaser for something else, you can create a new view mode.)

Then, when you render the entity reference field, just use the format "Rendered Entity" and configure the view mode that you wish to render (e.g., Teaser).

---
Tags: theming
---


# Question
Title: Why is my update query OK for the database but the page shows the wrong value?
I have 2 custom content entities created with Drupal Console (drupal generate:entity:content): 'person' and 'member'.
They are linked (1 member \<-\> n persons) by a field named 'member\_id' in 'person'.
If a person is set with 'iscontact' = true, the other persons related to the same member should have 'iscontact' = false.

In the PersonForm.php, I have this code.

```
public function save(array $form, FormStateInterface $form_state) {
  $entity = $this->entity;

  if ($entity->get('iscontact')) {

    $member_id = $entity->get('member_id')->getString();
    $iId = $entity->get('id')->getString();
    $database = \Drupal::database();
    $query = $database->select('person', 'ap');
    $query->fields('ap', ['id', 'member_id'])
      ->condition('id', $iId, '<>')
      ->condition('member_id', $member_id, '=');
    $results = $query->execute();

    foreach ($results as $key=>$result) {
      $numberofrowsaffected = $database->update('person')
        ->fields(['iscontact' => 0,])
        ->condition('id', $result->id)
        ->execute();
    }
  }

  $status = parent::save($form, $form_state);

  switch ($status) {
    case SAVED_NEW:
      drupal_set_message($this->t('La personne « %label » a été ajoutée.', [
        '%label' => $entity->label(),
      ]));
      break;
    default:
      drupal_set_message($this->t('La personne « %label » a été modifiée.', [
        '%label' => $entity->label(),
      ]));
  }
  $form_state->setRedirect('entity.person.canonical', ['person' => $entity->id()]);
}

```

When I execute this, the table 'person' in the database is correctly updated, but in the page the previous person is still seen as having 'iscontact' = 1.
It's incorrect until I clear the cache. What am I doing wrong?

# Answer
> 2 votes
I replaced

```
foreach ($results as $key=>$result) {
  $numberofrowsaffected = $database->update('person')
    ->fields(['iscontact' => 0,])
    ->condition('id', $result->id)
    ->execute();
}

```

by

```
  $storage = \Drupal::entityTypeManager()->getStorage('person');
  foreach ($results as $key=>$result) {
    $person = $storage->load($result->id);
    $person->iscontact = 0;
    $person->save();

```

And it works!

---
Tags: 8, entities
---


title: How to display the status of the user?

text:
# Question
Title: How to display the status of the user?
I created a TWIG template for the "Teaser" view of the user account.

I want to display a logo and change its color according to the status of the user :

* When the user is logged in `<i class="user-online fa fa-circle fa-lg"></i> Online`
* When the user is logged in and the last access is less than 30 minutes `<i class="user-absent fa fa-circle fa-lg"></i> Absent`
* When the user is offline `<i class="user-offline fa fa-circle fa-lg"></i> Offline`

How to display the status of the user ?

I think it must be possible to create conditions in TWIG

# Answer
you can use template\_preprocess\_user like

```

 /**
 * Implements hook_entity_presave().
 */
function mytemplate_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

```

In you template check on `status` variable like the following:

```
{% if status == 'Online' %}
  <i class="user-online fa fa-circle fa-lg"></i> Online
{% elseif status == 'Absent' %}
  <i class="user-absent fa fa-circle fa-lg"></i> Absent
{% else %}
  <i class="user-offline fa fa-circle fa-lg"></i> Offline
{% endif %}

```

Add `use Drupal\Core\Database\Database;` to the top of your file.
> 2 votes

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


# Question
Title: How to get field value after getting a node?
I have a content type which contains school information. School name and school id are two fields in the content type. I have the school ID and I am able to retrieve the node. How do I get the school name? Below is how I retrieve the particular school node. I used the getValue() to retrieve the school name however, I get an empty array as a response for that. I am able to see the school name if I var\_dump the school node.

```
$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$schoolNode->field_school_name->getValue()

```

# Answer
> 1 votes
If you want to use node object from entityTypeManager, you need to get current value from the array after loading like below:

```
$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$node_load = current($schoolNode);
$schoolname = $node_load->field_school_name->getValue();

```

This is only for a single node. If you have multiple nodes, foreach node as

```
foreach(schoolNode as $node){
  $schoolname = $node->field_school_name->getValue();
}

```

---
Tags: entities, nodes
---


title: Fire javascript on a form submit

text:
# Question
Title: Fire javascript on a form submit
Even the searching I have done that looks like there may be a solution doesn't really seem to answer this.

I have a form with an input value. When the user enters a value and clicks submit, I want to call a javascript routine and make that value available to it.

It seems simple enough, but I can't really find a good answer.

# Answer
You need some jQuery on the page, e.g:

```
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {
    $("form#my-form").submit(function(e) {
      alert('form submitted');
      alert($('form#my-form #edit-name').val());
    });
  }
}

```

You could add to your theme `script.js`, with `drupal_add_js` or form\_alter and `$form['#attached']` ( recommended )
> 8 votes

# Answer
Alternatively you can do this from Form API where you have access to the form directly. This enables complex behaviours and form alterations on AJAX calls.

Take a look at the Ajax framework commands. You'll need to enable AJAX in your form too. Sometimes this is as simple as adding the no-js path argument in `hook_menu` or adding the `use-ajax` class on links. Read up on the AJAX framework in Drupal and ajaxifying forms.

After the hook\_form\_submit you can then return an array of commands to run including the roll-your-own ajax\_command\_invoke.
> 2 votes

# Answer
Here's how I did it:

```
Drupal.behaviors.form_submit_processor = {
  attach: function (context, settings) {

    // Function to be run before form submission
    var preFormSubmit = function () {
      // do some stuff here...
    }

    // Add a js function to run before form submission
    var formE = $('#my-form-id');
    formE
      .on('submit', function (e) {
        e.preventDefault();
        $.when(preFormSubmit()).done(function () {
          formE
            .off('submit')
            .submit();
        });
      });
    }
  };
})(jQuery);

```

Using `$.when(preFormSubmit()).done` allows `preFormSubmit()` to finish before the form is submitted.
> 0 votes

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


# Question
Title: how it's possible to load nodes by taxonomy terms
Here im loading nodes by "type" article, i want to call nodes by another id , but this id is in another table, should i join tables , or it is some other way to do this

```
$type = "article";

          $build = array();
          if ($nodes = node_load_multiple(array(), array('type' => $type))); {
              $build['nodes'] = node_view_multiple($nodes, 'teaser');
          }

```

# Answer
In Drupal 7 conditions are deprecated, it is preferable to use EntityFieldQuery to retrieve a list of entity IDs. You can see more here:
About EntityFieldQuery

In this answer you can see an example: What's the proper use of EntityFieldQuery?

In Drupal 8 you can do something like that:

```
$nids = \Drupal::entityQuery('node')
->condition('your_taxonomy_field', 'your taxonomy id')
->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

```

I hope it helps
> 1 votes

# Answer
Yes i have figure it out, thank you, here is it

function category1\_page() {

```
      $query = new EntityFieldQuery();

      $query
          ->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'article')
          ->fieldCondition('field_blog_category', 'tid', 4);

      $result = $query->execute();

      $build = array();
      if ($nodes = node_load_multiple(array_keys($result['node']))); {
          $build['nodes'] = node_view_multiple($nodes, 'full');
      }

    return $build;

  }

```
> 0 votes

---
Tags: nodes
---


title: Error generating image, no error log

text:
# Question
Title: Error generating image, no error log
I am new to Drupal, I am trying to move an existing site from serverA to serverB.

When I visit

```
http://serverB/sites/default/files/styles/thumbnail/public/publications/43026/cover.jpg

```

I get **Error generating image.**

I am using Drupal 7.22, on an ubuntu server, PHP Version 5.4.9, have php5-gd and mod\_rewrite installed and activated. Error log of apache server is empty. I also have the following directories created.

```
mkdir -p /var/www/sites/all/files/styles/thumbnail
mkdir -p /var/www/sites/default/files/styles/thumbnail
chmod 777 /var/www/sites/all/files/styles -R
chmod 777 /var/www/sites/default/files/styles -R

```

How can I fix/find the source of this problem. Where should I look for some useful error logs.

# Answer
Problem is - you are trying to generate styled image, but you do not provide security token. In Drupal 7.20 and later security token is required so images are only generated when Drupal site itself tries to use them. To turn it off, just add the following line to your settings.php file:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

Solution taken from this answer and 7.20 release notes.
> 3 votes

# Answer
If all permissions are correct. Make sure that ImageMagick is installed on your server for PHP5.

Just run the following commands:

```
sudo apt-get install imagemagick

sudo apt-get install php5-imagick

```

Source: https://stackoverflow.com/a/18150533
> 0 votes

# Answer
FWIW : in my case the problem was that the original image contained errors, so it seems logic that the derivative couldn't be created
> 0 votes

---
Tags: media
---


title: Entityreference multiple choice

text:
# Question
Title: Entityreference multiple choice
I have an entityreference field on users and I can't find a way to select more than one value. I want to make like a multiple select, but with the entityreference.

I use the EntityReference module, here is my form item :

```
$form['maj_planning']['suivi_par'] = array(
  '#type' => 'entityreference',
  '#title' => t('Suivi par'),
  '#required' => FALSE,
  '#default_value' => $entity->suivi_par,
  '#era_entity_type' => 'user',
  '#era_bundles' => array(),
  '#era_cardinality' => 1,
  '#era_query_settings' => array(
    'limit' => 15, // Default is 50.
    'property_conditions' => array(),
    'field_conditions' => array(),
  ),
);

```

How can I achieve this ?

# Answer
> 0 votes
Try this in your .theme file:

```
function MyTheme_user_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $form['maj_planning']['suivi_par']['#multiple'] = TRUE;
}

```

---
Tags: 7, entities
---


title: Hide fields from a view

text:
# Question
Title: Hide fields from a view
I am not sure how to explain this as I have very little experience with Drupal. I built a site with Drupal 7 and now I am trying to recreate it in Drupal 8. I have a problem with the Content area.

I have set up a view that looks like this.

The arrow points to a title name link.

When I click the link, I want to see additional detail not shown in the view. This works. However, there is as an additional view that looks like a “teaser” view that I do not want to be displayed. The area at the top in the rectangle I want and is part of the “Entity View (Content) with a category of Chaos Tools. The bottom part near the x is the teaser part and is a duplicate of the top part I don’t want. How can I remove the bottom part?

# Answer
man. Have you solved yet? There's this custom module that even someone with basics of programming could do. But it is not perfect, you will have to make an extra view and stuff... https://atendesigngroup.com/blog/removing-duplicate-content-across-multiple-drupal-views
> 0 votes

---
Tags: views
---


# Question
Title: How do I enable aggregation in the settings?
I have the same problem as in Views sorting by number of values in field". I would really like to try the solution that is given.

How can I enable aggregation in the view settings? I can't find it anywhere.

The following is a screenshot of the view panel. Is there any other name for "aggregation"?

# Answer
Your view appears to be a search API view, for which "aggregation" is not supported. Which is also why the "Use aggregation" option is not visible (credits: comment to question Clive).

A possible solution (work around?) to make the aggregation option available, is to NOT use the Search API for your view, and instead use a regular content type view (credits: comment to question Alfred Armstrong).

**PS**: Comments may get deleted, for all sorts of reasons, which is why I included them in this answer ...
> 0 votes

# Answer
Pretty old question now, but posting in case anyone comes here looking to do the same thing in D8 with a Search API view.

With D8 version of Search API, when making the index you can add a General field `Aggregated field`.

In the setting of this field, simply select `Count` as the aggregation type and select the field you want to count.

Remember to set the type to `Integer` when looking at the list of added fields.

This will provide a new field in the search View that will display a count of the selected field for that row.
> 0 votes

---
Tags: views
---


title: Get top 5 recent post by taxonomy term

text:
# Question
Title: Get top 5 recent post by taxonomy term
I am new to Drupal and I have started overriding Twig files in Drupal 8. I have a requirement where I want other top 5 posts by taxonomy term.

Suppose I have a category as JavaScript. And I am on the node where I am displaying a post on JavaScript. On the same page I need other posts on JavaScript.

I have looked for twig file `theme/templates/content/node--article.html.twig` and tried to override it.

I have even tried to debug the node using `kint` tool. I have looked for my requirements in node and content variable.

```
{{ kint(node) }}
{{ kint(content) }}

```

But no success. I need suggestion where can I can other posts of same category in twig file. Any suggestion is appreciated.

# Answer
> 1 votes
First of all, you say:

> I have started overwriting Twig files in Drupal 8.

I hope you mean "overriding" Twig files.

Rule #1: *Don't hack core.*

Secondly, as leymannx suggests in the comment above, this is better accomplished using Views rather than in a Twig template.

---
Tags: theming
---