title: How to keep track of days online?

text:
# Question
Title: How to keep track of days online?
I'd like to display the total number of days that users were online in a View on their profile pages.

How can I do this?

# Answer
> 2 votes
This problem can be solved with a variant of my solution for a more general problem. In particular, here are the adaptations that have to be made. Add a new user Date field *Last day online* that stores a day, month and year. Also create a user integer field *Total days online*. Then use the following Rule:

```
{ "rules_extra_day_online" : {
    "LABEL" : "Extra day online",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "NOT data_is" : {
          "data" : [ "site:current-user:field-last-day-online" ],
          "value" : "today midnight"
        }
      }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "site:current-user:field-total-days-online" ],
            "op" : "+",
            "input_2" : "1"
          },
          "PROVIDE" : { "result" : { "new_total" : "New total" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-total-days-online" ],
          "value" : [ "new-total" ]
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-last-day-online" ],
          "value" : "today midnight"
        }
      }
    ]
  }
}

```

This is what the Rule does in words:

* First, check that the current user is verified, and make sure the user's *Last day online* is not `today midnight`.
* If the above requirements are satisfied, then increase the *Total days online* by one and change the *Last day online* to `today midnight`.

# Answer
> 2 votes
You can use Visitors module.

It will give you the following reports:

> View pages that have recently been visited.
> View pages that have been hit frequently.
> View pages count per month.
> View pages count per day of month.
> View pages count per day of week.
> View pages count per hour.
> View pages count per host.
> View access log.
> View user activity report (hits, nodes, comments).
> View referer list.

and many more things.

Maybe for your requirement you need some customization.

# Answer
> -1 votes
You can take a clue form User Stats module if it doesn't support your requirement and implement your own custom solutions to track user logged in days...

> Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
>
> days registered; join date; days since last login; days since last post; post count; login count; user online/offline; IP address;

---
Tags: 7, views, users, nodes
---


# Question
Title: When is a module shown as 'Unsupported' in the list of available updates?
In the available updates, there are few modules with the note *unsupported*.

What does that note actually mean?

# Answer
> 1 votes
In Drupal 8, that string is output from `UpdateManagerUpdate::buildForm()`, which contains the following code.

```
  case UPDATE_NOT_SUPPORTED:
    $type = 'unsupported';
    $entry['title'] .= ' ' . $this->t('(Unsupported)');
    $entry['#weight'] = -1;
    break;

```

The `UpdateManagerInterface::NOT_SUPPORTED` constant simply means the current release is no longer supported by the project maintainer. The maintainer doesn't intend to further develop the module code, not even to fix security issues. If you look at the project page, you will notice the following note, given under the *Project information* section.

> Unsupported
> Not supported (i.e. abandoned), and no longer being developed. Learn more about dealing with unsupported (abandoned) projects

As such, the update page is suggesting to find another module with the same, or similar, features because, in case of security issues, chances are nobody is going to fix them, and the module would need to be uninstalled, to avoid site issues.

In Drupal 7, a similar string is output from `theme_update_status_label()`, which contains the following code.

```
case UPDATE_NOT_SUPPORTED:
  return '<span class="not-supported">' . t('Not supported!') . '</span>';

```

The `UPDATE_NOT_SUPPORTED` constant has the same meaning saw for Drupal 8, and it was introduced in Drupal 6.

# Answer
> 0 votes
The question doesn't say which version of Drupal it is about, and for D6 you don't get such "`unsupported`" (only a variation of it, something like "`not supported!`". So assuming this question is about D8, you probably see a message containing (exactly) "`unsupported`" as in this image.

If my (educated) guess is correct, you possibly get such message for some module which is no ***`longer available for download`***. At least that's what is mentioned also in the linked image. Apart from this, be aware of this D8.6 issue ... current status "needs review".

PS: even though I can't find a relevant contributed project with status "abandonded" (in the list of modules I ever used), I doubt you get such "unsupported" message for contributed projects with such project status.

---
Tags: updating
---


title: Save a format for a node body

text:
# Question
Title: Save a format for a node body
How do I save the format used for a node body?

I am using the following code, but it doesn't work.

```
$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->set('body', "My body...");
$article->setPublished(TRUE);
$article->body->format = 'full_html';
$article->save();

```

How can I achieve this?

EDIT:

Fixed:

Right code:

```
$article = Node::create(array('type' => 'article'));
$article->setTitle($node->title);
$article->body->value = $node->body;
$article->body->format = 'full_html';
$article->setPublished(TRUE);
$article->save();

```

# Answer
> 7 votes
// $node is supposed to be previously defined node object.

```
$article = Node::create(array(
  'type'     => 'article',
  'langcode' => 'en,
  'title'    => $node->title->value,
  'body'     => ['value' => $node->body->value, 'format' => 'full_html'],
  'status'   => 1,
));
$article->save();

```

This is the code if in case, anyone wants it.

# Answer
> 2 votes
You left out `->value`: it should be `$article->setTitle($node->title->value);` but also `$node->body->value` I think. This likely throws an exception as a result and then something it eats it up so you don't get an error but it's not working indeed.

# Answer
> 1 votes
For an existing node, you can set the `body` with `format` simply as follows:

```
$node->body = array('format' => 'full_html', 'value' => $body);
$node->save();

```

---
Tags: nodes, 8
---


# Question
Title: How can I restrict user access to view nodes based on field value?
I am setting up a relatively simple website using Drupal 8. There are several different content types. Within each content type I would like some content to be available to anonymous users and some only available to authenticated users (i.e. 'member only' content).

I would like to add a simple tick box field that would control whether the content was publicly available or not. i.e. if the field is ticked then it is available to anyone but if it isn't ticked then it is only available to members.

I have managed to get some way to achieving this by using Node View Permissions and creating a duplicate of each content type - both have the same fields but one is visible to anonymous users and the other is only visible to authenticated users. This works, but isn't very satisfactory because it requires duplicate content types. I would prefer to have a single content type with a field that controls view permissions.

Do you have any suggestions?

# Answer
> 2 votes
After further research I opted for the following approach.

* Install Taxonomy Access Control Lite
* Create a new vocabulary in taxonomy - e.g. 'Access control'
* Create a new term in this vocabulary - e.g. 'Member only'
* Configure Taxonomy Access Control Lite to make content tagged with this term viewable to the roles you want (e.g. authenticated users)
* Add a taxonomy field with this vocabulary to each content type that you want to restrict access to

After following these steps I have a simple select field called 'Access control' which can be set to ' - None - ' or 'Member only'. The content will be displayed publicly or only to members depending on the option chosen.

**Notes**

1. I looked at another module that works in a similar way: Permissions by Term. This looks like a good alternative.
2. I opted to display the 'Access control' field as a select list as I only needed one selection. It would be easy enough to use tick boxes instead if you allowed multiple selections for this field.

# Answer
> 6 votes
You could use a programmatically solution using `hook_node_access()`, in this example the `field_YOURFIELD` is a checkbox.

```
/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  $access = new \Drupal\Core\Access\AccessResultNeutral();
  if ($node->hasField('field_YOURFIELD')) {
    $field = $node->get('field_YOURFIELD')->getString();
    if (empty($field) && $account->id() != $node->getOwnerId()) {
      $access = new \Drupal\Core\Access\AccessResultForbidden();
    }
  }
  $access->addCacheableDependency($field);
  $access->addCacheableDependency($node);
  return $access;
}

```

# Answer
> 2 votes
There are a few options.

If it's really just that checkbox and won't get more complicated over time and writing code is an option, then you can write a custom views filter plugin that only adds a condition if the user is not a member.

Such a plugin would do something like this in the query method and extend from the one that is used by default, and then you use hook\_views\_data\_alter() to use your plugin on your field instead of that one, or add your own views data definition.

```
/**
 * {@inheritdoc}
 */
public function query() {
  // Only add the condition if the current user is not authenticated.
  if (\Drupal::currentUser()->isAnonymous()) {
    parent::query();
  }
}

```

The other option is to rely on a node access module like https://www.drupal.org/project/content\_access. That has a development release for Drupal 8, I'm not sure how usable it is already. There might also be alternative modules that do something, or you can implement one yourself. Drupal core has a fairly simple node\_access\_test test module that makes nodes private based on a "private" field, you could base yours on that.

---
Tags: 8, users
---


# Question
Title: Taxonomy term via Rest API returns 406 Not Acceptable
I can't get the Taxonomy terms to work with the Rest API. I've used the Rest UI module to enable the Taxonomy Term for the Rest API, and enabled all formats.

When I request http://www.domain.com/taxonomy/term/1?\_format=json though, I get the message:

```
{"message":"Not acceptable format: json"}

```

Same for for hal and xml. Everything works fine for nodes, so I suspect a bug somewhere. Using 8.2.6 .

# Answer
> 1 votes
This works as expected using Drupal 8.3.x using latest Rest UI **Mar 28, 2017**.

Note I have tested as admin and anonymous with same results. Enabling HAL and requesting the formats **xml** and **hal\_json** gave the expected results too.

Disabling cookie request and enable basic\_auth give a different response.

> {"message":"The used authentication method is not allowed on this route."}

Hope this helps.

# Answer
> 1 votes
Im having this issue but with nodes, not with Taxonomy terms. Im trying to get the json of a node by doing http://localhost/mysite/node/1?\_format=json

However all i get is {"message":"Not acceptable format: json"} Event thou i configured the REST resources like this:

When i try with taxonomy term it works, just like described on Clemens Comment. However nodes still give me the Not acceptable format issue. Is there any configuration im missing to make the nodes endpoints work?

# Answer
> 1 votes
This could be the url pattern **/taxonomy/term/%**, which is same in views and Rest api.

When you check the request object, it has the controller **ViewPageController::handle**, where as in deleting nodes, the request goes through **RequestHandler::handle** which is from the REST module.

I have checked the views page for taxonomy views and found the a page with the same url pattern /taxonomy/term/%. Just tried disabling this view and hit the API, and checked the request, which now calls the **RequestHandler** controller.

The issue is with same url pattern provided in Views page and the REST API, As the url pattern is already registered in views, the api call doesn't work.

So try to disable the taxonomy view and hit the api again.

Check this at drupal.org

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


# Question
Title: How to use custom block view mode in View?
We have a custom block type block\_countries and we are using a View(my\_view\_custom) to display the all the blocks where type = block\_countries. Under block\_countries view mode, we setup a "Full" view mode where we display certain information.

The view is displayed as a block and placed into a region (i.e. content region) from the theme. We want to style the block\_countries "Full" view mode and setup a preprocess hook to do some processing, however we cannot find the way to do this.

We need help figuring out the proper twig template and preprocess\_hook to call in order to get the desired out below. How can we do this?

Block type fields (block\_countries):

1. body
2. language
3. country (Entity reference: taxonomy term)

Full view mode (fields shown):

1. body
2. country

View settings:

1. Format = unformatted list
2. show: custom block: Full (where full is the view mode)
3. Filter Criteria: custom block : block type = block\_countries

We have tried the following but they do not work

Twig

```
views-view-unformatted--my-view-custom--block-1.html.twig

```

Hooks

```
mytheme_preprocess_views_view(&$vars)
mytheme_preprocess_views_view__my_view_custom(&$vars)

```

Desired output (per row returned from view):

```
<div data-country="{{ country }}"> {{ body }} </div>

```

# Answer
> 0 votes
Don't use custom blocks, use nodes or a custom entity type. Custom blocks are designed to be displayed as a block, not a view inside a block. They don't have a template on their own. See https://www.drupal.org/node/2704331.

Yes, it's not great, but it is unlikely that this will change any time soon.

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


# Question
Title: How to trigger an Action on an Entity from a button in a Views row (without VBO)?
I know actions can be done with Views Bulk Operations (VBO), but I just want a button in each row of a view of entities. When I press the button, the action is executed for that entity.

# Answer
> 1 votes
What you're asking for is perfectly possible using the Rules Link module (no need for VBO). Some details about this module (from its project page):

> *Features*: ... The links are usually displayed using Views...
>
> *Usages*: ... The Rules Link module will create a Views field for each link, which can be hidden, using the visibility conditions ...

However, assuming you're familiar with the basics of Views, it isn't obvious at first about how to actually add such extra column. The clue to get it to work, can be found in this part of the module's README.txt:

> Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

### Example

Below is a list (= Views result) of "All blocked/active users" shown to a user with role Administrator:

```
User name      Active  Created date        Last login
Hillary.Trump  No      06/18/2016 - 13:45                      Unblock user
Donald.Clinton No      06/18/2016 - 13:42                      Unblock user
Someone.Else   Yes     05/12/2016 - 12:09  09/17/2017 - 11:18
Pierre.Vriens  Yes     03/11/2016 - 21:05  10/06/2017 - 16:04
Dries.Buytaert Yes     11/23/2015 - 10:11  09/17/2017 - 10:38
Anonymous      No

```

Note the extra column added (to the right), with links labeled `Unblock user` which are only shown for the blocked users, and not for Anonymous. After using (clicking) that link, for some user with `Active=No`, the user's status becomes `Active` (an example of "*an action triggered on a user entity*", as in your question), and the link is no longer shown for that user. If you wonder how to create such extra column (using Rules Link), refer to my answer to "How to show authorized users a link for relevant Views results using the Rules Link module?". Obviously, transforming such link into a button is just a matter of some (basic) CSS to be applied to that link.

# Answer
> 0 votes
You could do this by writing a custom module:

The Button Field module also looks like it could help you do what you want: https://drupal.org/project/button\_field

---
Tags: 7, views, actions
---


title: How do I execute stored procedures?

text:
# Question
Title: How do I execute stored procedures?
I have a website which does lot of work on financial data. It involves operations on large volumes of data most of the time. Hence I find it useful to do those operations in MySQL stored procedures. I have stored procedures in my database. I want to know how can I execute stored procedures in Drupal? Is there any good method to execute stored procedures in Drupal? How does Drupal handle stored procedures in general? Or we just have to use the PHP to execute stored procedures?

# Answer
> 12 votes
Assuming you're using Drupal 7 you can use code like the following:

```
// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// Prepare the statement and bind params
$statement = $conn->prepare("Call GetNodeList(?,?)");

$op_status = $statement->bindParam(1, $node_type, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 25);
$op_status = $statement->bindParam(2, $publish_state, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT);

// Execute the statement and reset the connection's statement class to the original.
$exec_result = $statement->execute();
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);

// Get your data
while ($row = $statement->fetchColumn(0)) {
  // ...
}

```

That method is completely culled from this article and has worked for me well in the past.

# Answer
> 1 votes
Not sure whether this is the correct way to this, but it worked for me. I have a legacy system which shares the same Postgres database server that Drupal does.

In a submit handler I needed to send data to this legacy system which had a stored procedure (Postgres calls them functions) to handle the data:

```
// Get legacy database connection set-up in settings.php
Database::getConnection('default', 'legacy')
  ->query('SELECT * FROM stored_procedure(:named_parameter_1, :named_parameter_2, ...);', [
    ':named_parameter_1' => $value_1,
    ':named_parameter_1' => $value_2,
    ...
  ]);

```

This got the data successfully into my legacy system

---
Tags: database
---


# Question
Title: How do I create a route that opens an external file?
How do I create a route that opens an external file?

As an example I have an XML file in my S3 bucket. I need to create a route to open that file from my website.

Is there a way to achieve this without calling a controller? Can I just set a property in the .routing.yml file for this?

```
my_module.index:
path: '/file.xml'
defaults:
  _controller: 'Drupal\my_module\Controller\moduleController::view'
  _title: 'file View'
requirements:
  _permission: 'access content'

```

# Answer
> 1 votes
> Is there a way to achieve this without calling a controller from the route file?

No, a route needs a controller, no exceptions. If you can find an existing controller/method that does what you need, reliably, then you should use that. If not, you'll need your own controller and method.

---
Tags: 8, routes
---


title: altering user_admin_account form

text:
# Question
Title: altering user_admin_account form
I am working to change the standard display when pressing the "People" button. Instead of showing "Username" I want it to show a custom field. For example "Last name".

I almost made it work, but the pager is not working. When I click page 2, the same info shows as page 1. Sorting is working though.

Here's the slightly changed code, which originated from the core user module.

```
<?php
function user_custom_form_user_admin_account_alter(&$form, &$form_state, $form_id) {

  $header = array(
    'field_lastname_value' => array('data' => t('Username'), 'field' => 'dn.field_lastname_value', 'sort' => 'asc'),
    'status' => array('data' => t('Status'), 'field' => 'u.status'),
    'roles' => array('data' => t('Roles')),
    'member_for' => array('data' => t('Member for'), 'field' => 'u.created'),
    'access' => array('data' => t('Last access'), 'field' => 'u.access'),
    'operations' => array('data' => t('Operations')),
  );

  $query = db_select('users', 'u');
  $query->condition('u.uid', 0, '<>');
  $query->leftJoin('field_data_field_lastname', 'dn', 'u.uid = dn.entity_id');
  user_build_filter_query($query);

  $count_query = clone $query;
  $count_query->addExpression('COUNT(dn.entity_id)');    // or u.uid, does not make any diff.

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u', array('uid', 'name', 'status', 'created', 'access'))
    ->fields('dn', array('field_lastname_value'))
    ->limit(20)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

...

    $account->name = $account->field_lastname_value;
    $options[$account->uid] = array(
      'field_lastname_value' => theme('username', array('account' => $account)),
      'status' =>  $status[$account->status],
      'roles' => theme('item_list', array('items' => $users_roles)),
      'member_for' => format_interval(REQUEST_TIME - $account->created),
      'access' =>  $account->access ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $account->access))) : t('never'),
      'operations' => array('data' => array('#type' => 'link', '#title' => t('edit'), '#href' => "user/$account->uid/edit", '#options' => array('query' => $destination))),
    );

      ...
}
        ?>

```

Can anyone help? I have been struggling with this for hours. I did try changing the position of pagerDefault and TableSort to all kind of possible places like in the beginning before the join, after the join, tried with other joins then just left join, I'm stuck. Maybe I have to call SELECT FROM the custom field table and join the users table? But that's odd. Any help is really appreciated.

# Answer
You can use Administration Views module which will allow you to work with that table as a View.

This means you can add fields, reorder them as you want and add custom filters for example.

User fields are supported out of the box, so you should be able to do what you want without any code.

It's much more flexible than altering the form, especially if you need some other custom functionality to it later on.
> 2 votes

# Answer
I faced a similar issue while adding a new field 'Mail' in the 'user\_admin\_account' form.

During my search I came across this post & also this post 'https://drupal.org/node/1899708' which address the same issue. I got a solution for this as described below:

```

/**
 * Implements hook_form_FORMID_alter()
 * @param $form
 * @param $form_state
 * @param $form_id
 * @return $form
 */
function CUSTOMMODULE_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  // Adding User Mail Field in the 'user_admin_account' form
  $mail_header = array(
    'mail' => array('data' => t('Mail'), 'field' => 'u.mail'),
  );
  // Placing Mail at 2nd position
  array_splice($form['accounts']['#header'], 1, 0, $mail_header);

  foreach($form['accounts']['#options'] as $key =>$value){
       $query = db_select('users', 'u')
        ->fields('u', array('mail'))
        ->condition('u.uid', $key)
        ->execute()
    ->fetchAssoc();

    array_unshift($form['accounts']['#options'][$key], $query['mail']);
  }

  $form['pager'] = array('#markup' => theme('pager'));

  return $form;
}

```

Although this post dates back in '11, but as i did not get any solution based on my search so considered to post this answer. Hope it helps.
> 2 votes

# Answer
To answered Oct 7 '13 at 12:49 of dhrubaj

Is need to do like that:

`$form['pager'] = array('#markup' => theme('pager', array('element' => 1)));`

where 1 from `'element' => 1` is the number of needed pager from page, in that case we have two pager first (0) from `user_admin_account` (it exists in pager array) form and second our pager(1) from form `user_custom_form_user_admin_account_alter`.

Without `'element' => 1` `theme('pager')` render first pager that have limit 50 pages and we have some users and pager not show.

To see all pagers use:

```
 global $pager_page_array, $pager_total;
 var_dump($pager_page_array, $pager_total);

```
> 1 votes

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


title: Cannot use the alias "/libraries"

text:
# Question
Title: Cannot use the alias "/libraries"
I am trying to make a node have the alias "/libraries" but I get a Page Not Found error which looks to be returned before Drupal has fully bootstrapped (I don't get the usual Drupal 404).

I checked a few other sites and they seem to have the same issue. Is there some reason why I cannot use this alias in Drupal? Would it have anything to do with a "libraries" folder in the root of the project?

Edit: It *does* appear to be because I have a "libraries" directory in the docroot which contain various JS libraries for CKEditor and other modules that need them.

So what is the fix here? I assume if I change the directory to anything else, those plugin paths will break. I could add Libraries API maybe, but I don't know the status of that module, but it still means any module that has a `libraries.yml` file that looks for `/libraries..../file.js` still won't work.

In this actual case, `/libraries` is a View (or could wind up being a node with a View block on it) that lists all libraries in the system, and thats what I want the URL to be.

# Answer
> 1 votes
For anyone looking in the future, this will solve it.

Add this to your htaccess file:

```
# Allow the alias "/libraries" to work without breaking actual assets in the libraries directory.
RewriteRule ^libraries$ /index.php [L]

```

Just before this block:

```
  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

```

I also had to add an `.htaccess` file to the libraries directory. Inside of that, I had to do:

```
DirectoryIndex ../index.php
DirectorySlash off

```

Now I can create an alias for `/libraries` and not introduce and endless redirect loop, and physical assets (CKEditor plugins) can still be loaded correctly from this directory.

---
Tags: 8, path-aliases, uri
---


title: How to customize welcome email

text:
# Question
Title: How to customize welcome email
Could anyone show me how to customize welcome email in Drupal 8, as I spend a lot of time trying to get it done.

I've already tried in Back Office but Drupal seems to ignore it totally.

# Answer
Navigate to /admin/config/people/accounts and scroll to the bottom.
> 4 votes

# Answer
Go to `admin/config/people/accounts` and scroll to the bottom:
> 4 votes

# Answer
we had a simliar issue with Drupal showing always default email. Despite the fact we overrided the Welcome (no approval required) input field.

After a lot of research, we found out we had a database issue, there was an additional collection (language.fr) when actually France was the default language (then there is no sense language.fr collection to be there, as default language doesn't have collection data)

Our solution, was to remove french language (was our default language) and add it back again (please do a backup first).
> 2 votes

---
Tags: 8, users
---


# Question
Title: What is the best way to overwrite a node display with a view
I would like to know what is the best way display a view instead of the content page. This is to have the versatility of views when showing fields instead of the traditional view mode. My current setup is:

1. Use Panelizar to manage node display
2. Create a view block with the node id as contextual filters
3. Add this block to the panelized panel

My question is: is there a better way? Maybe one that does not require an external module?

Thanks

# Answer
> 1 votes
I think the Drupally way to replace node content with a views block would be to hide the fields via the Display Settings, add the fields to your views block, display the views block on the node.

If you cannot hide the fields on this content type, I would suggest creating a content type for this type of page and use case.

My personal vote, if you need truly "re-arrangeable" content, would be to start using Paragraphs.

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

I offer this as an answer because I feel that while things like 301 redirects, NID template overrides, or even hook alters might get the job done, they may be a little hacky for a content situation.

Paragraphs allow you to create re-useable pieces of content with as many or as little fields in each as you'd like. And by far Paragraphs has been the best content experience I've had in Drupal.

---
Tags: views, 8
---


# Question
Title: How to display custom text for entity reference field, depending on vocabulary term.
This must be simple, but I can't find how to do it ..

Say I have a custom content type of 'staff' which, among other, has an entity reference field linked to a taxonomy vocabulary which has the terms: 'type A', 'type B', 'type C'.

How can I display some custom text according to which term the content type belongs to?

for example, if 'John Doe' of content type 'staff' belongs to 'type A', I want that field to be displayed as 'Director' and not 'type A'.

I don't want custom text for each individual, I would like to display 'Director' for *all* 'type A' staff, 'Manager' for *all* 'type B' staff and 'Administration' for *all* 'type C' staff..

I would prefer to solve this via core modules and not touching code, if possible. If not possible, then is there a lightweight module to achieve this?

thanks.

# Answer
Change the text of your terms to the actual text you want to display. "Type A" should be "Director". Then just show that field on the content type via the Display Settings.

or

Add fields to your taxonomy terms. Add a field such as "Staff Position" and then print that field in your template file

```
{{ node.field_reference.entity.field_staff_position.0.value }}

```
> 0 votes

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


title: A redirect doesn't work in user form

text:
# Question
Title: A redirect doesn't work in user form
The project it's in Drupal 8.2

Hello, when a user fill the profile and Save ( /user/id/edit) the page it's reloaded with the new data in the same url, but I want to redirect the user to /user/id

This code should work:

```
function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_state->setRedirect('user.page');
}

```

But it doesn't work, any idea what's going on?

Thanks

# Answer
You can not set a redirect directly in the form alter. Submit callbacks are responsible for setting a redirect. You need to add a submit callback on the button after the default one and then set the redirect there.
> 2 votes

# Answer
You need to add a new submit handler to the form:

```
function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'custom_user_submit_handler';
}

```

Inside the new submit handler set the redirect:

```
function custom_user_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form_state->setRedirect('user.page');
}

```
> 3 votes

# Answer
In this case this is the correct code to make it works.

```
/**
 * Implement hook_form_id_alter()
 */
function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][]= 'custom_user_custom_submit_handler';
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function custom_user_custom_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_state->setRedirect('user.page');
}

```

Thanks to Berdir and Colin by their helps.
> 0 votes

---
Tags: 8
---


# Question
Title: Can't seem to load CSS in a custom theme
I'm working on trying to add CSS to a custom theme, and it seems my logic is failing somewhere.

I'm adding simple css files in the .libraries.yml on the root of the theme (only thing in them right now is forcing a background color on the body) and not one of the css files is loading.

Where does my logic fail here?

This is in Drupal 8

# Answer
Ensure you have a call to your library in your .info.yml

```
libraries:
 - pixelcircus/global

```
> 0 votes

---
Tags: 8, theming
---


# Question
Title: Group entitiy queries for a specific content type using Taxonomy Term
Using Drupal 8 entity query I'm trying to figure how I can fetch values from a specific content type and group them that are associated via a specific taxonomy term.

As seen in the screenshot below I have an entity field called `Group Schedule` that is currently binded to a Taxonomy Term. Is there way I could group those entities that are assigned to a specific taxonomy?

```
Group Schedule Name (field_group_sched)
First Schedule (field_created_date)
Second Schedule (field_created_date)

Group Schedule Name 2 (field_group_sched)
First Schedule (field_created_date)
Second Schedule (field_created_date)

```

So far I've managed to fetch the values from the `Schedule` Content type

```
// Entity Query for Schedule Node Type
$scheduleType = $query->get('node')
    ->condition('status', 1, '=')
    ->condition('type', 'schedule')
    ->condition('field_associated_programs', $nid_degree, '=')
    ->sort('created')
    ->execute();

foreach ($scheduleType as $key => $program) {

    $programNode = _nodeLoad($program);

    $variables['schedule_content'][$key]['schedule_group'] = $programNode->get('field_group_sched')->value;
    $variables['schedule_content'][$key]['schedule_name'] = $programNode->get('field_schedule_name')->value;
    $variables['schedule_content'][$key]['schedule_date'] = $programNode->get('field_created_date')->value;

}

```

---

```
{% for program in schedule_content %}

<div class="scheduled-dates">
    <h3 class="label">{{ program['schedule_group'] }}</h3>
    <span data-label="{{ program['schedule_name'] }}"  class="date" >{{ program['schedule_date'] }}</span>
    </div>

{% endfor %}

```

# Answer
Ok well here we go if i understand you correct you want nodes linked by a entity reff field value: in your example "field\_group\_sched" the see the below condition but later you can just group stuff by anything you want

```
   // this is the known term id.
    $group_term_id = 1;
    // for Entity ref use field_name.target_id
    $query = \Drupal::entityQuery('node')
      ->condition('status', 1, '=')
      ->condition('type', 'schedule')
      ->condition('field_group_sched.target_id', $group_term_id, '=')
      ->sort('created');

    $entity_ids = $query->execute();
    if (count($entity_ids) != 0) {
      $entities = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadMultiple($entity_ids);
      // dump($entities); // requires var dummper
      if (count($entities) != 0) {
        $group1 = [];
        $group2 = [];
        // then you can play with order or whatever you want here.
        foreach ($entities as $node) {
          // These are the loaded nodes;
          $title = $node->getTitle();
          $field_name  = $node->field_schedule_name->value;
          // if the schedule_name is "beer" put in to group 1
          if ($field_name == 'beer') {
            $group1[] = $node;
          }
          else {
            $group2[]= $node;
          }
        }
        // SEND your Nodes to the template here.
      }
    }

```
> 1 votes

---
Tags: entities, database
---


# Question
Title: How to turn fieldset to normal field for date field
I have a date field that is rendered in a fieldset unfortunatelly. I would like to render it as normal field. I found this for drupal 7 how to avoid fieldset in drupal date field

How can this be done in drupal 8?

# Answer
> 1 votes
Drupal 8 core date field looks like this ....

perhaps your theme is overriding this field type like boostrap or some thing if that is the case find the template file move to your sub theme and change it back to normal.

UPDATE:

But If you are using the Select Widget You have some options:

1) Make css to fix the look of it, a good fast option all you need to do is find the field ID then change the rules for that id only. if not using a custom theme you will need a form alter and attach a custom css library.

2) Override the Field set template if you turn on theme debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates) and inspect the element will see the templates that the field uses, you can copy them in to your theme and override them, or create your own theme hooks see my example of hook\_theme\_suggestions\_HOOK\_alter on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook\_theme\_suggestions\_HOOK\_alter/8.2.x

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


title: Render block in twig file drupal 8

text:
# Question
Title: Render block in twig file drupal 8
I have created a block in custom block library, i need to render the block on all pages except home page.

Unfortunately I need to do it in twig file only because of ui issues if I enabled in the block layout UI

In twig file how can I render the block in drupal 8.

Thanks

# Answer
> 1 votes
Add following code in "themename.theme"

```
function themename_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('block_id');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
 $variables['your_block_name'] = $block_content;
}

```

in twig template file use following variable

```
{{ your_block_name }}

```

---
Tags: blocks
---


# Question
Title: How to troubleshoot an Ajax HTTP Result Code 200 Error?`
I am receiving the following Ajax error when on any Views page. The Drupal logs (/admin/reports/dblog) don't have any corresponding events. I've tried disabling all custom and view related modules and adjusting jQuery versions with no success.

I'm running Drupal 7.57-dev and Views 7.x-3.18

I know there are several other questions about this error but their solutions are specific or not relevant to this specific response text.

How do I begin drupal shooting this error?

# Answer
> 3 votes
The `<?php` tag at the beginning of the ResponseText indicates that there is a stray `<?php` in the markup, this was being caused by a syntax error in a completely unrelated template. After template syntax error was fixed the Ajax Http 200 error pop-up went away.

# Answer
> 1 votes
I have the same problem with BOM, I just :

> grep -rl $'\xEF\xBB\xBF' .

And correct it with phpstorm :

> File \> Remove BOM

---
Tags: 7, views, ajax
---


# Question
Title: How to mass update recurring date rules?
I would like users to be able to mass update recurring date rules possibly using VBO and Rule sets.

For example: user would like to add "exclude date = 01/01/2012" recurring date rule for all selected nodes' dates where date is a new field added to a content type.

How to do this ?

---=EDIT=---

I have already build a basic Rule with the following code:

```
{ "rules_change_end_date_for_selected_content" : {
    "LABEL" : "Change end date for selected content(s) (Test rule)",
    "PLUGIN" : "rule",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Content", "type" : "node" },
      "event_end_date" : { "label" : "Event End Date", "type" : "date" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_event_date" } },
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "event" : "event" } } } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-event-date:0:value2" ],
          "value" : [ "event-end-date" ]
        }
      },
      { "entity_save" : { "data" : [ "node" ] } }
    ]
  }
}

```

What should I put instead of `node:field-event-date:0:value2` to modify the date rule end date ( not the first date enddate). I would like to change the date until this node repeats but I cannot see tokens for the date repeating rule.

# Answer
> 1 votes
This sounds like it will need a custom module, However have you tried the bulk update module?, you could extend this and adapt it for dates, I do not have any code examples, as it does sound quite complex.

# Answer
> 1 votes
Take a look at the Date Repeat Entity module. Module features, see item 2 specifically for your needs:

> * Attach unique content to each date in a recurring series
> * Update current, future or all recurring dates
> * Delete current, future or all recurring dates
> * Configuration per bundle (content type)
> * Provides warnings when updates may affect referenced content
> * Includes hooks for additional control of what gets repeated and when

I personally just started using this module, it's fantastic.

# Answer
> 0 votes
In your case, the crucial part of a working rule is a Rules Action to perform a **Loop** (to replace your first Rules Action to "Set a data value"). If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) have a Rules Action to create a loop related to your `node:field-event-date` field (as shown in the rule included in your question). After you do, you should iterate over each item in that list. And for each iteration you should then perform a Rules Action to "Set a data value for the list item being processed in the loop", and set that value to your Rules Component parameter `event_end_date`.

***Done***

PS: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

---
Tags: 7, rules, datetime, views
---


title: Drupal 8 Hide Title If Front Page

text:
# Question
Title: Drupal 8 Hide Title If Front Page
In drupal 8 how can I hide title on front page ? The title is rendered through page-title.html.twig through the code below

```
{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

```

I want to wrap it in **if not front page** condition but don't know the syntax.

# Answer
For this you can use the is\_front variable

```
{% if not is_front %}your code{% endif %}

```
> 4 votes

# Answer
The title is displayed in a block. Go to the block layout (/admin/structure/block), look for the block "Page Title", click on "Configure" and set the visibility on "Pages" to hide for `<front>`:
> 8 votes

---
Tags: 8, theming
---


title: Hundreds of unserialize requests

text:
# Question
Title: Hundreds of unserialize requests
I have a large Drupal 7 website on my hands that is very large and has loads of modules (over 200). I am already seeing poor performance symptoms in the FPM logs with max\_children limits reached on the Acquia server. I installed a profiler (blackfire) and the main issue (on every page) is an absurd amount of calls to unserialize (over 300) coming from DrupalDatabaseCacheprepareItem (autenticated). This happens even on a basic page. I am having a tough time coming up with a solid strategy to pinpoint the bottleneck and which module(s) are the culprit.

Anyone can help me with this?

# Answer
> 0 votes
I ended up using the variable debug module, which was incredibly useful in helping me find out the expensive variables I had.

---
Tags: 7, caching, performance
---


# Question
Title: how to apply language detection for the standard search page result?
I manage an intranet in french and dutch. I do not know how to apply language detection from the result page search/node. I mean I have a result page with both language references and I would like to apply the filter related to language detection and I do not find how ?? Should I use a module or other stuff like search API or Search API Solr Search ?

# Answer
You may want to have a look to the custom\_search module. It allows to customize additional search parameters and also to expose the language of the content to be searched.
> 0 votes

# Answer
Thank you, I will try the custom\_search module. I was just following a training from webwash.net about search API. My goal is to encounter all my employer's needs and I have to follow a lot of trainings. So, Thanks to webwash.net and udemy.com I found the solution.

We have to install search API thanks to which we can create a server and an index that we can thinly configure. But my goal is to set the detection language function for a result page, and I found the solution with the related search API view "/search/content" where I set the filter in question AND it works !!! I have a french result page for the french interface, and I have a dutch result page for the dutch interface !
> 0 votes

---
Tags: search, i18n-l10n
---


title: Render key and value of a field

text:
# Question
Title: Render key and value of a field
I have a field (list integer) and I would like to render its keys and values. I found field.html.twig but within I only have access to item.content which is the value. I would also like to access the key. I also had a look to `theme_preprocess_field(&$variables)` but I'm not able to get the correct keys.

I tried

```
  foreach ($variables['items'] as $key => $item) {
    $variables['items'][ $key ]['key'] = $key;
  }

```

Unfortunatelly this only gives me the array positions 0,1,2 ... But I would like to have the actual keys from my list, i.e.

100|red 200|green 300|blue 400|black ...

# Answer
> 0 votes
Here is how you can get the list field key and value

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

    if ($variables['field_name'] == 'field_test') {

        foreach ($variables['items'] as $key => $item) {
            $list_field_value = $item['content']['#markup'];
            $list_field_key = $variables['element']['#items'][$key]->getString();
        }

    }

}

```

**Note:** replace `field_test` with the actual field machine name, **do not replace `field_name`.**

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


title: How to get the node status?

text:
# Question
Title: How to get the node status?
I have a function that returns sets of variables. Now, I want to control the return value by using node status. Basically I dont want the value to be returned when the node is unpublished. Any idea? Here is the function by the way. I just need to add a condition in the return value like this `if($node->status == 1){ return $omniture_variables; }`

```
function my_module_omniture_variables() {
  $current_day = date('D');
  $current_hour = date('G');
  .....

  $omniture_variables['variables'] = array(
    ....
  );

  //Sets omniture variables
  if(module_exists('omniture')) {
  ....
  }

  if(count($extra_variables) > 0) {
    $omniture_variables['variables'] = array_merge($omniture_variables['variables'], $extra_variables);
  }

  return $omniture_variables;
}

```

# Answer
> 2 votes
To avoid a node\_load() you can do:

```
  $query = db_query("SELECT * FROM {node} WHERE nid = %d LIMIT 1", $number);
  $result = db_fetch_object($query);

```

and then look at $result-\>status.

# Answer
> 8 votes
Getting a node's status is quite simple:

```
// Get the node with node ID 123.
$node = node_load(123);
// Get its status.
$status = $node->status;

```

That said... I don't know what your function looks like or in which context it's running, so depending on your situation, there may be an even better way to get what you want.

# Answer
> 8 votes
For Drupal 8:

```
<?php

// Get status method
$status = $node->isPublished();

// Set status
node->setPublished(TRUE);

```

https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/function/Node%3A%3AisPublished/8.2.x

https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Entity%21Node.php/function/Node%3A%3AsetPublished/8.2.x

# Answer
> 2 votes
**Drupal 8 method for avoiding using node\_load:**

```
$bundle = $node->bundle(); // or $bundle='my_bundle_type';
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', $bundle); // Optional
$entity_ids = $query->execute();

```

# Answer
> 0 votes
Using the Drupal 7 Database API, you can get the status of a node to determine if it is published or not like this:

```
// Determine if the node is published or not.
$query = db_select('node', 'n')
  ->fields('n', array('status'))
  ->condition('n.nid', $nid)
  ->execute();
$result = $query->fetchObject();
$is_published = $result ? $result->status : FALSE;

if ($is_published) {
  // Take action...
}
else {
  // Relax...
}

```

---
Tags: nodes
---


# Question
Title: How do I add path exception in Redirect and Fast 404 modules?
I have a module which has dynamic paths (e.g. /mymodule/one/file1/a.png, /mymodule/one/two/three, /mymodule/one/two/three/four/b.js), where the number of path parameters are resolved by a class implementing the `InboundPathprocessor` interface. mymodule is present in all the paths.

I want the *Redirect* and the *Fast 404* module to ignore paths with "mymodule" in it.

# Answer
Using an OutBoundPathProcessor and reversing the path logic in it worked for me
> -1 votes

---
Tags: redirection
---


# Question
Title: Error when get rest resource : The controller result claims to be providing relevant cache metadata
I try to create a REST resource. I used EntityResource as base. I would like to return my fields in html. Here is a exemple of my code :

```
public function get($id) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    $entity = \Drupal::entityTypeManager()->getStorage('node')->load($id);
    $entity_access = $entity->access('view', NULL, TRUE);
    if (!$entity_access->isAllowed()) {
      throw new AccessDeniedHttpException($entity_access->getReason() ? : $this->generateFallbackAccessDeniedMessage($entity, 'view'));
    }

    $result = array();
    $other_entity_dependency = array();
    if ($entity instanceof FieldableEntityInterface) {
      $fields = array();
      $contentType = $entity->bundle();
      if (isset($contentType) && !empty($contentType)) {
        foreach (\Drupal::entityManager()->getFieldDefinitions('node', $contentType) as $field_name => $field_definition) {
          if (!empty($field_definition->getTargetBundle())) {
            $fields[] = $field_name;
          }
        }
      }
      foreach ($fields as $field_name) {
        $field = $entity->$field_name;
        $field_access = $field->access('view', NULL, TRUE);
        if ($field_access->isAllowed()) {
           $value = \Drupal::service('renderer')->render($field->view())
           $result[$field_name]['value'] = $value;
            $result[$field_name]['label'] = $field->getFieldDefinition()->getLabel();

        }
      }
    }

    $response = new ResourceResponse($result, Response::HTTP_OK);
    $response->addCacheableDependency($entity);
    $response->addCacheableDependency($entity_access);

      return $response;
  }

```

The problem is that when I use a render function, I have this error :

> The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\rest\ResourceResponse.

I haven't this issue when I use `$field->value` instead of `\Drupal::service('renderer')->render($field->view())`, but I would like to have the html render of fields, for file or image too (these types of fields are empty when I use `$field->value`).

How can I solve this problem ?

# Answer
The problem is, that `render()` produces metadata which leaks to the outside of the controller. You can try `renderPlain()` if you don't care about the metadata or see this question how to provide your own render context to catch the metadata and add it to the response:

How to get cache metadata from nested render array when returning response?
> 0 votes

---
Tags: entities, caching, 8
---


# Question
Title: I can't backup my website on a shared server because memory runs out. What can I do?
I have a large Drupal7 website on a shared Hostgator server, and I cannot do automated backups because I always run out of resources.

I've tried 2 methods:

1) I first built my own CLI bash file and I set up a cron job to execute it every night. The cron job emails me the output, and it never finishes and it says it ran out of resources. It was to just save the backup to the same machine.

2) I installed the Backup and Migrate module for Drupal and set up an FTP account on a seperate server on a seperate network to send the backup to. When I try it, after a minute it goes to an Error 500 screen. There's an advanced option for choosing to use CLI tools (it says this is better for larger sites) but after several minutes it went to an Error 405: Not Allowed page.

Does anybody have any advice?

Thanks!

# Answer
According to this tutorial hostgator shared hosts can get ssh access so 2 of the solutions below assume ssh access ha been setup properly (the setup of ssh is beyond the scope of these forums)

This is also a general solution as most shared hosts nowadays have ssh access

# 1. using command line

```
# go to root directory
cd httpdocs

# dump database
mysqldump -u USERNAME -p'PASSWORD' DATABASENAME > database.sql

# zip the whole drupal directory
zip -9 -qr html.zip .

```

# 2. Using drush

**setup drush (done once)**

```
# get drush
wget http://files.drush.org/drush.phar;
# if above does not work go to and get the link to latest version .phar from
# https://github.com/drush-ops/drush/releases
# wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;

```

**using drush**

```
# after setting up drush
# go to root directory
cd httpdocs
# dump the database
drush sql-dump > database.sql
# zip the whole drupal directory
zip -9 -qr html.zip .

```

# 3. if no ssh present you will need to use cpanel, plesk or another control panel

**database backup (one of the following)**

* go into cpanel and find phpmyadmin go into your database and start the `export` process
* some panels will have under `databases` a way to backup a database without getting into phpmyadmin

**files backup**

* go into file manager and find the root directory (public\_html or httpdocs) and zip the folder

# Notes

More on drupal backup

If memory runs out on any of the previous solutions perhaps you ought to upgrade your plan or move to a vps/dedicated/cloud hosting solution

if none of the above works and the support is not willing to help you set a way to backup your site get out of that host they are not worth the money that you spend
> 4 votes

---
Tags: backups
---


# Question
Title: How to add View Translated Version button in Views?
My site is multilingual and I have a view page of content type. If node has translation then I want to add a button/link for viewing the translation.

```
Example

View Row 1
Title 1
Body 1
View in English | View in Arabic

View Row 2
Title 2
Body 2
View Full Content

View Row 3
Title 3
Body 3
View in English | View in Arabic

```

# Answer
> 1 votes
You can add filter 'Translation Language' in view which can be exposed for user to select the language.

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


title: Configuring Kaltura module in drupal 7

text:
# Question
Title: Configuring Kaltura module in drupal 7
I am trying to configure the Kaltura module in Drupal 7. If I try adding the partner ID, email ID, and password (which I have received from Kaltura's website), it gives me the following error:

> Class 'KalturaUser' not found

I also added the library but it's not working. Could anyone tell me how to configure the Kaltura module?

# Answer
> 0 votes
According to Kaltura module documentation here http://cgit.drupalcode.org/kaltura/plain/README.txt?h=7.x-3.2

You should download the php version of API from here (http://cdnbakmi.kaltura.com/content/clientlibs/php5\_16-12-2014.tar.gz) and place it under DRUPAL\_ROOT/sites/all/libraries/KalturaClient directory.

Note: The directory name is case-sensitive.

Alternatively you can use drush for this.Here is a command for drush.

```
    Drush kaltura-client-install

```

---
Tags: installation
---


title: Top 10 Commenters this Month

text:
# Question
Title: Top 10 Commenters this Month
We are trying to set up a view that shows a list of top commenters. Played around with views but we can't figure it out.

Basically, aggregate all the comments left by each user let say this month.

Then list the usernames in descending order and also show the total number of comments of each user. Next to username for example.

Anyone has ideas on how to do this?

# Answer
Take a look at this question. They're doing nearly the same thing but with nodes authored by the user.

After that, you just need to limit the view to 10 results.
> 1 votes

---
Tags: views, users
---


# Question
Title: How to alter the welcome message after successfull registration
A message is shown upon successful registration, with the following contents:

> A welcome message with further instructions has been sent to your e-mail address

I would like to change the content of that message and use a different HTML structure, e.g.:

```
 <p>Thanks for registering</p>
 <a href="#">continue</a>

```

How can I do that?

# Answer
you can achive this and much more similar things with LoginToboggan module, from module page:

> The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements: Allow users to login using either their username OR their e-mail address. Allow users to login immediately. Provide a login form on Access Denied pages for non-logged-in (anonymous) users. The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login. Customize the registration form with two e-mail fields to ensure accuracy. Optionally redirect the user to a specific page when using the 'immediate login' feature. Optionally redirect the user to a specific page upon validation of their e-mail address. Optionally display a user message indicating a successful login. Optionally combine both the login and registration form on one page. Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!). Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)

UI settings are simple and straight forward, and are located in admin/config/people/accounts
> 0 votes

---
Tags: 7
---


# Question
Title: Fatal Error HtmlRouteProvider not found?
> Fatal Error: Fatal error: Class 'Drupal\custom\_avatar\CustomAvatarHtmlRouteProvider' not found in /Sites/drupal8/core/lib/Drupal/Core/Entity/EntityTypeManager.php on line 252

I am creating config Entity type and below is structure of my module shown in screenshot:

I below code I have defined below routing so that I don't have to define each of these routes statically in our module's routing.yml file. My class extends AdminHtmlRouteProvider :

> "route\_provider" = { "html" = "Drupal\custom\_avatar\CustomAvatarHtmlRouteProvider", },

```
<?php

namespace Drupal\custom_avatar\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;

/**
 * Defines the Avatar profile entity.
 *
 * @ConfigEntityType(
 *   id = "custom_avatar",
 *   label = @Translation("Avatars for user profiles"),
 *   handlers = {
 *     "list_builder" = "Drupal\custom_avatar\CustomAvatarListBuilder",
 *     "form" = {
 *       "add" = "Drupal\custom_avatar\Form\CustomAvatarForm",
 *       "edit" = "Drupal\custom_avatar\Form\CustomAvatarForm",
 *       "delete" = "Drupal\custom_avatar\Form\CustomAvatarFormDeleteForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\custom_avatar\CustomAvatarHtmlRouteProvider",
 *     },
 *   },
 *   config_prefix = "custom_avatar",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/custom_avatar/{custom_avatar}",
 *     "add-form" = "/admin/structure/custom_avatar/add",
 *     "edit-form" = "/admin/structure/custom_avatar/{custom_avatar}/edit",
 *     "delete-form" = "/admin/structure/custom_avatar/{custom_avatar}/delete",
 *     "collection" = "/admin/structure/custom_avatar"
 *   }
 * )
 */

class CustomAvatar extends ConfigEntityBase implements CustomAvatarInterface {
  /**
   * The Avatar profile ID.
   *
   * @var string
   */
  protected $id;

  /**
   * The Avatar profile label.
   *
   * @var string
   */
  protected $label;
}

<?php

namespace Drupal\custom_avatar;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;

class CustomAvatarHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $collection = parent::getRoutes($entity_type);

    $entity_type_id = $entity_type->id();

    if ($collection_route = $this->getCollectionRoute($entity_type)) {
      $collection->add("entity.{$entity_type_id}.collection", $collection_route);
    }

    return $collection;
  }

  /**
   * Gets the collection route.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type.
   *
   * @return \Symfony\Component\Routing\Route|null
   *   The generated route, if available.
   */
  protected function getCollectionRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) {
      $entity_type_id = $entity_type->id();
      $route = new Route($entity_type->getLinkTemplate('collection'));
      $route
        ->setDefaults([
          '_entity_list' => $entity_type_id,
          // Make sure this is not a TranslatableMarkup object as the
          // TitleResolver translates this string again.
          '_title' => (string) $entity_type->getLabel(),
        ])
        ->setRequirement('_permission', $entity_type->getAdminPermission())
        ->setOption('_admin_route', TRUE);

      return $route;
    }
  }

}

```

Please suggest what is cause of error, the module gets installed without any error but when I clear all cache it shows error and the routs are not build using this way(page not found). I want to try using this class to build dynamic admin (canonical, add, edit, and delete forms for entities ) routs rather than defining in routing.yml

Thanks!

# Answer
> 3 votes
Unless you’re doing something custom, your classes need to be under ./src to be discovered. By default, MODULE/src/Foo.php is mapped to the `Drupal\MODULE\Foo` namespace and so on.

Move the two classes out of the root of your module and into ./src, clear cache, and try again.

See PSR4 namespaces and autoloading in Drupal 8 for full details.

---
Tags: 8, entities, configuration
---


title: Add priority headers

text:
# Question
Title: Add priority headers
I realize priority headers are something of the past for the most part, but I was wondering if it's possible to add additional headers (eg. Priority Flag) to an email sent from Webform (Drupal 8 version)?

Similar to this question - https://www.drupal.org/forum/support/post-installation/2013-08-29/adding-priority-flag-to-email-sent-by-webform-module

I understand this is possible with a remote post, but this is strictly for sending an email.

Any help is apprciated.

Just for context, here is how it can be set strictly in a PHP email.

```
$headers = "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$headers .= "X-Priority: 1 (Highest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";

$to = 'bob@email.com';
$subject = 'High Importance Email Testing';
$message = 'Testing email importance, please ignore';
$status   = mail($to, $subject, $message,$headers);

```

I managed to get the module working as I'd like, thanks to @jrockowitz

Here is the final module

```
<?php
/**
* implements hook_mail_alter()
*/
function priority_headers_mail_alter(&$message)
{
    // only alter webforms
   if (strpos($message['id'], 'webform_email_web_requests') === 0)
   {
       //Get webform submission
       $webform_submission = $message['params']['webform_submission'];

       //Get the value from the priority field
       $priority = $webform_submission->getElementData('priority');

       if($priority == 'Critical')
       {
           /*setting priority headers*/
           $message['headers']['X-Priority'] = '1 (Highest)';
           $message['headers']['X-MSMail-Priority'] = 'High';
           $message['headers']['Importance'] = 'High';
       }
   }
}

```

# Answer
> 1 votes
There is a hook for that...

hook\_mail\_alter()

For an example see webform\_mail\_alter()

---
Tags: webforms, emails
---


# Question
Title: How to execute ajax action after image file upload with media widget?
I want to prepopulate some node fields with image metadata (using the EXIF module) right after an image is uploaded/inserted in a node image field with media browser widget and before the node is being saved.

By default, the EXIF module updates the node fields with image metadata after the node is being saved. But, ideally, I would like to **hook into the file upload** process and update the node fields instantly with **ajax**, so that users can preview and even edit the metadata related fields.

# Answer
If I understand your question correctly, I believe you can do this with hook\_form\_alter. You can create a new form submit handler to do anything you want to do the data before it's saved. I'm not sure why you would need ajax.

```
my_module_form_alter(&$form, &$form_state, $form_id){
    $form['#submit'] = array();
    $form['#submit'][] = 'my_module_submit_handler';
//this makes sure your submit handler is run first
     array_unshift($form['#submit'], 'my_module_submit_handler');
}

```

Then create a function to make your changes and call the original form submit function...

```
function my_module_submit_handler($form_id, &$form_state){
     /*
       changes to the values submitted to your form
     */
   }

```

This is off the top of my head but should put you on the correct path. I believe that your handler will execute and then the default handler will execute.
> 0 votes

---
Tags: 7, forms, ajax, media
---


title: How to add translation of all content?

text:
# Question
Title: How to add translation of all content?
I am adding Arabic translations to an English website. For every article node, I need to individually translate each node.

Is there a way to add translations in one go?

The customer will update the content, but I need to create the initial translation of more than 500 nodes.

# Answer
> 1 votes
You can get all nodes, then with a foreach create a translation for each node.

```
$nodes = \Drupal::entityQuery("node")
//->condition('type', 'my_custom_type') //use this for specific content types
->execute();

$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ($nodes as $node) {
  //Creating the translation Spanish in this case
  $node_es = $node->addTranslation('es');
  $node_es->title = 'Mi prueba!';
  $node_es->body->value = '<p>El cuerpo de mi nodo.</p>';
  $node_es->body->format = 'full_html';
  //Saving the node
  $node_es->save();
}

```

You can add some fields like title and body, or just save.

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


# Question
Title: node_delete_confirm_submit() and hook_node_delete()
Still getting my head around Drupal 8 after using Drupal 7 for so long. I want to override (alter) the node delete action. Now in Drupal 7 I would have used `node_delete_confirm_submit()` and `hook_node_delete()` or similar such as using hook\_form\_alter and changing the submit function.

In Drupal 8 this has partly changed. I can still use `hook_node_delete()`, but there is no `node_delete_confirm_submit()` which was deprecated in favor of `\Drupal\Core\Form\ConfirmFormBase`. Rather than try and create a hack I would like to learn the proper way I should be doing this.

I have tried to use `ConfirmFormBase`. I have a src/Form/DeleteXXXConfirm.php file.

```
namespace Drupal\XXX\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

class DeleteXXXConfirm extends ConfirmFormBase {

   ... code here for confirm and delete ...

}

```

Since I want to override node/nid/delete, I assumed the routing file would look something like this.

```
XXX.delete:
  path: '/node/{id}/delete'
  defaults:
    _form: '\Drupal\XXX\Form\DeleteXXXConfirm'
    _title: 'Confirm Deletion'
  requirements:
    _permission: 'administer site configuration'
    id: ^\d+$

```

This doesn't appear to work, do I need a `Controller`? Or am I totally barking up the wrong tree? I am obviously misunderstanding something. Can anyone point me in the right direction?

# Answer
I've found inspecting the routes availble and then working back to the controller to be a super helpful way to understand how to override things.

You will need Drupal console installed.

For example run

```
drupal router:debug | grep node | grep delete

```

This will list all routes, and then filter only ones with node in and then filter only ones with delete in.

You should then see the route you are interested in (`/node/{node}/delete`) is called `entity.node.delete_form`

Now you can debug just that specific route:

```
drupal router:debug entity.node.delete_form

```

This will show you that the form for this route is called `node.delete`. If however there was a method and a controller for the route is would show you exactly what the callback is.

To change the `entity.node.delete_form` route to use your own callback you can use the new method of doing menu\_alter.

However if you want to keep the same node delete form and just change the submit handler then you can still use hook\_form\_alter to change this.
> 2 votes

---
Tags: forms
---


# Question
Title: How to set up subscription service with credits that visitors can use to buy products?
I have a client that has a Drupal 7 site with Drupal Commerce already running to manage his store of products.

He wants to add a subscription service where users could pay a monthly subscription fee, and this fee would give them credits to buy products with.

Just wondering the best way to set this up/what recommendations people have to implement this.

# Answer
> 0 votes
The Drupal Commerce site builder's guide refers to modules named Commerce Credits and Commerce Credits Transactions for building sites with a "store credit" feature.

However, these modules seem to be unmaintained and aren't covered by Drupal.org security policies, so you would need to evaluate the value of using them in your integration vs the risk of having to support a site using them without much help.

---
Tags: commerce
---


# Question
Title: how can I pass array from drupal code to js file
I have an array define in my module and I want to pass that array value to js file according to that i want to add class to html. .module file

```
$aha_initiatives = '#aha_initiatives';
  //Add a JS library
  $variables['#attached']['library'][] = 'benefit_with_unite_tabs/quick-tab';
$variables['#attached']['drupalSettings']['lotus']['lotusJS']['aha_initiatives'] = $aha_initiatives;

```

.js file

```
(function ($, Drupal, drupalSettings) {

Drupal.behaviors.benefit_with_unite_tabls = {
  attach: function (context, settings) {
    // can access setting from 'drupalSettings';
    var aha_initiatives = drupalSettings.lotus.lotusJS.aha_initiatives;

     if(window.location.hash == aha_initiatives) {
        $(".tabbable #myTab ."+window.location.hash.substr(1)).addClass("active");
        $(".tabbable #myTabContent #"+window.location.hash.substr(1)).addClass("active in");
      }
  }
};
})(jQuery, Drupal, drupalSettings);

```

here iam sending single variable but i want to send array how can I do that

# Answer
```
  // In your form alter or block or controller or where ever you have this attached.
$array = [
  'red' => 'red so hot right now',
  'blue' => 'wow thats blue',
];
$form['#attached']['drupalSettings']['myArrayOfStuff'] = $array;

```

Then JS:

```
console.log(drupalSettings.myArrayOfStuff);

```
> 1 votes

---
Tags: theming, javascript
---


title: Drupal 8 - Stock quote cache

text:
# Question
Title: Drupal 8 - Stock quote cache
I'm building a Drupal 8 site that has a stock quote on every page. The data for the quote comes from a database. The requirement is that the stock quote data be refreshed every five minutes and I've nailed down the database update portion of the process.

The other content on each page is highly static and I do not want to refresh the cache every five minutes. Our Drupal config has cache set at one hour. We also have Varnish to deal with.

Is it possible to exclude just this one block from cache? I've tried using the preprocess hook to set max-age:

```
function mytheme_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'stocktickerblock') {
        $vars['#cache']['max-age'] = 0;
    }
}

```

But this doesn't seem to work.

Thank you

# Answer
> 0 votes
Put this in a custom module:

```
/**
 * Implements hook_block_view_alter().
 */
function MYMODULE_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  if (!empty($build['#id']) && $build['#id'] == 'stocktickerblock') {
    $build['#cache']['max-age'] = 0;
  }
}

```

but if the your 'stocktickerblock' block is from a custom plugin you can set the build cache directly in that plugin render array.

---
Tags: blocks, hooks, caching
---


# Question
Title: Breadcrumbs disappear on cache clear, come back with subsequent cache clear
I have a site where the breadcrumb is in different locations depending on what node type or page is being viewed.

In some places, it is interspersed with node content, so the only solution was for my colleague to inject it into the page as a variable, like so (from `.theme`):

```
$block = Block::load('breadcrumbs');
$variables['content']['breadcrumbs'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

```

I've noticed that when I deploy code, the breadcrumbs disappear. I then have to clear the cache, clear Varnish, and clear the cache again and finally hard refresh in my browser to see them again.

Is this related to how breadcrumbs are being injected into the page and if so, is there a better way to do it?

# Answer
In a node use the breadcrumb builder directly:

```
\Drupal::service('breadcrumb')->build(\Drupal::routeMatch())->toRenderable();

```

The node gets cached already and the cache metadata of the breadcrumbs bubbles up to the node.

In a page it's preferable to place the block in a region (can be a region of its own) and then place the variable of the region in the page template.

If you want to use code to place the block, make sure you use the block for the correct theme (you have to query the block table with the property `theme` for this). Now it seems like you use the breadcrumb block placed first on your site, not necessarily the one for your theme.
> 2 votes

---
Tags: 8, navigation
---


# Question
Title: Automatic Login after Successful Registration
Is there any way to automatic login user after a successful registration, it seems I can't find any tuts/solution how to do this.Thanks!!

Any replies are much appreciated....

in my template.php

```
function drupal_onrevue1_form_user_register_submit($form, &$form_state){

    //$form_state['rebuild'] = TRUE;
    $form_state['redirect'] = "user/login";
    //print_r($form_state);die();
   $edit = array(
          'name' => $form_state['values']['name'],
          'pass' => $form_state['values']['current_pass'],
          'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
          'field_last_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),
          'field_middle_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_middle_name']))),
          'field_year_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_year_select']))),
          'field_month_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_month_select']))),
          'field_date_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_date_select']))),
          'field_gender' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_gender_select']))),
          'mail' => $form_state['values']['field_mail'],
          'init' => $form_state['values']['field_mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
    );

    $account->is_new = TRUE;
    $hello = user_save($account, $edit);
    //print_r($hello);die();

}

```

# Answer
Have a look at the Logintoboggan module. This offers you to login new users immediately.
> 3 votes

# Answer
After saving the users' data..I used to user\_authenticate() function for authenticating the username and password. Since the return value of it is the uid of the user, you can now used the user\_login\_submit() function

```
$username = $form_state['values']['name'];
$pass = trim($form_state['values']['current_pass']);
$userRecord = user_authenticate($username, $pass);
$form_state['uid'] = $userRecord;
user_login_submit(array(), $form_state);

```
> 1 votes

# Answer
Normally drupal will automatically login after successful registration , may be you have wrong settings under 'user \> settings'
> 0 votes

# Answer
Ha.. This one is simple. You just have to assign $GLOBALS\['user'\] variable to the newly created user object.

```
$fully_loaded_user_object = user_save($account); //returns user obj on success otherwise FALSE
if ($fully_loaded_user_object) {
  $GLOBALS['user'] = $fully_loaded_user_object;
}

```
> 0 votes

# Answer
I found this to work in Drupal 7.56 (and I should think earlier and later Drupal 7 versions too).

After a user is created, the `hook_user_insert` is fired. So the solution is to implement this hook in a custom module as follows:

```
/*
 * implements hook_user_insert(&$edit, $account, $category)
 */
function mymodule_user_insert(&$edit, $account, $category) {
    $newly_registered_user_id = $account->uid;

    // credit: ML and https://www.drupal.org/project/login_activity/issues/2066899 (second snippet of code)
    global $user;
    $user = user_load($newly_registered_user_id);
    drupal_session_regenerate();
}

```

Credit to my colleague xiwar for finding the second snippet of code at Programmatically login user in drupal 7 *Note* that even though this issue was raised as an issue on Login Activity contrib module, this module is *not* required as the `$user` variable, `user_load` and `drupal_session_regenerate` used in the hook are part of core as indeed the base hook, `hook_user_insert` is as well. In fact my code base doesn't have Login Activity module.

I did also try calling this code from my custom submit handler for the user registration form but although my debugging proved that the custom submit handler was called on submit, the code for auto-login did not work there. So that's why I implemented my hook for `hook_user_insert` in my custom module.
> 0 votes

---
Tags: users, forms
---


# Question
Title: How to display all the terms of a vocabulary with a list of the items associated to the term below in a view?
In a view in D8, I want to achive something like :

```
term 1
-item 1
-item2
term 2
-item 3
-item 4
term 3
- item 5
- item 6

```

Is it possible ? If yes, how ?

# Answer
It sounds like you are looking for a glossary view. There are many tutorials on how to do this, ex: https://www.ostraining.com/blog/drupal/glossary/

... after rereading, you may actually be looking to create a view of all terms in that is grouped by parent id. There are different ways to do this. Take a look at:

These talk about D7, but the same should work in D8
> 0 votes

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


# Question
Title: How can I get a list of content by contentType?
I created my content type Programmatically .. I need a function that list content who have my ContentType.

# Answer
> 1 votes
You can try like this

```
$types = \Drupal::entityTypeManager()
->getStorage('node_type')
->loadMultiple();

```

More info Get all node types in Drupal 8

---
Tags: 8, nodes
---


# Question
Title: How to hide default "N/A" option for checkboxes?
I have a "gender" (checkbox) option that I want to show on the user profile page (but not on the registration page). The options are "Male" (default) and "Female". Since I don't make the field required it is showing the "N/A" option. Drupal does this by design.

If I make the field required the "N/A" option will go away but then it will automatically show on the registration page which I don't want.

I was trying to hide it with CSS but I cannot see a way to just hide that checkbox and "N/A" text:

```
<div class="form-item form-type-radio form-item-field-gender-und">
<input id="edit-field-gender-und-none" class="form-radio" type="radio" value="_none" name="field_gender[und]">
<label class="option" for="edit-field-gender-und-none">N/A </label>
</div>
<div class="form-item form-type-radio form-item-field-gender-und">
<input id="edit-field-gender-und-0" class="form-radio" type="radio" checked="checked" value="0" name="field_gender[und]">
<label class="option" for="edit-field-gender-und-0">Male </label>
</div>
<div class="form-item form-type-radio form-item-field-gender-und">
<input id="edit-field-gender-und-1" class="form-radio" type="radio" value="1" name="field_gender[und]">
<label class="option" for="edit-field-gender-und-1">Female </label>
</div>

```

Help! ;-)

# Answer
You can use jQuery to accomplish this

```
$("#edit-field-gender-und-none").remove();

```
> 4 votes

# Answer
I think a better way to acheive this would be to write a simple form\_alter hook and `unset()` the option you don want from your field.

```
function YOURMOD_form_YOURFORM_alter(&$form, &$form_state) {
  unset($form['YOURFIELD']['und']['#options']['_none']);
}

```

in the example above, the field is a taxonomy reference field on an entity edit form, so there is the extra `['und']` \- it doesnt have to be there under all ocasions. You may want to `dpm($form)` first, to see the structure of the form.
> 3 votes

# Answer
Another quick solution is to have Drupal add a form-disabled class to the N/A form-item by adding the following function to your template.php file.

```
function <theme_name>_form_element($variables) {
  $element = $variables['element'];
  // Disable radio button N/A
  if ($element['#type'] == 'radio' && $element['#return_value'] === '_none') {
    $variables['element']['#attributes']['disabled'] = TRUE;
  }
  return theme_form_element($variables);
}

```

Then you can use CSS to do

```
.form-radios .form-disabled {
  display: none;
}

```
> 3 votes

# Answer
In Drupal 7 try the following code:

```
/**
 * Implements hook_element_info_alter().
 */
function MODULENAME_element_info_alter(&$type) {
  $type['radios']['#process'][] = '_remove_radio_na';
  $type['select']['#process'][] = '_remove_radio_na';
}

/**
 * Removes the '_none' option from a form element.
 */
function _remove_radio_na($element) {
  unset($element['#options']['_none']);
  unset($element['_none']);
  return $element;
}

```

Make sure you clear caches, otherwise it won't work.

This is a better way than hiding results with CSS or JS/jQuery as empty values are removed before the output.
> 1 votes

# Answer
I do this:

`jQuery("#edit-field-gender-und-none")[0].children[0].remove();`
> 0 votes

# Answer
One of the interesting Features of Drupal 7 is the Field API. Prior to Drupal 6, to make a custom field the Core Profile Module and Content Profile Modules are used. Now in Drupal 7 we can make any custom field to appear in User Registration Form. When Adding Custom Fields Such as Gender usually we use Radio Button Input. However there is a small Problem with the core module as it displays the third option N/A in the input. To Remove the N/A option the field needs to be set as mandatory. To Remove this option there is another way. Go to modules/field/modules/options/options.module and comment the the code $properties\['empty\_option'\] = ‘option\_none’ as shown below under buttons.

```
case ‘buttons’:
$properties = array(
‘filter_xss’ => TRUE,
);
// Add a ‘none’ option for non-required radio buttons.
if (!$required && !$multiple) {
//$properties['empty_option'] = ‘option_none’;
}
break;

case ‘onoff’:
$properties = array(
‘filter_xss’ => TRUE,
);
break;
}

```

However the proper way to achieve it would be to override this function in custom module. But for a quick fix we can also follow this method. \[blog\]: http://yamafm.wordpress.com/ "click here for updates"
> -1 votes

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


# Question
Title: What do the three checkboxes on the Interface translation import mean?
When importing a *.po* file at /admin/config/regional/translate/import

What do these three options mean?

* Treat imported strings as custom translations
* Overwrite non-customized translations
* Overwrite existing customized translations

# Answer
> 2 votes
* ***Treat imported strings as custom translations***

Will add to the Site the translations strings present in the .po file as custom translations.

* ***Overwrite non-customized translations***

All the strings that comes in the .po file will overwrite the existing translations that are not customized in the Site.

* ***Overwrite existing customized translations***

The customized translations present in the Site will be overwrite with the translations present in the .po file.

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


title: Webform Confirmation AjaxResponse

text:
# Question
Title: Webform Confirmation AjaxResponse
I'm trying to update the URL on a successful webform submission, with an inline ajax confirmation. The form works and submits fine and I already have a custom Drupal ajax command to `history.push` setup, but cannot figure out how to hook into the confirmation flow.

I have tried:

* Adding a custom callback to $form\['actions'\]\['submit'\]\['#submit'\] and returning an ajax response from that callback
* Adding a custom handler, but can't see where I could add the functionality necessary

Thanks.

# Answer
I ended up doing this by creating an event subscriber and listening for the webform ajax response as described on this issue page: https://www.drupal.org/project/webform/issues/2911409

The keylines (amended for brevity):

```
// The event to listen for
KernelEvents::RESPONSE

// Check to see if it is a webform ajax request
if(
    $event->getResponse() instanceof WebformSubmissionAjaxResponse and
    $event->getResponse()->getWebformSubmission()->isCompleted()
)

// Add my custom Ajax command
$event->getResponse()->addCommand(new UrlHistoryCommand)

```
> 1 votes

---
Tags: 8, webforms
---


# Question
Title: Update a Referenced Node with a value from the node referencing it
In Drupal 7, it was easy to update a referenced node with a value from the node referencing it, using rules: https://www.drupal.org/node/1836240

But how could I do the same in Drupal 8? This code is for updating a node programmatically:

```
use Drupal\node\Entity\Node;
$node = Node::load($nid);
$node->setTitle('MY NEW TITLE'); // This is a special meta field
$node->set('FIELD_NAME', 'THIS IS DATA'); // This is a Field added in to the content type
$node->save();

```

What hook should I call and place this code inside? I need when the user creates a new node or updates an existing node, then a field from the referenced node been updated with the value of a field from the current node. Should I use a form alter function? Is it possible with hook form alter to update, not only the current node, but also a field from the referenced node, or is there another hook for that?

# Answer
> 1 votes
Thank you both @GiorgosK and @4k4, for pointing me to the right direction! Here is the solution:

```
use Drupal\node\Entity\Node;

function my_module_entity_insert(Drupal\Core\Entity\EntityInterface
$entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() ==  'iamoriginal') {
   if (!$entity->field_my_reference->isEmpty() &&   !$entity->field_number->isEmpty() &&
 !$entity->field_hide_me->value) {
  _my_module_update_parent($entity, 'add');
 }
 }
}

function my_module_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'iamoriginal') {
$original = $entity->original;
if (!$entity->field_my_reference->isEmpty() && !$entity->field_number->isEmpty() &&
  $entity->field_hide_me->value != $original->field_hide_me->value) {
  $operation = ($entity->field_hide_me->value) ? 'sub' : 'add';
  _my_module_update_parent($entity, $operation);
}
 }
}

function _my_module_update_parent($entity, $operation) {
 $ref = $entity->get('field_my_reference')
   ->first()
   ->get('entity')
   ->getTarget()
  ->getValue();
 if ($ref->hasField('field_number_of_originals') &&        $ref->hasField('field_total_value')) {
$total = $ref->field_total_value->value;
$count = $ref->field_number_of_originals->value;
$number = $entity->field_number->value;
switch ($operation) {
  case 'add':
    $total += $number;
    $count++;
    break;
  case 'sub':
    $total -= $number;
    $count--;
    break;
}
$ref->set('field_total_value', $total);
$ref->set('field_number_of_originals', $count);
$ref->save();
 }
 }

```

If a user adds a new node of the post type "iamoriginal" then the value of the field\_number is added to the refrenced node's field\_total\_value and +1 to the field\_number\_of\_originals. If he later wants to disable the original node ,he gives a value to the field\_hide\_me and the previously added values to the referenced node are abstracted. Thank you again for your help!!!

# Answer
> 0 votes
I would take the route of not duplicating content and only deal with views configuration and theming instead.

This is how I would display such a field

**using views**

1. add relationship to the entity reference field
2. add field of the entity field (based on relationship)

**using a node view/display** add in your theme's `node.html.twig` code similar to this based on your actual entity reference

```
// get author's gender field value
{{ node.uid.entity.field_gender.value }}

// get category name
{{ node.field_category.entity.name.value }}

```

## NOTES:

If this Drupal 7 module field\_extractor gets ported to D8 then it will make field integration a configurable option and you will not have to mess with twig files as it gives a entity reference field formatter that can extract any field

Alternatives that probably require more work

* creating your own module (as per poster's request) using this as a start

```
use \Drupal\Core\Entity\EntityInterface;
//get control when entity saved or updated
function MODULENAME_entity_presave(EntityInterface $entity) {
  //see if its of specific type
  if ($entity->bundle() == 'article') {

    //get values
    $title = $entity->getTitle();
    $nid = $entity->id();
    $cat = $entity->field_category[0]->entity->label();

    //set values
    $entity->field_teaser->value = 'teaser text';
    $entity->setTitle($entity->get('field_date')->value);

    //no need to save anything its autosaved
  }
}

```
* create rules with  `React on event: updating a node`

---
Tags: 8, forms, hooks
---


# Question
Title: How do I use CkEditor layout on textfield input?
I have a content type with a "Text (formated)" field. When I try to write something in it, all my HTML is ok. But I want to use the buttons of ckEditor to make it more "user friendly". I don't want to always have to write all my tags manually.

On "Text, long (formated)" field, there is no problem.

You can see what I mean in this screenshot.

I already tried to switch text format under my field. Nothing changed, except I got more tags allowed.

# Answer
CKEditor only works on a textarea, you can’t attach an instance to a textfield.

You could implement `hook_form_alter` and change it from a textfield, but it’s hard to see what the point would be.

If you need long text, just use a long text field. It was designed for your use case, so will always work as expected.
> 1 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Best method of changing content of one field based on whether another exists
I have one field, field\_foo, that I want to be rendered one way if field\_bar does not have a value. Should field\_bar exist, I would like to render the values of both field\_foo and field\_bar together inside the same markup that all my other fields have.

I could do this in the template file for the content type, but that does not seem like the Drupal way (logic in the tpl file).

I am already using theme\_field to adjust the way some of my fields are being rendered, and I have tried to put the logic in there, but I am not sure how to access other fields from within a field-specific theme\_field function. Moreover, this does not really strike me as the proper place for this logic either.

What would be the best way of implementing the different rendering of one field based on whether or not another field has content?

# Answer
Some additions to the answer from Taggart Jensen ... I agree with using hook\_node\_view.

---

You have a few ways of going about this.

1. Using the Hook in the template.php file of your custom theme.
2. Making a small custom module and using the hook in there.

I would recommend the second option so that this is not theme-dependent.

---

Let's say you want to name your module **foo\_display**.

1. Create the folder sites/all/modules/**foo\_display**
2. Create sites/all/modules/foo\_display/**foo\_display.info** file (Note: Read here for more details on making an info file.) For the sake of this example, feel free to use this:

---

```
name = Foo Display
description = Changes how field_foo and field_bar are displayed based on their values.
core = 7.x

```

---

3. Create sites/all/modules/foo\_display/**foo\_display.module** file.
4. Enable the **foo\_display** module you created.

Inside of the **foo\_display.module** file, we are going to use **hook\_node\_view()**.

Start with the following code:

```
<?php

foo_display_node_view($node, $view_mode) {
    if ($node->type == 'MACHINE_NAME_OF_CONTENT_TYPE') {

            // Logic for Fields Here

        return $node;
    }
}

```

It was right of you to see that putting logic in the theme is not the right place. Doing something like this is a bit more Drupal-y.

---

I also saw that you were having trouble getting field-specific data.

I recommend using Entity metadata wrappers.

Here is an example of how you could use it in your scenario:

```
<?php

foo_display_node_view($node, $view_mode) {
    if ($node->type == 'MACHINE_NAME_OF_CONTENT_TYPE') {

            // Create Entity Metadata Wrapper for the Node being viewed
            $node_wrapper = entity_metadata_wrapper('node', $node);

            // Get the Value of field_foo
            $field_foo_value = $node_wrapper->field_foo->value();

            // Get the Value of field_bar
            $field_bar_value = $node_wrapper->field_bar->value();

            // Check if field_bar has a value or not
            if ($field_bar_value == NULL) {

                // Render both values together

            }

        return $node;
    }
}

```

I hope that this helps to get you started!
> 1 votes

# Answer
look in to https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_view/7.x

In Drupal 7 yes you can do this in the template file for the content type, -\> unless you are changing themes lots perhaps the "custom logic" in the theme file is the quickest win.
> 1 votes

---
Tags: 7, entities
---