# Question
Title: How to write update db hook for alter the table(make sure the existing data should not corrupt) in drupal
Can anyone please help me to write the update db hook for altering the table. Actually I want change the column size of desc field something like :

function abc\_update\_1001(){ // what will the code }

Example : Table name : shared\_data

```
--------------+---------------+------+-----+---------+-------+
| Field        | Type          | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| id           | varchar(50)   | NO   | PRI | NULL    |       |
| title        | varchar(29)   | NO   |     |         |       |
| desc         | varchar(2000) | NO   |     |         |       |
| time         | datetime      | NO   |     | NULL    |       |
+--------------+---------------+------+-----+---------+-------+

```

The alerted table should look like:

```
--------------+---------------+------+-----+---------+-------+
| Field        | Type          | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| id           | varchar(50)   | NO   | PRI | NULL    |       |
| title        | varchar(29)   | NO   |     |         |       |
| desc         | varchar(3000) | NO   |     |         |       |
| time         | datetime      | NO   |     | NULL    |       |
+--------------+---------------+------+-----+---------+-------+

```

Many Thanks

# Answer
> 3 votes
```
function hook_update_n() {
  db_change_field('shared_data', 'desc', 'desc', array(
    'type' => 'varchar',
    'length' => 3000,
  ));
}

```

---
Tags: hooks
---


# Question
Title: Programmatically created revision set as the main node instead of revision
I am using D8 and creating revision for a node with the following code.

```
  $nid = "my_node_id";
  $node = \Drupal\node\Entity\Node::load($nid);
// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

```

When I create a revision, it is set as the main revision, instead of one of the revisions. Is it taking the revision timestamp when creating, and pushing latest to the top? Is there a function that tells me I am using the latest revision?

# Answer
> 5 votes
You're looking for \Drupal\Core\Entity\RevisionableInterface::isDefaultRevision(), set that to false if you want to save a revision that is not the default revision.

---
Tags: 8, entities
---


title: Access nid in field template

text:
# Question
Title: Access nid in field template
How do I access the `nid` of the current `node` in a `field.html.twig` template?

# Answer
I found myself a solution for this. Maybe not the perfect way to go, but it worked very well for my needs:

in .theme-file:

```
function MYTHEME_preprocess_field(&$variables, $hook) {
   $variables['nodenid'] = \Drupal::routeMatch()->getRawParameter('node');
}

```

and in .twig:

```
{{ nodenid }}

```

of course you might want to filter the preprocess hook to only add this variable to a specific field.
> 1 votes

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


# Question
Title: Form API multiplie file upload validation error
I have a simple form with a multiple file upload field. I am trying to validate the documents against extensions and file size. The validation seems to work, but now if I don't select any file (field is not required), the validation fails and I get an error:

> **Fatal error:** Call to a member function getError() on a non-object in /home/www/test/core/modules/file/file.module on line 726

Here is my validation function:

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

  $validators = array(
    'file_validate_extensions' => array('pdf doc docx xls xlsx txt jpg jpeg png gif'),
    'file_validate_size' => array(7 * 1024 * 1024), // 7MB file size limit
  );

  /** @var File[] $documents */
  $documents = file_save_upload('documents_upload', $validators, 'public://');
  $error = false;
  if(null !== $documents) {

    foreach($documents as $i => $document) {
      if ($document === FALSE) {
        $error = true;
      }
    }

    if ($error === true) {
      $form_state->setErrorByName('documents_upload', 'Error: could not upload file.');
    }
  }
}

```

Any idea?

# Answer
This happened to me today. After some research it's appear that Drupal8 have a bug with empty file form element when this one is multiple.

The `file_save_upload` function expects an array looks like this when element is empty :

```
 ['form_field_name' => NULL]

```

But actually for an empty multiple file form element the array is:

```
 ['form_field_name' => [0 => NULL]]

```

So the condition check for an empty value and fail. The code continue until it try to use getError() on a null value.

Here is a function to check if a file were uploaded or not. You can use it in the validateForm callback of your form class or in a hook.

```
function isFileUploaded($form_field_name) {
  $all_files = \Drupal::request()->files->get('files', array());

  return isset($all_files[$form_field_name]) &&
    !empty($all_files[$form_field_name]) &&
    NULL !== reset($all_files[$form_field_name]);
}

```

It's not very pretty but it'll work until they fix that bug.
> 1 votes

---
Tags: forms, files, 8
---


# Question
Title: Can't change default settings in foundation theme
I am thinking about changing my Drupal site theme to a Foundation based one. I use Windows 7, with the Foundation module installed and activated, along with Ruby, Compass and Sass.

To experiment I have changed this in the scss files:

\_variables.scss:

```
 $row-width: em-calc(1280);
 $column-gutter: em-calc(30);
 $total-columns: 12;

```

\_init.scss:

```
$topbar-height: rem-calc(90);

```

I get no error messages when I navigate to my sub theme's folder and run `compass compile` from the command line. Instead I get this:

```
 write css/custom.css
directory css/foundation
 write css/foundation/foundation.css
 write css/foundation/normalize.css

```

... which looks promising enough. After this I added this to my sub theme's info file:

```
stylesheets[all][] = css/foundation/foundation.css
stylesheets[all][] = css/foundation/normalize.css

```

I also commented out the app.css line in the info file:

```
; For CSS users, load the app.css file:
; stylesheets[all][] = css/app.css
; Comment the app.css file (above) if you're using sass to preprocess css:
 stylesheets[all][] = css/custom.css

```

I have looked in the page source and can confirm that those files are actually loaded.

The width is still is the default 1000px value and the top bar still have the same height (45). And yes, I have cleared all cache.

What have I forgotten?

# Answer
Sorry about the noise... after a couple of hours of struggling I removed these lines in the info file:

```
stylesheets[all][] = css/foundation/foundation.css
stylesheets[all][] = css/foundation/normalize.css

```

... and everything began to work. So never mind this question.
> 1 votes

---
Tags: 7, theming
---


# Question
Title: How to customize the "Read more" link in D7?
By default, the "Read More" link wrapped in the tag `<li>`. How i can change this tag to `<p>`?

I tried to use hook `theme_node_view_alter(&$build)`, but i couldn't find in `$build` required variables.

# Answer
`node_build_content` is where it's originally set. You should be able to override this by implementing `hook_node_view` or `hook_entity_view`. The links should be in `$node->content['links']`
> 0 votes

---
Tags: 7, theming, nodes, navigation
---


title: Redirecting to "old" site

text:
# Question
Title: Redirecting to "old" site
I copied files and database of a Drupal 7 site to another domain.
When I put the site in maintenance mode, and I login, I am redirected and logged in to the *old* site. I cleared the cache, also in the database, but the result is the same. When the site is not in maintenance mode, this doesn't happen.

Additionally, I have to say that I created an SSL connection and checked \_Use a symbolic link from private\_html to public\_html - allows for same data in http and https\_. I don't know if this has something to do with that.

Where is the responsible file? What do I need to do?

# Answer
> 0 votes
Try setting the $base\_url variable to the new site domain. This is in the /sites/default/settings.php file.

---
Tags: maintenance-mode
---


# Question
Title: Install sub-theme without creating blocks
Currently when installing a sub-theme (not sure if this applies to a theme too) blocks from existing themes are copied to the new sub-theme in the Blocks layout section. Is there a way to prevent this from happening? I want to install a sub-theme and then manually add just the blocks I need.

# Answer
They're not really "copied". They're the same blocks from your theme, but moved to the available regions of your subtheme after enabling it (iirc, they move to similarly named regions, disabled if none found).

What you could do is export the configuration. Drupal also keeps track of the active theme and block positions in the config. You could position blocks in the old theme and export the config for that. Then when you move to the new theme, you reposition the blocks and export again. Whenever you feel like switching over, you simply reimport the config you like.

I'm not so familiar with the config management in the UI, but this can be done with Git and Drush `cex`/`cim` quite easily.
> 1 votes

---
Tags: 8
---


# Question
Title: Route isn't being created for custom rest resource
I'm attempting to create a custom rest resource, and have followed very many examples but I can't seem to get it to work. Every time I test it using https://www.hurl.it/ I just get a 301 error.

I'm using http://example.com/myrest\_test/1?\_format=json as the url as a GET request.

My format is as follows. I have a custom module called rest\_test

Inside /rest\_test/src/Plugin/rest/resource/MyRestTest.php I have

```
<?php

namespace Drupal\rest_test\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a resource for accepting rest calls
 *
 * @RestResource(
 *   id = "myrest_test",
 *   label = @Translation("My Rest Test"),
 *   uri_paths = {
 *     "canonical" = "/myrest_test/{id}"
 *   }
 * )
 */

class MyRestTest extends ResourceBase {
    /**
     * Responds to GET requests.
     *
     *
     * @param int $id
     *   The ID.
     *
     * @return \Drupal\rest\ResourceResponse
     *   The response.
     */
    public function get($id = null) {
        $response = ['message' => 'Hey this worked and this is the id'.$id];
        return new ResourceResponse($response);
    }
}

```

and inside a form.js file I have

```
 (function($) {
    $(function() {
        console.log('form.js executed successfully');
        jQuery.ajax({
            url: "/myrest_test/5",
        }).done(function(msg){
            console.log(msg);
        });
    })
 })(jQuery);

```

I receive the 'form.js executed successfully' message so I'm certain the javascript is running, but msg is empty. I've tried with the entire url instead of just the relative one as well. I've also made sure I'm clearing the cache But I can't seem to get any proper response. Is there something I'm missing? Why doesn't my rest resource response to my ajax calls?

UPDATE: Looking in the error logs it looks like I'm getting page not found errors for that rest call

UPDATE 2: When I visit directly in my browser I receive /myrest\_test/{id}

> {"message":"No route found for \u0022GET /myrest\_test//234\u0022"}

UPDATE 3: After narrowing down the issue to it being a routing problem I found a similar question here No route found for custom REST resource however when I add

```
 *   uri_paths = {
 *     "canonical" = "/myrest_test/{id}",
 *     "https://www.drupal.org/link-relations/create" = "/myrest_test"
 *   }

```

I still encounter the same error

# Answer
I'm not sure if there is a different lingering issue, but I was able to solve it by using the REST UI module.

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

Once I installed it I was able to see my route listed on the configuration page, but it was listed as disabled. After enabling the route from the configuration page it started working.
> 0 votes

---
Tags: ajax, 8
---


# Question
Title: How to know all the available BASE_FORM_ID?
I know just a few BASE\_FORM\_ID to use with the `hook_form_BASE_FORM_ID_alter()` hook, there is an old article named Using hook\_form\_BASE\_FORM\_ID\_alter() talking about this.

In the article there is a method to know if a form have en BASE\_FORM\_ID

>

But, how to know all the available BASE\_FORM\_ID in Drupal 7 and Drupal 8?

# Answer
In D8 only entity forms implement the interface `BaseFormIdInterface`. The code to generate the base form id is in `EntityForm::getBaseFormId`:

```
  public function getBaseFormId() {
    // Assign ENTITYTYPE_form as base form ID to invoke corresponding
    // hook_form_alter(), #validate, #submit, and #theme callbacks, but only if
    // it is different from the actual form ID, since callbacks would be invoked
    // twice otherwise.
    $base_form_id = $this->entity->getEntityTypeId() . '_form';
    if ($base_form_id == $this->getFormId()) {
      $base_form_id = NULL;
    }
    return $base_form_id;
  }

```

So for each config and content entity type there is a base form id available: `[ENTITY_TYPE]_form`

In some cases special entity forms override this method, for example the confirm form class `ContentEntityConfirmFormBase` defines `[ENTITY_TYPE]_confirm_form`.

To get all available base form ids the best approach is probably to iterate over all routes that have entity forms or build the form object with the information you find in the entity types. The most work here is to get an entity for the form object, because `getBaseFormID()` depends on this:

```
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Entity\ContentEntityType;

$entityTypeManager = \Drupal::EntityTypeManager();
$base_form_ids = [];
foreach ($entityTypeManager->getDefinitions() as $id => $entity_type) {
  $handler_classes = $entity_type->getHandlerClasses();
  // check if the entity type has form operations
  if (isset($handler_classes['form'])) {
    $entity = NULL;
    // for config load the first entity
    if ($entity_type instanceof ConfigEntityType) {
      $entity = reset($entityTypeManager->getStorage($id)->loadMultiple());
    }
    // for content create a new instance, because we don't know if content exists
    elseif ($entity_type instanceof ContentEntityType) {
      $values = [];
      // if the entity type has bundles we have to provide one when we create the entity
      if ($bundle_key = $entity_type->getKey('bundle')) {
        if ($bundle_entity_type_id = $entity_type->getBundleEntityType()) {
          if ($bundle = reset($entityTypeManager->getStorage($bundle_entity_type_id)->loadMultiple())) {
            $values[$bundle_key] = $bundle->id();
          }
        }
      }
      $entity = $entityTypeManager->getStorage($id)->create($values);
    }
    // if we have an entity, get the base form id for each form operation
    if ($entity) {
      foreach ($handler_classes['form'] as $operation => $form_class) {
        $form_object = $entityTypeManager->getFormObject($id, $operation);
        $form_object->setEntity($entity);
        if ($base_form_id = $form_object->getBaseFormId()) {
          $base_form_ids[$base_form_id] = $base_form_id;
        }
      }
    }
  }
}

```
> 5 votes

# Answer
For Drupal 7 you can invoke `hook_forms` and you'll find the info in the 'callback' returned value.

> Return value
>
> An associative array whose keys define form\_ids and whose values are an associative array defining the following keys:
>
> **callback**: The callable returning the form array. If it is the name of the form builder function then this will be used for the base form ID, for example, to target a base form using hook\_form\_BASE\_FORM\_ID\_alter(). Otherwise use the base\_form\_id key to define the base form ID.

Use this code to get the values:

```
$base_forms = [];
foreach (module_invoke_all('forms') as $form) {
  if (!in_array($form['callback'], $base_forms)) {
    $base_forms[] = $form['callback'];
  }
}
// To use dpm() you need the devel module.
dpm($base_forms);

```
> 3 votes

---
Tags: forms
---


title: $_GET['q'] for all entities

text:
# Question
Title: $_GET['q'] for all entities
I have this code.

```
     if ($_GET['q'] == 'entity/bundle'){
        unset($css[drupal_get_path('module', 'system') . '/system.base.css']);
 }

```

Which I use in template.php to unset css on certain pages, but I want to have code (in this case unset css) to run on all entity pages for example entity/bundle/1, entity/bundle/2, entity/bundle/3. How can I get this to apply to all entity pages. I need something like entity/bundle/% or entity/bundle/\* or maybe there is another way.

# Answer
> 0 votes
Context add assets seems to be a good solution for this https://www.drupal.org/project/context\_addassets

---
Tags: 7, entities
---


# Question
Title: Creating a view with 2 content of different content types
I currently have 2 different content types which are very different from each other. I have also created multiple content using these content types.

I want to create a view which shows only 2 specific contents one below the other. Is this possible? Currently I can only have a view which filters on the two content types but that results in all of the different instances of the content types coming onto the page and not just the ones I want.

The content that I want to show in the view have no relationship with each other, I just want to be able to filter them in using their names.

# Answer
> 1 votes
"2 specific contents" .. if it's very specific / admin decides, add an extra field with code. Fill 2 nodes with something like 'promo' or '1234 Hide this field in the display, so you only see the code when you're editing. In the view, filter on this field (only nodes with this and this code) and voilá.

-edit: in this way you can re-use the view for different codes. Maybe use the URL (like foobar.com/promo shows the 2 nodes with promo in the code field). Tbh, i don't know how to use the URL in Views ;-)

# Answer
> 0 votes
I think you're looking for the group functionality:

1. Under the fields section, click add.
2. Search for "Content type", check the box, and click "Add and configure fields"
3. If you don't want each of your rows displaying the which content type they belong to, check "Exclude from display" on the field configure popup:
4. Go to the Format Settings:
5. Under "Grouping field Nr.1", select "Content: Content Type"
6. Click Apply

This groups all of the rows with the same value to "Content Type". Above each group will be a header with the value of that Content Type. For example, there'll be a header "Basic Page" and below will be listed all of the basic pages.

If you want don't to display the header, you'll have to either override the template (recommended, but harder) or hide it using CSS (less recommended, but easier).

---
Tags: views, nodes, entities
---


# Question
Title: How to alter existing page of a node that is Organic Group and add Two links above
i am using Drupal 7 with og support and also the og corresponding modules (og, entityreference, services\_menu) inside DrupalGap.

As can be seen from the picture i want to add some links(drawed in red color) on top of the display of an Organic Group. I want the subscribe/unsubscribe button AND the navigation buttons above.

# Answer
1. Create a Custom DrupalGap Block
2. Place it above the `title` block within the `region` configuration of the `settings.js` file
3. Use a List Widget and some CSS to render your buttons above the title
> 0 votes

---
Tags: 7, organic-groups, javascript
---


# Question
Title: How to put multiple entity fields inline as sub fields?
Not sure how to explain this so will add an image.

I want a field to have 2 values, one is the type of data, the other is how many, needs to be on the same line.

For example for a website, I need the client to be able to select the photo type, and then how many of them.

I'm using entity form, but a solution for webform also might work, although I prefer entity forms.

# Answer
> 0 votes
Have you considered Paragraphs? It allows you to 1) create predefined sets of fields and 2) allows you to add fields that allow you to add those predefined fields. You have the option to restrict the paragraph selection as well as the number you can add.

A closely identical module is Field Collection although their project page suggests moving to Paragraphs instead.

It's not the two dropdowns you're looking for, but allows you to select a type and add as many as you want.

---
Tags: forms, entities, webforms
---


# Question
Title: How to correctly add Google AMP .js files to my theme
I'm using the Drupal AMP module,theme and library in Drupal 7

I'm using the AMP verification tool here validator.ampproject.org

I have the amp-sidebar working fine except the JavaScript causes an error. When adding the AMP internal js file I get the below error when validating.

```
<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

```

I get the following warning

**"The tag 'script' is disallowed except in specific forms."**

The second error i get is the following. And as a result of that I get this error The tag 'amp-sidebar extension .js script' is missing or incorrect, but required by 'amp-sidebar'. Learn more.

I have included the full HTML file contents below if you want to run it through the validator to see the errors live, Just copy and paste the code. Pastebin of full Drupal AMP page

# Answer
Add the AMP component JS in the `<head>` section of your document, then it will be ok.

```
<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

```

> Extended components are loaded by including a tag in the head of the document https://www.ampproject.org/tr/docs/reference/spec
> 1 votes

---
Tags: theming, javascript
---


# Question
Title: hook_menu - setting a variable to use in page.tpl.php
I know how to use `hook_preprocess_page()` to add/change variables for use in page.tpl.php. For nodes, you can use `menu_get_object()` to load the current node and process it from there.

How do I do this for a page I've created using `hook_menu()`? I've tried printing out all the $variables but there is nothing much I can identify this page with, apart from the 'theme\_suggestions' which seems a bit flaky. Using `arg(0)` also seems like a hacky way to go.

Is there any way to set the page.tpl.php variable directly with `hook_menu()`? That would be ideal.

**EDIT for clarification:**

This is what I want to achieve:

```
function mymodule_menu() {

  $items['my-page'] = array(
    'title' => t('My Page'),
    'page callback' => 'mymodule_callback',
    'access callback' => TRUE,
    'page arguments' => array(),
    'page vars' => array('myvariable' => 'hello') // Obviously this doesn't work, but would be great
  );

}

function mymodule_preprocess_page(&$vars) {

  if($something === 'my-page'){ // What to do here???
     $vars['myvariable'] = 'hello';
  }

}

```

Basically I want something within hook\_preprocess\_page &$vars array to identify the route I have created with hook\_menu. If I can define this somehow in hook\_menu itself (or the callback) it would be even better.

I can use arg(0) but that doesn't account for any subpages, and I might want to change the route which means I need to change preprocess function too. Is there a better way?

# Answer
> 0 votes
Just as an option, you could use a specific page template for your path, and sub-paths.

```
/**
 * Implements hook_preprocess_page
**/
function HOOK_preprocess_page(&$variables) {
  // Optional logic to check path condition
  // e.g arg(), request_uri(), current_path() etc..
  $some_condition = FALSE;
  if(arg(0) == 'base' || $some_condition) {
    // Set single page--base.tpl.php template, for /base and /base/subpath
    // Note: this overrides theme_hook_suggestions[]
    $variables['theme_hook_suggestion'] = 'page__base';
    // Sample template variable
    $variables['foo'] = 'bar';
  }

}

```

Then, in your theme, you can copy `page.tpl.php` to `page--base.tpl.php` and add whatever page specific markup you need in the template.

You could also add logic and template variables to `hook_preprocess_page`. They would be available in your custom template. They can also be added there for the default `page.tpl.php` template. In any case, you will need some condition check for the specific target path match there.

Some relevant API functions to check the URL path include:

Note: `arg()` is also used by core `template_preprocess_page` to set the theme suggestions.

> Uses the arg() function to generate a series of page template suggestions based on the current path.

---
Tags: routes
---


# Question
Title: Multilingual views hide if no translation
My Drupal website has 2 languages and I created **blog view** that lists articles (content type). Default language is English.

Problem is that some articles are only in German and then on my English view I get German articles.

I tried adding **Content: Translation language** Filter that I set to **Interface text language selected for page** but then on German page I only get articles that were created on German and the ones that were created in English but have German translation are missing.

Query :

```
SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN
('article')) AND (node__field_content_type.field_content_type_value = '1')
))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

```

Query with **Translation language** filter:

```
SELECT node_field_data.created AS node_field_data_created,
node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_content_type} node__field_content_type ON
node_field_data.nid = node__field_content_type.entity_id AND
(node__field_content_type.deleted = '0' AND
node__field_content_type.langcode = node_field_data.langcode)
LEFT JOIN {node__field_tags} node__field_tags ON node_field_data.nid =
node__field_tags.entity_id AND node__field_tags.field_tags_target_id = '4'
WHERE (( (node__field_tags.field_tags_target_id IS NULL) )AND((
(node_field_data.status = '1') AND (node_field_data.type IN  ('article'))
AND (node__field_content_type.field_content_type_value = '1') AND
(node_field_data.langcode IN  ('en')) )))
ORDER BY node_field_data_created DESC
LIMIT 5 OFFSET 0

```

From queries, I see that LEFT JOIN is adding **node\__field\_content\_type.langcode = node\_field\_data.langcode** and I think that is making problems when I add the language filter, any suggestion?

# Answer
> 2 votes
The problem was that I was doing condition in views with field that wasn't translatable and views are adding join on `langcode`, thanks to user 4k4 that linked to this issue that can be found here.

I fixed this by removing untranslated field from view and hooking into `hook_views_query_alter` and adding relationship myself :

```
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

function hook_views_query_alter(ViewExecutable $view,
QueryPluginBase $query)
{
    if ($view->id() == 'blog') {
        $definition = [
            'table' => 'node__field_content_type',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
        ];
        $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
        $query->addRelationship('node__field_content_type', $join, 'node__field_content_type');
        $query->addWhere('1', 'node__field_content_type.field_content_type_value', 1, '=');
    }
}

```

Also this hook has to be in `MODULE.views_execution.inc` file

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


# Question
Title: Alter custom menu links with a session variable
I've got a new problem, searched everywhere but was unable to find a solution.

I'm quite new to PHP / Drupal.

To explain :

I would like to use a session variable (got from a form) in my custom menu links, like this :

/path/{year}

So,in a module I have routes and links defined this way :

my\_module.routing.yml :

```
testlink:
  path: '/path/{year}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PageController::init'
    _title: 'Test'
    year: ''
  requirements:
    _permission: 'access content'

```

my\_module.links.menu.yml :

```
testlink:
  title: 'test'
  description: 'test'
  parent: my-custom-menu
  menu_name: my-custom-menu
  route_name: testlink
  route_parameters: { year: '0000' }

```

Everything works fine, my menu link is displayed like this :

/path/0000

But I cannot find a way to use my session variable to replace "0000".

Any idea ?

Thanks in advance.

# Answer
> 1 votes
The menu links defined in yaml files are static. For dynamic menu links you have to use a menu link class:

*src/Plugin/Menu/CustomMenuLink.php*

```
<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class CustomMenuLink extends MenuLinkDefault {

  public function getTitle() {
    return $this->t('Test-Link');
  }

  public function getRouteName() {
    return 'entity.node.canonical';
  }

  public function getRouteParameters() {
    $nid = rand(1,10);
    return ['node' => $nid];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}

```

This example is a menu link randomly selected a node between 1 and 10. For code depending on a session replace the cache max age with a context:

```
  public function getCacheContexts() {
    return ['session'];
  }

```

Point the yaml file to this class to replace the static details of the route with the dynamic methods defined in the class:

*mymodule.links.menu.yml*

```
mymodule.testlink:
  weight: 10
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\CustomMenuLink

```

# Answer
> 1 votes
Again, thanks a lot, I got something that works.

I post here the solution that worked for me, quite the same but just a little bit different because I use the private tempstore : I'm not sure that it's the cleaner way to accomplish this but it works.

my\_module.routing.yml :

```
myroute.testlink:   path: '/path'   defaults:
    _controller: '\Drupal\my_module\Controller\PageController::init'
    _title: 'Test'
    year: ''   requirements:
    _permission: 'access content'

```

my\_module.links.menu.yml :

```
myroute.testlink:
  weight: 10
  menu_name: my-custom-menu
  class: Drupal\my_module\Plugin\Menu\MyCustomMenuClass

```

MyCustomMenuClass.php :

```
<?php
namespace Drupal\import_ctnt\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class MyCustomMenuClass extends MenuLinkDefault {

  public function getTitle() {
    return $this->t('My Custom Title');
  }

  public function getRouteName() {
    return 'myroute.testlink';
  }

  public function getRouteParameters() {
    $year = \Drupal::service('user.private_tempstore')->get('my_data')->get('year');
    return ['y' => $year];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}

```

And that's it.

I now have a parameter in the URL : /path?y=2017

---
Tags: navigation
---


title: drupal_http_request with proxy

text:
# Question
Title: drupal_http_request with proxy
I'm working on proxy based machine where I've configured my proxy settings at settings.php and its working fine.

When I'm trying to access a URL the data is getting displayed perfectly, for instance, https://maps.googleapis.com/maps/api/geocode/json?address=California but when I'm doing the same thing at my `devel/php`

```
$maps_url = 'https://maps.googleapis.com/maps/api/geocode/json?address=California';
$maps_json = drupal_http_request($maps_url);
dsm($maps_json);

```

it's returning me this:

I've confirmed 2 settings in my php.ini:

1. allow\_url\_fopen
2. allow\_url\_include

Where else should I look so that this issue will get fixed?

# Answer
> 0 votes
Found this module cURL HTTP Request via this thread and it worked like charm. The issue was with HTTPS hence the HTTP proxy module wasn't able to help me on this.

---
Tags: http-request
---


# Question
Title: How do I create a role-specific registration page?
I would like to create a "hidden" registration page that I can send to our wholesale customers in order to sign up as dealers, instead of standard authenticated users.

As our dealers have access to wholesale pricing, I will require that this type of user be approved by the admin.

I will need to add a few new fields that I would only like to be shown on this dealer-specific registration page (vs. std), e.g. company, company address, POC. Do I create a new template for this form?

How can I add a Honeypot field to this form?

# Answer
I suggest you to try the Multiple Registration module (https://www.drupal.org/project/multiple\_registration), since this is precisely what it does "adds ability to create role-specific registration pages."

And as for the need to add the "admin approval" functionality, too, for specific user roles on your site, I would recommend you the Registration Role with Approval module (https://www.drupal.org/project/registration\_role\_with\_approval)

Also, see if you will find this post of any help: https://www.optasy.com/blog/how-create-role-specific-user-registration-forms-drupal

Good luck!
> 0 votes

---
Tags: forms, users, commerce
---


# Question
Title: Override global JPEG quality value based on cookie
I am working on a site that has an international audience and that needs to allow users to toggle a "low bandwidth" version. In order to achieve this, I would like to check if a cookie has been set and if so, override the global JPEG quality value from 75% down to, for example, 40%.

How can I override this variable and is this even possible with image caching?

# Answer
This would need a bunch of image styles, a custom field formatter, a custom module that reads that cookie value, and a speed test of some sort.

1. You'd need to create image styles for each of the quality tiers that you want. That part can be done with the built-in image styles module.
2. Then you'd want to create a custom module that:

* Detects the speed of the client's connection and sets that cookie. It can simply be JS downloading a 1KB file download whose start and end times are recorded and set on a cookie.
    * Supplies a custom field formatter to image fields that, instead of making you select a fixed quality, will select the image style and render the image with that image style on-the-fly. As an added bonus, you could allow the formatter to be configurable by exposing a form that allows the selection of which image style to use at certain speeds.
    * Lastly, detects the cookie that was set earlier and informs the field formatter which image style to use based on the cookie value.

This assumes that all imagery are coming from fields (because of the field formatter). For theme imagery, you'll need to render your images by hand in the same way as above, sans the field formatter.
> 0 votes

---
Tags: 8, media
---


# Question
Title: Finding and display custom user variables
I have create a series of user fields. Some of these fields reference taxonomy terms, require a mobile number or are just basic text fields. I used the below to print one of the fields (the number field) inside my page.tpl.php.

```
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$number = $user->field_phone_number['und'][0]['value'];

if (isset($number) && !empty($number)) :
print 'Cell: ' . $number;
endif;

```

My question is how would I go about finding the information I need to print the other fields? The potion that reads `['und'][0]['value'];` in particularly is where i'm stuck. I have used devel before to find this information for node variables but I cant find similar information for custom user variables.

# Answer
It's easier to have Xdebug installed so that you can add breakpoints, pause execution and inspect surrounding variables. Alternatively, you can use Kint to print out variables.
> 0 votes

---
Tags: users, debugging
---


# Question
Title: Views programmatically remove node access (tag)
I'm trying to remove the node access check from a view programmatically. But i'm not sure where the access tags are added/executed.

```
function MYMODYLE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
kint($query);
}

```

If i print the $query the tags are empty, and i can't really figure out where or when those access tags are added. And how to manipulate them.

Can someone point me in the right direction?

Drupal: 8.3.2

# Answer
Found it: MYMODULE\_query\_node\_access\_alter().

$query-\>condition contains al de realm conditions, these can be adjusted here.
> 0 votes

---
Tags: views, 8, domain-access
---


# Question
Title: How do I display highly customized content?
What is the correct way to display parts of a highly customized application? For example my website only consists of a friendlist with user name as well as images and a live chat frame.

Is this the right approach?

1. Create Theme with 2 regions (friend\_list, chat\_frame)
2. Develop custom Blocks for each feature (friend\_list Block and chat\_frame Block)
3. Assign Blocks to the regions
4. Style each Block individually to fit my requirements
5. Add javascript for each block for chat and asynchronous updating of the friendlist (ajax)

Is it better to place all features in one module? Can one module have multiple blocks?

# Answer
> 0 votes
Looks like this is a job better suited for a JavaScript web app (Angular, React, etc.) than using Drupal to render the UI. You can create a dummy module whose only job is to load the JavaScript for your webapp. Then it's all JS from there.

For the back end, assuming Drupal is also powering the data layer, you can use the REST API features of the Views module to send and retrieve data.

Additionally, I wouldn't use block layout for the layout of the site since it's a global layout. This hampers further customization of the layout of the site. Consider using Panels to create dedicated pages that have their own layout. Imagine block layout, but only for a specific page or set of pages.

---
Tags: 8, blocks
---


# Question
Title: How to determine if the current Drupal page is a contact page?
With Drupal 8, in THEMENAME.theme I can generate a class based on the current node ID which will be inserted in the body tag :

In the `THEMENAME_preprocess_html()` function, i use :

```
$node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }

```

But how can i determine if we are on the contact page since it is not a node ?

# Answer
> 7 votes
Have you tried

```
\Drupal::routeMatch()->getParameter('contact_form');

```

This returns an object of type `ContactForm` when the user is on a contact page. A simple detection you can do with `getRouteName()`:

```
if ('entity.contact_form.canonical' === \Drupal::routeMatch()->getRouteName()) {
  // huhu, a contact form
}

```

You can have a look at `./core/modules/contact/contact.routing.yml`. There are all routes available.

---
Tags: 8, emails
---


# Question
Title: How can I output custom html inlcuding js files
I'm trying to output a JS based frontend app through one controller action.

To achieve this I need this action to output a very specific html layout, inlcuding some js files.

As far as i know I can return a symfony response object to bypass drupals render stack, inlcuding themeing mechanism. But how to deal with the js files that should be included? Right now they are located inside my module folder, and I definitly don't want to link to this location inside my custom html output.

# Answer
> 0 votes
If i understand u want to output custom HTML for module, for smoething like this best practice is to preprocess output with twig template, in twig u can generate custom HTML for your needs and of course attach js and css with libraries. See: Theme system overview.

# Answer
> 0 votes
Like mentioned in a comment above, you need a `my_module.libraries.yml` in your module. As an example: Your js files are situated in the folder `./modules/my_module/app`. Then your YAML should looks so:

```
my_custom_library:
  js:
    app/main.js: {}
    app/router.js: {}

```

And in your module you can attach the file when it is needed. For instance in a preprocess hook:

```
my_module_preprocess_node(&$variables) {
  $variables['#attached']['library'][] = 'my_module/my_custom_library';
}

```

Clear cache and your library will be loaded when nodes are on the page.

---
Tags: theming
---


# Question
Title: Do I have to update to 8.3.0 first before I can update to latest stable release?
I pritty messed up my site by updating my 8.2.6 site as followed.

Step 1: I edit my composer.json file. I replaced the replace to require `"replace": {
 "drupal/core": "~8.3"` to

`"require": {
 "drupal/core": "~8.3"`

Because I wanted to update core and vendor I did this composer command step 2: `composer update --with-dependencies`

step 3: Site was broken unexpected error (500) using WAMP 2.4.23, php version 7.0.10 and mysql 5.7.14.

Do I have to update to 8.3.0 first before I can update to latest stable release? \- example: `composer require drupal/core:8.3.0`

# Answer
> 0 votes
It depends on your modules. If you are using DisplaySuite there is an issue with updating because of the change from `layout_plugin` to the `layout_discovery` module. See this issue. And have a look at the 8.3.0 Release Notes for broken changes and affected modules.

---
Tags: 8, updating, composer
---


# Question
Title: Custom View : display fields linked to file upload field?
I'm trying to accomplish this simple thing but cannot find a way to do it. If someone could guide me a little bit because I'm going inside deep crazy methods and classes, but I'm sure I'm going the wrong way and there's a simple way to accomplish this :)

I have a view block, that displays these fields :

* Content: Title (the title)
* Content: Image (Image)
* Content: Pdf (File Upload)

So, the title, the image and the file upload are displayed.

I would like to output something like this :

```
<a href="__link_to_my_pdf__">
    __Title__
    __Image__
</a>

```

Is there a way to do this through the view management ? If not, what could be the right way ? Twig ? Preprocess ? Module ?

I tried through a views-view--myviewblock.html.twig to get the variables inside {{rows}}, but spent 4 hours and failed.

Thanks in advance.

# Answer
Thanks for the link, I'll read it. I finally got an answer on drupal.org that suits perfectly. The idea is to use the "Custom text" field :

> * Add title, image, file and Custom Text field to your view.
> * List item
> * Edit Title, Image field and check exclude from display option and save.
> * Edit File field and check exclude from display checkbox, In Formatter drop down select "URL to file" and save.
> * Edit custom text field
> * Click to "REPLACEMENT PATTERNS"
>
> + Here you can find tokens for title, image and file fields. E.g. {{ title }} fir Title field and {{ field\_image }} for image field.
>     + Copy {{ title }} {{ field\_image }} and paste it to Text.
>     + Then click to "REWRITE RESULTS"
>     + Check "Output this field as a custom link" and enter File field token {{ field\_my\_file }} to "Link Path" textfield. Save this field.
>     + Save the view and now its ready.
> 1 votes

# Answer
For output like this u need to use template suggestions and custom twig template for specific view. See: The Power of Extending Twig Templates
> 0 votes

---
Tags: views, entities, files
---


# Question
Title: How can I translate the Profile 2 field labels?
I can't find a way to translate the fields labels for the Profile 2 fields. I have activated the Profile 2 translation module, but I don't want to translate fields of the entity, I just want to show the labels translated in the user page and the user edit form.

Does anyone know how to do it?

# Answer
> 0 votes
**EDIT:** the following description describes the steps for Drupal 8, but they are similar for Drupal 7:

---

You need the potx module to extract a translation template which you can translate. Unfortunately there isn't an official Drupal 8 release available, but you can use this github fork, which works fine for my needs.

Here is a short procedure to handle translations of my modules:

### 1. extent your module with the Interface Translation Properties (only Drupal 8)

Example `my_module.info.yml`:

```
name: My Module
description: ''
type: module
core: 8.x

'interface translation project': my_module
'interface translation server pattern': modules/my_module/translations/%language.po

```

Now your module is available for the `locale` module and translation can be handled with `drush locale-check` resp. `drush locale-update`.

### 2. create a subfolder for your translations

In the subfolder `./modules/my_module/translations` I put the generated template and the `*.po` files. Fore more information have a look at the documentation on drupal.org.

### 3. create your template

I'm using **drush** to create the template. The best way for me is the creation with

```
drush potx single --folder=modules/my_module/ --api=8

```

It generates a `general.pot` file at the root directory of your Drupal installation. I move it into the translation folder but it's not necessary.

### 4. create your translation

To create a translation I'm using Poedit as editor. You can create different language files from the `general.pot` template. The free version of Poedit is quiet useful for editing `*.po` files. Save your language files in the translation folder.

### 5. import the translations

Run the following commands to import the translations:

```
drush locale-check && drush locale-update

```

And clear the cache:

```
drush cr

```

That's it ;)

---
Tags: users, i18n-l10n
---


title: PHP filtered page is cached

text:
# Question
Title: PHP filtered page is cached
With a few years of Drupal 6 and 7 experience, I've happily made my first Drupal 8 installation. In my previous installations of Drupal I've used custom made PHP code that does a lookup in a personal database. I still need this in Drupal 8.

I've managed to install the PHP filter, and scripts are executed fine, but the page becomes cached, and changes in my database are not seen before I edit the page or empty the cache manually. Inconvenient, to say the least.

According to documentation, PHP filtered pages will not be cached, but evidently my page is.

Any suggestions?

# Answer
> 2 votes
PHP filter is an unrecommended module and you should not use it. It not a secure option and the site maintenance is too difficult.

My recommendation is avoid this module and implements a dummy module with this functionality.

If you decide to use in any case, as you told correctly this pages should not been cached but it depends of your cache config and the place where the php-text is located. I mean, you can use the php filter text in a view or in a block (for example) and the cache behavior will be different.

---
Tags: input-formats, external-scripts
---


title: Content Type Custom Submit Handler

text:
# Question
Title: Content Type Custom Submit Handler
I am very new to Drupal and is still learning. Please excuse if I have done my coding wrong.

**Problem:** I wanted to add two buttons to my Content type.

* 1st button for Save Form - save the form and not publish it.
* 2nd button to Submit Form - save the form and submit it.

My Save Form button works right and it uses the default submit handler.

My Submit Form button is calling a custom submit handler and here is the code:

```
  function submit_Form(array $form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $node = entity_create('node',$values);
  $node->save();

  drupal_set_message('Your form has been submitted. It will be reviewed by the team.');
  $redirect_path = "/user";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);

```

}

I am getting this error:

> Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type node in Drupal\Core\Entity\ContentEntityStorageBase-\>doCreate() (line 83 of /var/www/clients/client1/web2/web/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php).

Thank you for looking at this.

# Answer
> 1 votes
When you create an entity `node` a value `type` for the content type is required. If your form doesn't provide one, you can add it to the values before creating the node:

```
  $values = $form_state->getValues();
  $values[] = ['type' => 'article'];
  $node = \Drupal\node\Entity\Node::create($values);

```

---
Tags: nodes
---


# Question
Title: How to display date/ time of current user base on time zone?
Is it possible to display date/time of current user in his/her profile page. It should be base on his/her time zone settings. How can I achieve this goal?

# Answer
You can modify the user pages (view/edit/etc) with the user templates, like the user profile template In the template's top documentation there's some good info like:

```
 * Use render($user_profile) to print all profile items, or print a subset
 * such as render($user_profile['user_picture']). Always call
 * render($user_profile) at the end in order to print all remaining items.

```

So you can first dpm the $user\_profile array and find out the user's timezone, then add php code after the `print render($user_profile);` to print the date/time according to the timezone value you retrieved from the user profile array.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Filter a view with content from two different content types
I am creating an RSS feed that outputs all posts from two views: one is the men's blog, and the other is the women's. I found out that, when I specify my filters, I need to select both custom content types, leaving me with no results as if one cancels out the other. How do I add these two together, so I get all posts in the feed?

I noticed in contextual filters there is "month + year." I need something like this for two content types.

# Answer
Are you creating two separate filters? For example in your filter list, does it say:

> Content: Type (= MensBlog)
>
> Content: Type (= WomensBlog)

This essentially becomes an AND filter, which means it's looking for a content type that is both MensBlog AND WomensBlog.

You could instead change this to have the data in one filter. Remove one of the filters and click to edit the other one. On this screen, make sure the "Is one of" radio box is selected under Operator and then select MensBlog and WomensBlog. This filter will be an or filter, rather
> 2 votes

# Answer
I ended up adding a new field to both content types labeled RSS enabled, and I was able to filter them together that way. I am not sure if this is the best solution, but it works.
> 0 votes

# Answer
1. Add filter: "Content: Type"
2. Make the operator "Is one of"
3. Select the Women's Blog & Men's blog content type names under "Content Types"

As mentioned by @Chapabu, you have to use only one "Content Type" filter with the "Is one of" filter. If you use two, you're asking for content type that is both Women's and Men's, which is impossible. That's why it's returning none.

Note: Make sure you remove the other "Content Type" filters for this to work. You should have **only one** in the end. Having more will display nothing.
> 0 votes

---
Tags: views, nodes
---


title: How do I start an empty breadcrumb?

text:
# Question
Title: How do I start an empty breadcrumb?
I am modifying a module that extends `PathBasedBreadcrumbBuilder`, but that only has methods to add a link at the end of the bread and I want in certain cases to start the breadcrumb from scratch or add a link at the beginning of the breadcrumbs.

How can I do this?

# Answer
I'm looking at this documentation and I think it says that you could start from scratch using:

```
$breadcrumb = new Breadcrumb();

```

And the class:

```
use Drupal\Core\Breadcrumb\Breadcrumb

```
> 1 votes

# Answer
In your custom PathBasedBreadcrumbBuilder, you have to return true in the applies() method and additionally return your new Breadcrumb object in the build() method.

And you need this import

```
use Drupal\Core\Breadcrumb\Breadcrumb;

```

And in the services.yml of your module you must register the breadcrumb\_builder plugin like so:

```
  preosasde.breadcrumb:
    class: Drupal\preosasde\PreosAsdeBreadcrumben
    arguments: ["@proreosservice", "@request_stack"]
    tags:
      - { name: breadcrumb_builder, priority: 100 }

```
> 1 votes

---
Tags: 8, breadcrumbs
---


# Question
Title: contextual filter for a block view with relationship
I defined two content types : *Book*, *Quote*. A quote has a *Book* field, an entity reference to the book it is extracted from.

I want to build a block view to be displayed on each *Book* node page : all the quotes extracted from that book. In other words, all the quotes whose *Book* field value matches the NID of the current *Book* node.

So I defined

• a relationship `field_book : Content` (`Content using field_property_book`) ;

• a contextual filter : `(field_book : Content) Content : Book` set

* to use `Relationship` = `field_book : Content`
* `When the filter value is NOT available` : `Provide a default value` = `Content ID from the URL` (I also tried `Raw value from URL` \+ element number 2 : node/NID)

The view block displays no results. Obviously, I missed something about configuring a contextual filter for a block view ! Any ideas ? Help to a newbie with relationship greatly appreciated :-) Thanks.

# Answer
I figured it out: the contextual filter should NOT use the relationship, as the *Book* field is in the *Quote* content type!

Finally, this worked: contextual filter `(field_book : Content) Content : Book` set

`Relationship` = `Do not use any relationship`

`When the filter value is NOT available` : `Provide a default value` = `Content ID from the URL`
> 0 votes

---
Tags: blocks, views
---


title: Custom widget not saving

text:
# Question
Title: Custom widget not saving
I've created a custom widget for a textarea (to display the contents in a table as well). So the textarea should appear and work just like a normal textarea widget, but with an additional HTML table of its contents.

I can make it appear correctly, but when I save the form the values do not get saved.

In fact, my "data\_source\_field\_is\_empty()" function is never called (the dpm() text never appears).

```
function data_source_field_widget_form(&$form,
                                         &$form_state,
                                         $field,
                                         $instance,
                                         $langcode,
                                         $items,
                                         $delta,
                                         $element) {
  switch ($instance['widget']['type']) {
    case 'data_source_data_widget':
      $thisItem = isset($items[$delta]) ? $items[$delta]['value'] : '';

      $widget['#type'] = 'textarea';
      $widget['#default_value'] = $thisItem;

      // Only do this if there is already content in the field
      if (isset($items[$delta])) {
        $rows = _data_source_parse_csv($thisItem);

        $widget['#prefix'] = '<button type="button" id="show-hide-raw-table-data">Show raw data</button>';
        $widget['#suffix'] = _data_source_dataTable($rows, 0);

        $form['#attached']['js'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/js/data_source.js',
          'type' => 'file',
        );
        $form['#attached']['css'][] = array(
          'data' => drupal_get_path('module', 'data_source') . '/css/data_source.css',
          'type' => 'file',
        );
      }

      $element[$field['field_name']] = $widget;
      break;

  }

  return ($element);
}

function data_source_field_is_empty($item, $field) {
  dpm("Got here");
  return empty($item[$field['field_name']]);
}

```

Any ideas? I'm looking at the `$element[$field['field_name']] = $widget;` part, but none of the variations I've tried have worked.

# Answer
After studying the code in modules/field/text/text.module, I found the missing item: I had to assign my new widget to $element\['value'\], so:

```
$element['value'] = $widget;
return ($element);

```
> 0 votes

---
Tags: 7, entities
---


title: Edit a node using AJAX

text:
# Question
Title: Edit a node using AJAX
I'm loading the edit node form in a block and I want to use Ajax to save the node.

```
class MyBLockNameBlock extends BlockBase{

  public function build() {
    //I find the $nid i want to display

    $entity = Node::load($nid);
    $form = \Drupal::service('entity.form_builder')->getForm($entity, 'default');

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
      'wrapper' => $wrapper_id,
      'callback' => '::ajaxCallback',
     ],
   ];

   $block['form'] = $form;
   $block['#markup'] = $this->t('<h3>Project Plan</h3>');
   return $block;

  }

  public function validateForm(array &$form, FormStateInterface $form_state)
  {
    if($form_state->hasAnyErrors()){
      return $form;
    }
  }

  public function ajaxCallback(array &$form, FormStateInterface $form_state)
  {
     return $form;
  }
}

```

But it doesn't work. If I change the $form\['actions'\]\['submit'\] to

```
$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes'   =>array('class' => array('btn btn-info use-ajax-submit')),
  '#ajax' => [
    'wrapper' => $wrapper_id,
    'callback' => '::ajaxCallback',
  ],
];

```

The Ajax works but it doesn't validate the form. Should I create the validation by myself for each field?

Also I tried ajax\_form\_entity module but even if the ajax works, reloads the form, doesn't clear the fields after submission and still doesn't validate.

Also I need an extra handler when the user clicks the submit button in order to update a field from an other form.

Any idea?

# Answer
You cannot add elements to the form outside of the form definition. You are adding your form elements in your block class, which is why it's not working as you expect. If you want to alter the entity form, you'll need to use hook\_form\_alter() and add your ajax there.
> 0 votes

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


title: Upgrade drupal commerce kickstart

text:
# Question
Title: Upgrade drupal commerce kickstart
I'm trying desperately to update a customer's e-commerce site. I am a novice in Drupal.

```
Drupal version: 7.18
Drush version: 8.1.10
Install profile: commerce_kickstart

```

I checked with Drush for security updates:

```
drush up --security-only

 Name                                           Installed Version  Proposed version  Message
 Drupal                                         7.18               7.54              SECURITY UPDATE available
 Views Bulk Operations (views_bulk_operations)  7.x-3.1            7.x-3.4           SECURITY UPDATE available
 Address Field Tokens (addressfield_tokens)     7.x-1.3            7.x-1.5           SECURITY UPDATE available
 Chaos tools (ctools)                           7.x-1.2            7.x-1.12          SECURITY UPDATE available
 CKEditor (ckeditor)                            7.x-1.12           7.x-1.17          SECURITY UPDATE available
 Commerce (commerce)                            7.x-1.4            7.x-1.13          SECURITY UPDATE available
 Commerce Kickstart (commerce_kickstart)        7.x-2.0            7.x-2.45          SECURITY UPDATE available
 Ogone (commerce_ogone)                         7.x-1.3            7.x-1.6           SECURITY UPDATE available
 Context (context)                              7.x-3.0-beta6      7.x-3.7           SECURITY UPDATE available
 Date (date)                                    7.x-2.6            7.x-2.10          SECURITY UPDATE available
 Display Suite (ds)                             7.x-2.0            7.x-2.14          SECURITY UPDATE available
 Entity API (entity)                            7.x-1.0-rc3        7.x-1.8           SECURITY UPDATE available
 Entity Reference (entityreference)             7.x-1.0            7.x-1.2           SECURITY UPDATE available
 Features (features)                            7.x-1.0            7.x-2.10          SECURITY UPDATE available
 Fieldgroup (field_group)                       7.x-1.1            7.x-1.5           SECURITY UPDATE available
 Media (media)                                  7.x-1.2            7.x-1.6           SECURITY UPDATE available
 Google Analytics (google_analytics)            7.x-1.3            7.x-2.3           SECURITY UPDATE available
 Internationalization (i18n)                    7.x-1.7+14-dev     7.x-1.15          SECURITY UPDATE available
 Inline Entity Form (inline_entity_form)        7.x-1.0            7.x-1.8           SECURITY UPDATE available
 jQuery Update (jquery_update)                  7.x-2.3            7.x-2.7           SECURITY UPDATE available
 LoginToboggan (logintoboggan)                  7.x-1.3            7.x-1.5           SECURITY UPDATE available
 MailChimp (mailchimp)                          7.x-2.10           7.x-4.8           SECURITY UPDATE available
 Meta tags (metatag)                            7.x-1.0-beta5      7.x-1.21          SECURITY UPDATE available
 Meta tags (quick) (metatags_quick)             7.x-2.7            7.x-2.9           SECURITY UPDATE available
 Migrate (migrate)                              7.x-2.5            7.x-2.8           SECURITY UPDATE available
 Mime Mail (mimemail)                           7.x-1.0-alpha2     7.x-1.0-beta4     SECURITY UPDATE available
 OAuth (oauth)                                  7.x-3.0+18-dev     7.x-3.4           SECURITY UPDATE available
 Services (services)                            7.x-3.3            7.x-3.19          SECURITY UPDATE available
 Rules (rules)                                  7.x-2.2            7.x-2.9           SECURITY UPDATE available
 Search API (search_api)                        7.x-1.4            7.x-1.21          SECURITY UPDATE available
 Search sorts (search_api_sorts)                7.x-1.3            7.x-1.7           SECURITY UPDATE available
 Title (title)                                  7.x-1.0-alpha5     7.x-1.0-alpha9    SECURITY UPDATE available
 Views (views)                                  7.x-3.14           7.x-3.16          SECURITY UPDATE available
 Views Data Export (views_data_export)          7.x-3.0-beta9      7.x-3.2           SECURITY UPDATE available
 Views megarow (views_megarow)                  7.x-1.0            7.x-1.7           SECURITY UPDATE available

```

Of course the update in drush does not work absolutely. I get an error even when performing module backups drush:

```
The date directory could not be found within the modules directory at                                                         [error]
/xxxx/profiles/commerce_kickstart/modules/contrib/date, perhaps the project is enabled but has
been deleted from disk.

```

I tried as asked a commerce\_kickstart update manually by downloading the commerce\_kickstart-7.x-2.45 core. I deleted on my server all Drupal folders and files with the exception of the sites/ folder Then, I copied all the folders and files with the exception of the folder commerce\_kickstart-7.x-2.45 core sites on my server. I tried to access the update.php url and I get a lot of userWarning directly!

```
User warning: The following module is missing from the file system: commerce_discount_date. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following module is missing from the file system: commerce_kickstart_payment. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following module is missing from the file system: commerce_kickstart_service_provider. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following module is missing from the file system: jirafe. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following theme has moved within the file system: shiny. In order to fix this, clear caches or put the theme back in its original location. For more information, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following module is missing from the file system: commerce_kickstart_checkout_redirect. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following module is missing from the file system: imagcache_actions. For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following theme has moved within the file system: alpha. In order to fix this, clear caches or put the theme back in its original location. For more information, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).
User warning: The following theme has moved within the file system: omega. In order to fix this, clear caches or put the theme back in its original location. For more information, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1138 of /xxx/includes/bootstrap.inc).

```

I also try to reinstall these modules as suggested documentation =\> impossible with drush always errors, even no way to make a clear cache either.

I still tried to update the 84 pendings updates =\> ERROR

```
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. update.php?op=selection&token=tLbdNHx9Y0AFjTKaNYc_NuAif0VkT_HPsfb6pIS7f8Q&id=42504&op=do StatusText: OK ResponseText: Fatal error: Call to undefined function inline_conditions_get_info() in /xxx/profiles/commerce_kickstart/modules/contrib/commerce_discount/commerce_discount.rules.inc on line 12

```

And here is the content of the error page:

```
DatabaseSchemaObjectExistsException: Table field_data_commerce_compatibility_strategy already exists. in DatabaseSchema->createTable() (line 660 of /xxx/includes/database/schema.inc).

```

What I also had by trying the update with Drush from commerce\_kickstart !!!

Someone would have an idea because I find no information on the Internet ???

# Answer
> 0 votes
It's advised that you *do not* use the typical Drush workflow, nor updating individual modules. The first step is to review our documentation, which highlights upgrading, https://drupalcommerce.org/commerce-kickstart-2/install.

The *first* step that I recommend is getting the Features Override module to capture your customizations. Enable this module and create a feature containing all of your changes to the base of CK2. We have test coveraging asserting that this works from upgrading from even Features 1.x to the 2.x upgrade.

The most important thing to remember is that a distribution should be treated like updating Drupal core. It will replace *everything* but the following

* sites/all
* sites/default

# Answer
> 0 votes
Hi you've dug yourself into a hole. To start with the original system was a distribution, someone has gone an removed the modus from the modules profile folder and put it in the sites/all/modules folder . They have either have the module in the tow pleases or have deleted it from one location an placed it in the other. That was you initial issue which wasn't that problematic to resolve.

Now you've gone an done a number of more dramatic changes which are mode complex to resolve.

---
Tags: commerce
---


# Question
Title: Drupal 8 Development - How to Loop Through Field Formatter Elements
All-- I'm trying to wrap my head around Drupal 8 development, and I'm trying to create a very simple field formatter. It's being applied to a multi-file field, and I'm just trying to display information for each file uploaded to a custom content type that uses this field.

But-- I'm having issues figuring out exactly how to properly pass data from my PHP files to my Twig template. The code and Twig template below are displaying info about the two files uploaded to a page just fine, but as you can see, I'm not looping through an array of items; I'm just inserting the variable names for some metadata I'm trying to display for some file objects, yet it's looping through and displaying the info for each file uploaded to the page even though I'm not doing a Twig loop. Also-- if I add HTML above or below the Twig template placeholders ({{uri}} and {{filename}}), the HTML is being duplicated for each file that has been uploaded to the page.

So long story short: how should I massage my code to pass data to Twig such that I can loop through it with a Twig loop (e.g., {% for item in items %}) and also prevent any additional markup in the Twig template from being duplicated?

NOTE: here is the original viewElements() function that I was using, and that was causing my issue; all the code after this block is the final code that actually works:

```
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();
    foreach ($items as $delta => $item) {
    // Render each element as markup.
      $element[$delta] = array(
      '#items' => array(
      'uri' => file_create_url($item->entity->get('uri')->value),
      'filename' => $item->entity->get('filename')->value,
      '#theme' => 'video_file_display',
    );
   }
   return $element;
 }

```

From FieldFormatter PHP file:

```
public function viewElements(FieldItemListInterface $items, $langcode) {
$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
 $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}
return $element;
}

```

From .module file (hook\_theme):

```
function field_formatter_test_theme(){
  return array(
    'video_file_display' => array(
      'variables' => array(
        'items' => array(
          'uri' => NULL, 'filename' => NULL),
        ),
      'template' => 'video-file-display',
    ),
  );
}

```

Twig template:

```
<h3>Here is my page</h3>
{% for item in items %}
  {{item.uri}}<br/>
  {{item.filename}}
{% endfor %}

{{ kint() }}

```

Sample page output:

```
Here is my page
Twig context array(15)

```

(and examining the kint output shows null values for 'uri' and 'filename')

# Answer
> 2 votes
You define N #theme render arrays, if you want to be able to control the output in a single template, you need to define only one #theme element and pass it either two array of values or an array of arrays with a uri and filename key each.

```
$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
  $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}

```

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


# Question
Title: Prevent users from editing or viewing their own profile
What is the best way to disable access to the user's profile for viewing and editing? Basically users can create an account but won't be able to edit or view their own or other users' profiles.

# Answer
> 12 votes
Add this to a custom module:

```
function MYMODULE_menu_alter(&$items) {
  $items['user/%user']['access arguments'] = array('access user profiles');
  $items['user/%user']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('administer users');
  $items['user/%user/edit']['access callback'] = 'user_access';
}

```

This will put the user profile view under 'View user profiles' permission and edit under 'Administer users'.

# Answer
> 12 votes
Since the question doesn't seem to be specific for Drupal 7, this is how you do it in Drupal 8.

`hook_menu_alter()` is no used anymore; instead you use a `RouteSubscriber` class, as described in Altering existing routes and adding new routes based on dynamic ones.

The code for the `RouteSubscriber` class would look like this one.

```
namespace Drupal\my_module\Services;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.edit_form')) {
      $route->setRequirement('_permission', 'administer users');
    }

    if ($route = $collection->get('entity.user.canonical')) {
      $route->setRequirement('_permission', 'administer users');
    }
  }

}

```

The route names are taken from the User module. In `setRequirement()` you can do everything you can do in the normal route config. Note that `setRequirement()` adds a permission (or role, etc.), but the `["_entity_access"] => "user.update"` requirement is also still part of the route.

Then you need to register the service in your module's service YAML file.

```
services:
  my_module.route_subscriber:
    class: Drupal\my_module\Services\RouteSubscriber
    tags:
      - { name: event_subscriber }

```

# Answer
> 0 votes
Instead of creating a module for that you could simply create a rule.

Here's a how-to:

step 1: create a rule that acts on this event: "User account page is viewed"

step 2: set a condition, something like: "NOT User has role(s) Parameter: User: \[account\], Roles: administrator"

step 3: create an action: "Page redirect Parameter: URL: toboggan/denied" (in case you are using login toboggan but any page url should work here so you could create a page especially for that saying something like: "We're very sorry but at this moment you can't access your profile page."

step 4: make this rule active for example in case you wanted to get the latest version of your production site, download a sql backup, fiddle around with it locally and then be sure to upload it again without disappointing any users who might wanted to update their profile in the mean time.

additionally you could also add another condition to check if the user is viewing another user's profile page or their own so that you make two different rules, one which shows a page saying that they temporarily can't update their profile and another rule which shows a page that states why they can't view a particular user's profile.

I've tested this and added this condition: "Data comparison Parameter: Data to compare: \[account\], Data value: \[site:current-user\]" What this does is only deny access to view their own account and then show the correct page you created for this denied access. I think this makes more sense.

---
Tags: 7, users
---


# Question
Title: How can I override certain breadcrumb segments?
Drupal seems to be adding some default breadcrumbs that come from the URL. How can I disable this feature? I don't see it in configuration but maybe I'm looking in the wrong place.

# Answer
> 4 votes
The default breadcrumb builder is defined in the system services file and has the priority 0:

*system.services.yml*

```
  system.breadcrumb.default:
    class: Drupal\system\PathBasedBreadcrumbBuilder
    arguments: ['@router.request_context', '@access_manager', '@router', '@path_processor_manager', '@config.factory',  '@title_resolver', '@current_user', '@path.current']
    tags:
      - { name: breadcrumb_builder, priority: 0 }

```

If you want to turn off the default breadcrumb builder you define one with a higher priority. This is an example for taxonomy terms:

*taxonomy.services.yml*

```
services:
  taxonomy_term.breadcrumb:
    class: Drupal\taxonomy\TermBreadcrumbBuilder
    arguments: ['@entity.manager']
    tags:
      - { name: breadcrumb_builder, priority: 1002 }

```

With the method `applies()` you choose for which routes the breadcrumb builder should be used:

*TermBreadcrumbBuilder::applies()*

```
  public function applies(RouteMatchInterface $route_match) {
    return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
      && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
  }

```

The breadcrumb manager checks all applies() methods, starting with the highest priority, until it reaches the default breadcrumb builder, which applies for all routes:

*PathBasedBreadcrumbBuilder::applies()*

```
  public function applies(RouteMatchInterface $route_match) {
    return TRUE;
  }

```

# Answer
> -1 votes
In D8, breadcrumbs are now blocks. They can be disabled in Block Layout.

---
Tags: 8, breadcrumbs
---


# Question
Title: How do I add a custom script on a specific page?
I wanted to add custom JavaScript code on certain nodes. I have written this code in the *html.tpl.php* template, but this doesn't work. (*donate* is the path alias for a node.)

```
<?php if(arg(0) == 'DONATE'): ?>
  <script>
    (function() {
      // ...
    );
  </script>
<?php endif; ?>

```

# Answer
> 8 votes
You could do this:

```
<?php
$node = menu_get_object();
if ($node && $node->nid == DONATE_NODE_ID):
?>
<script></script>
<?php endif; ?>

```

But a better way would be to:

1. Wrap your script in Drupal.behaviors:

```
(function ($) {
  Drupal.behaviors.NameOfYourTheme = {
    attach: function (context, settings) {
      // Your JS code goes here.
    }
  }
})(jQuery);

```
2. Call `drupal_add_js()` in `hook_preprocess_page()`. This code would go to `template.php`:

```
function YOUR_THEME_preprocess_page(&$variables) {
  $node = menu_get_object();
  if ($node && $node->nid == DONATE_NODE_ID) {
    drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/path/to/js.js');
  }
}

```

# Answer
> 1 votes
Use the following code in your theme's template file

```
function mythemename_preprocess_page(&$vars, $hook) {

 $node = menu_get_object();
 if ($node && $node->nid == "node id of this node here"):
    drupal_add_js(path_to_theme().'/js/events.js');
  }

  $vars['scripts'] = drupal_get_js();
}

```

# Answer
> 1 votes
I like this solution because you can use path aliases w/ wildcards. https://gist.github.com/bjmiller121/3d6cf18ceccc8de5c057

Note: this solution uses aliases so it probably only makes sense to use it when URLs are very predictable and do not change.

In your theme's template.php (or custom module)

```
/**
 * Implements hook_preprocess_html
 * @param $variables
 */
function themename_preprocess_html(&$variables) {

  $alias = drupal_get_path_alias(current_path());
  $urls = array(
    'example/url',
    'example/url/*',
  );
  $patterns = implode("\n", $urls);

  if (drupal_match_path($alias, $patterns)) {
    // Do something only on ther specified URL patterns
  }

}

```

# Answer
> 0 votes
In your html.tpl.php file, use below code to implement javascript on your node.

```
if(arg(0) == 'node') {
        $arr_list_of_nodes = array('3', '4', '7');
        $nid = arg(1);

        if(in_array($nid, $arr_list_of_nodes)) {
                ?><script type=""text/javascript"" language=""Javascript"">
                        //your js code
                </script><?php
        }
}

```

Hope this helps you.

Thanks!

---
Tags: 7, javascript
---


# Question
Title: why importer cannot map to custom field type
I've created a custom field type and added a field with this field type to my content. When I add set any data on Node Edit page, the data will store into the database successfully. But if I try to set the data via feeds importer, in mapping, this field is missing. I don't know if I missed any hook function in my module, or is there any setting I have to do in my module.

Here, I list all hook functions I am using:

1. hook\_field\_info
2. hook\_field\_widget\_info
3. hook\_field\_widget\_form
4. hook\_element\_info
5. hook\_theme
6. hook\_content\_is\_empty

Does anyone have any idea about why I cannot find my field in mapping list? If you need more information, please leave me a message. Thank you!!!

# Answer
You may also need to specify the field mapping details in:

`hook_feeds_processor_targets_alter`

> Alter mapping targets for entities. Use this hook to add additional target options to the mapping form of Node processors.

Example implementations: http://www.drupalcontrib.org/api/drupal/contributions%21feeds%21feeds.api.php/function/implementations/hook\_feeds\_processor\_targets\_alter/7

More info: http://www.drupalcontrib.org/api/drupal/contributions%21feeds%21feeds.api.php/group/mappingapi/7
> 1 votes

---
Tags: 7, entities, feeds
---


# Question
Title: Programmatically update or add a user's avatar
I'm trying to update the user avatar in my custom module. Which method shall I use to update the image in db as well as to move the file to public directory?

Thanks.

# Answer
> 3 votes
The file gets stored to `file_managed` table like this:

```
// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
  'uid' => 1,
  'filename' => $_FILES['file_id']['name'],
  'uri' => 'public://pictures/' . $_FILES['file_id']['name'],
  'status' => 1,
]);
$file->save();

```

And I manually updated `user__user_picture` table which is referring to the `fid` in the above table.

Finally I ended up with `move_uploaded_file` to store the image to the filesystem. I'll proceed with this approach until I find a better way to do the same.

http://www.drupal8.ovh/en/tutoriels/47/create-a-file-drupal-8

# Answer
> 3 votes
```
$user = \Drupal\user\Entity\User::load($uid);
$user->set('user_picture', $fid);
$user->save();

```

---
Tags: users, 8
---


title: Notice: Undefined index

text:
# Question
Title: Notice: Undefined index
I copy the site files to my local testing environment(win7, not linux os). The site cannot run normaly. The error notes show below:

```
Notice: Undefined index: sidebar_first in include() (Line 138 of C:\xampp\htdocs\web\modules\system\page.tpl.php).
Notice: Undefined index: sidebar_second in include() (Line 144 of C:\xampp\htdocs\web\modules\system\page.tpl.php).
Warning: file_put_contents(temporary://fil5572.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55A2.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55B2.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).
cannot be created.
Warning: file_put_contents(temporary://fil55C3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).cannot be created.
Warning: file_put_contents(temporary://fil55E3.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc). cannot be created.
Warning: file_put_contents(temporary://fil55E4.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (Line 1938 of C:\xampp\htdocs\web\includes\file.inc).cannot be created.

```

I need your help to solve this problem.

# Answer
> 1 votes
This is most probably a problem with settings for the temporary directory, which is a typical issue moving from Linux OS to Windows or vice versa (this goes for the warning messages that you described)

You should go to: admin/config/media/file-system and set the temporary directory correctly for your local system.

The first two messages are PHP notices which are not critical, but indicating that there is a minor issue within your template files not correctly verifying variables. This is something that would normally be suppresed in a production environment and therefore you might not see this on your other server but it is there too.

By the way: I doubt that you are using Drupal 8 as you are indicating in tags, because page.tpl.php is something that clearly points to Drupal 7.

---
Tags: 8
---


# Question
Title: Render field by name in custom content node template
I'm trying to create a custom node template in drupal 8.

I've added the content type and am displaying them in the Front Page view.

I would like to render each field in the in the the node template (node--content-type.html.twig).

Using the recommended {{ content.field\_name }} syntax, causes the node to print nothing except the title.

Are there any prerequisites to using this syntax, what am I missing here?

# Answer
> 0 votes
Ended up installing a fresh copy of Drupal and re-adding the content type (through the UI as before). After that it worked fine.

Not sure why that happened, no time to debug, will just continue with this install.

I suspect either I broke the the 'Frontpage' view while fiddling, or one of the Modules was breaking it, perhaps Twig Field Value.

I need to now access a multi value field in Twig, thinking something like {{ content.field\_name.0 }}. I need to access the array directly without the use of a foreach loop, because they fit into different parts of the html layout.

Thanks for the responses!

---
Tags: nodes, entities
---


title: How to embed a view in a specific node?

text:
# Question
Title: How to embed a view in a specific node?
I try to embed a view in a specific node. I found tutorials for doing this with Drupal 7 and PHP-Templates:

```
<?php print views_embed_view('view_name'); ?>

```

But I look for a way in Drupal 8 with twig-Templates. I tried to call the `views_embed_view()` function in the `hook_node_view()` and assign it to the node so that I can print it out in the twig-Template. But it seems that this hook never gets called.

Any hints/solutions how to do this in the Drupal 8 way?

# Answer
> 22 votes
**Twig Views Embed**

> This module allows to embed views with a twig function.
>
> ```
> {{ views_embed_view('view_name', 'view_id') }}
>
> ```

The above module was depreciated in favour of

**Twig Tweak**

> Twig Tweak module provides a Twig extension with some useful functions and filters that can improve developer experience.

Ex: `{{ drupal_view('view_name', 'view_machine_name') }}`

You can find the `view_machine_name` **over here**

# Answer
> 8 votes
This is the way it worked for me in Drupal 8 beta 12 sub-theme of Classy.

In the your\_theme.info.theme file

```
function stjameskidsclub_preprocess_node(&$variables){
  $stuff  = views_embed_view('policy_documents', 'embed_1', 28);
  $variables["my_view"] = \Drupal::service('renderer')->renderRoot($stuff);
}

```

I copied the node.html.twig and surrounded the article tags (or the area you wish to replace) with a twig block. I placed this in the /template/content folder.

```
{% block replace_area %}
  <article{{ attributes.addClass(classes) }}>

    ...

  </article>
{% endblock replace_area %}

```

Then I created a node--2.html.twig (replace 2 with desired node) in the /template/content folder with the following code.

```
{% extends "node.html.twig" %}

{% block replace_page %}
  {{ my_view }}
{% endblock %}

```

# Answer
> 4 votes
The first problem you're fighting with is that rendered entities like nodes are now cached by default, so hook\_node\_view() is only called once after a cache clear/saving that node.

However, this is fairly easy to disable, see settings.local.php.

Then, putting the output of a view in $build is fairly easy and more or less works like in 7.x. Instead of using the embed function, consider using $views = Views::getView() and then $views-\>buildRenderable()

Two tips:

* Make the key you use for $build available as an extra field in hook\_entity\_extra\_field\_info(), then check the display if the component is enabled (see how user\_user\_view() does that. That allows you to configure the weight/placement of the view in the UI and also hide it on certain view modes.
* If your view has a page, then it is a bit more complicated, as the node output is cached. You need to make the cache key aware of the pager then, see comment\_entity\_build\_defaults\_alter() for an example (not a view, but that is the closest example that core has).

# Answer
> 2 votes
As Berdir alluded to View-\>buildRenderable is what you're looking for, but to give some more context in a module you'll need to do the following.

```
//use core libraries
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;

//use views class
use \Drupal\views\Views;

function hook_node_view(&$build, $node, $display, $view_mode){

 $thisView = Views::getView('view_name');

 $build['arbitrary_render_array_key_here'] = $thisView->buildRenderable('block_1',array($your_arguments));

}

```

Then in your page template you can access it with

```
{{ page.content.theme_name_content }}

```

# Answer
> 0 votes
Within views, you can create a block with your relevant data.

After block creation, you can assign the block to appear in your desired content area (footer/header/content/etc). Assign it, and then click "configure". You should be able to "Show block on specific pages". Selecting "Only the listed pages" and adding /node/your-node-number to the page specification should limit that view/block to appearing only with your desired node.

Cheers!

# Answer
> 0 votes
I know you mention you'd like to use twig templates but you could use the Views Reference Field module to avoid having to dig around in templates. Also gives the advantage of being able to add it to any fieldable entity so that content editors can configure the view / output.

---
Tags: views, 8, nodes
---


# Question
Title: Add query condition for referenced user by user ID
I have created a content type with machine name `user_points` and let's say have the following fields for this content type:

```
nid,
title,
reference_id (text),
user (reference of user entity),
points (integer)

```

the following code give me the sum of all points.

```
$storage = $this->entityTypeManager()->getStorage('node');
    $total_points = $storage->getAggregateQuery()
      ->condition('status', 1)
      ->aggregate('points', 'SUM')
      ->condition('type', 'user_points')
      ->execute();

```

I would like to add a condition to get total points for specific referenced user by user ID. How can I do it?

# Answer
if the machine name of user entity referenced in `user_points` content type is for example `field_my_user`, the following condition can be added to the query above to select only nodes with referenced user equal to `$user_id`

```
->condition('field_my_user.entity:user.uid', $user_id)

```
> 1 votes

# Answer
The user id for nodes is stored in node\_field\_data and/or node\_revision depending on some settings in your content\_type. Join these tables on nid/vid and add a condition for your uid/revision\_uid.
> 0 votes

---
Tags: entities, database
---


# Question
Title: How to create text base field without format?
How to create base field without `format` surplus?

E.g. this

```
$fields['data'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('XML Data'))
  ->setDescription(t('The product XML data.'));

```

creates two columns in the table:

```
`data__value` longtext,
`data__format` varchar(255) CHARACTER SET ascii DEFAULT NULL,

```

# Answer
> 2 votes
Text (plain, long) field type is `string_long`.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21StringLongItem.php/class/StringLongItem/8.2.x

---
Tags: 8
---


# Question
Title: How to add class only to top level ul in main menu
I am new to drupal theming.I want to add class only to top level ul in main menu.Using theme\_menu\__tree\_main\_menu() affect all the ul tag.I found this for adding class only to top level..https://www.drupal.org/node/988694 function THEMENAME\_menu\_tree\__menu\_top\_menu($variables) { return '' . $variables\['tree'\] . ''; } But it didn't work.Doesn't adding any class.Am I missing something?Please Suggest Me!!Thank

# Answer
That example is missing some code. Those two empty strings should not be empty.

There is a link on that page just above the code example to api documentation of theme\_menu\_tree() https://api.drupal.org/api/drupal/includes%21menu.inc/function/theme\_menu\_tree/7.x

On the api documentation page you can see it done correctly:

```
return '<ul class="menu">' . $variables['tree'] . '</ul>';

```
> 0 votes

---
Tags: theming, navigation
---


# Question
Title: How to use more than 2 versions on jquery?
I want to use bootstrap theme and it requires jquery 1.9, but when I set 1.9, ajax enabled views do not work. I am using views 3.14. There are few contrib modules which require older version of jquery. So in jquery\_update I can set "default drupal" for admin pages and 1.7 for the site.

How to get 1.9 as well for my site with no conflicts?

I have found jquery multi module during search, but do not know if it is what I am looking for.

Secondly, Can I use this module with jquery update enabled?

# Answer
Since you need to run multiple versions of jQuery for different contrib modules I would say the jQuery multi module would be the easiest solution (although I don't know the specifics of your requirements).

The 7.x-2.x branch of jQuery update is supported with jQuery multi.

For example, you could use Drupal default jQuery for admin pages, jQuery 1.7 for non-admin pages and jQuery 1.9 for the specific plugins/modules that require it. Or alternatively you can use 1.9 as the main version and 1.7 for specific plugins/modules. Whichever works best for your site.

Usage instructions for the jQuery multi module can be found in its README.txt file when you download it.
> 1 votes

---
Tags: 7, views, javascript
---


# Question
Title: Compound field that includes a file field
I'm trying to figure out how to create a custom compound field, but I'm not quite sure how to add a file field to it. There are plenty of tuts on creating compound fields that are comprised of text fields, but I can't find any that talk about combining text and file fields. I guess the main problem is that I don't understand how the 'schema' function would work, since it refers to Drupal data types, but the data uploaded via the file field won't be stored in the Drupal database, but rather stored on disk, as any other uploaded file would be.

Can someone point me in the right direction?

# Answer
A file field is an entity reference field pointing to the `File` entity (or in D8.4 to the `Media` entity). To build such a file field extend `FileItem` (which parent is `EntityReferenceItem`). An example for this would be the image field `ImageItem`, which is a compound field adding properties like title, alt, height and width:

*ImageItem::propertyDefinitions()*

```
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    unset($properties['display']);
    unset($properties['description']);

    $properties['alt'] = DataDefinition::create('string')
      ->setLabel(t('Alternative text'))
      ->setDescription(t("Alternative image text, for the image's 'alt' attribute."));

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t("Image title text, for the image's 'title' attribute."));

    $properties['width'] = DataDefinition::create('integer')
      ->setLabel(t('Width'))
      ->setDescription(t('The width of the image in pixels.'));

    $properties['height'] = DataDefinition::create('integer')
      ->setLabel(t('Height'))
      ->setDescription(t('The height of the image in pixels.'));

    return $properties;
  }

```

The properties for the referencing part are inherited from the parent.
> 0 votes

---
Tags: entities
---