add render array to custom entity in controller I have a custom entity, with a controller class that extends EntityViewController much like the node module does in core. The view method in this class returns a render array $build and it is called by the router for my entity.

I would now like to attach some more content to this render array, specifically some articles from another site. I have a class of my own that I am able to implement like this inside the view() function:

$client = new FrontpageArticlesBuilder();
$articles = $client->toRenderArray();

Where $articles is a render array. I would like to know how I can append this render array to my existing $build render array returned by view() method in my controller.

You can simply add this to the build array with an arbitrary key name. The only condition is of course that it does not already exist. Every key that does not start with a '#'-sign will be interpreted as another render element or an array of nested render elements.

$build['articles'] = $articles;


How to enable comments on custom entities I'm using a contributed module that provides a custom entity. I would like to modify that entity and want to enable comments for this entity.

Does anybody know how to enable commens for custom entities?

For Drupal 7, this module should do it - https://www.drupal.org/project/comments_entity

For Drupal 8, comments are available as a field for any entity type.

Summary:

Create a new Entity Type
Create a new Bundle for that Entity Type
Create a new Comment Type and select your Entity Type
"Manage Fields" on your new Bundle and add a new "Comments" field.
Configure comments as desired in the field settings.

Wrote a blog post about it here: http://www.daggerhart.com/drupal-8-add-comments-custom-entity-type/


Drupal WYSIWYG editor I want to have a simple WYSIWYG when people add comments and when people edit the body of a basic page.
Something that looks like this:

Any ideas?

I used ckEditor, it works fine.

You can also install wysiwyg which manage many wysiwyg editor like ckeditor and others.
You can try simple editor too.


LoginToBoggan + Don't use set password mail I would like to give my user the opportunity to register and login with username AND email.

Therefore I installed the module LoginToBoggan where you can enable that users can login using their e-mail address.

When you want users to set their password at registration you need to check the checkbox Set password. But when you do this you also get a mail to set your password (can only be used once).

But I don't want that. I just want them to register with email/username and directly login in without getting ANY email. I fire a rule to send a mail after I created an invoice so I don't want the drupal account emails.

But I didn't found out how I can simply do this?

I use the same type of setup as the one you describe:

Register and login with username and email.
Login using the email address.
User sets password upon registration (i.e. no email confirmation required).

I've found that the process where user receives a one-time link to set password is a huge stumbling block in the registration process.

Drupal let set up the site to have user sets password upon registration (Uncheck "Require e-mail verification when a visitor creates an account" on Administration » Configuration » People » Account settings).

However, I do not use LoginToBoggan to allow the users to login using the email address.

Instead, I use Realname Reg.  Please note that this is a sandbox project, but it is actively maintaned (by me), and it has been tuned specifically for the use case you describe.  I've used it on a dozen production sites for about a year with no issues.


tabledrag submit - $form_state missing values I have built a draggable table using this tutorial (halfway down page is the Drupal 8 code):

https://www.drupal.org/node/1876710

In the submit function I would like to look through all the rows and create an array for each row. I am using the following code:

foreach ($form_state->getValues(['mytable','rows']) as $tablerow) {

And then running db_update on each item using this:

$tablerow['label']

But this returns an error "undefined index". Is there something wrong with the foreach line?

UPDATE: My table is generated using this code:

  foreach ($entities as $id => $entity) {
    // TableDrag: Mark the table row as draggable.
    $form['mytable'][$id]['#attributes']['class'][] = 'draggable';
    // TableDrag: Sort the table row according to its existing/configured weight.
    $form['mytable'][$id]['#weight'] = $entity->get('weight');

    // Some table columns containing raw markup.
    $form['mytable'][$id]['label'] = array(
      '#plain_text' => $entity->label(),
    );
    $form['mytable'][$id]['id'] = array(
      '#plain_text' => $entity->id(),
    );

    // TableDrag: Weight column element.
    $form['mytable'][$id]['weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight for @title', array('@title' => $entity->label())),
      '#title_display' => 'invisible',
      '#default_value' => $entity->get('weight'),
      // Classify the weight element for #tabledrag.
      '#attributes' => array('class' => array('mytable-order-weight')),
    );

    // Operations (dropbutton) column.
    $form['mytable'][$id]['operations'] = array(
      '#type' => 'operations',
      '#links' => array(),
    );
    $form['mytable'][$id]['operations']['#links']['edit'] = array(
      'title' => t('Edit'),
      'url' => Url::fromRoute('mymodule.manage_edit', array('id' => $id)),
    );
    $form['mytable'][$id]['operations']['#links']['delete'] = array(
      'title' => t('Delete'),
      'url' => Url::fromRoute('mymodule.manage_delete', array('id' => $id)),
    );
  }

I have run dpm($form_state->getValue(['mytable','2'])); on submit for each of the rows, but only the operations and weight column values appear in $form_state. How do I get the id and label columns to appear?

The answer is quite simple - markup doesn't make it into $form_state. Place the item id ($entity->ref in the below code) in a textfield or number field instead and use the following to hide and disable it (not sure if disabling is necessary):

    $form['mytable'][$id]['label'] = array(
    //'#plain_text' => $entity->ref,
    '#type' => 'number',
    '#title' => "",
    '#default_value' => $entity->ref,
    '#disabled' => TRUE,
    '#access' => FALSE,


Multiple user avatars I'm looking at putting together a Drupal 7 installation for a community website. One of the features of the website will actually be in specific user profiles, which will double as "About" pages in a catalogue of team members. Anyway, the site is currently designed in such a way that a user has a detailed photo on their page. I'm looking at one of two different options, and would like some input as to how best to carry out this task.

After a user uploads a profile picture (with the ImageStyle profile_picture) , have the system create a duplicate photo for the forum avatar based on what was just uploaded, only resize and crop the photo to be 200x200 pixels, and have the duplicate be named under the image style forum_avatar.
Provide an additional upload form for avatars in the user configuration settings with Drupal 7.

Obviously, the first one would take a little bit of doing, but I'm really curious: what would be the best way to carry out one of these two processes?

Assuming that you want to use the same avatar image, just in different sizes, you do not have to duplicate anything.

Being able to display the same image with different styles is the whole point of having different image styles. "Styled" images are created on demand, according to the request. This already works out of the box for normal image files (For example, you can chose a different image style for teaser and default view modes).

The user avatar image can be displayed with different image styles too, the only problem right now is that you can't select the image style when using theme_user_picture(). There is however already a patch for that. And if you're using Views, it should already be possible to choose the image style for the user picture.


Will upgrading PHP version affect my current site that running Drupal 6? I am going to test Drupal 8 RC, unfortunately my PHP version is too old.

It's asking for upgrade the version higher than PHP 5.5.9.

If I upgrade it to PHP 5.5.9 or latest version PHP 5.6.14, will it affect my current site that running Drupal 6?

Your PHP installation is too old. Drupal requires at least PHP 5.5.9. See the system requirements page for more information.

As reported in System requirements, Drupal 6 requires PHP 5.x, since support for PHP 4.x has been dropped by PHP maintainers; it is recommended PHP 5.2.5 or higher, but PHP 5.3.x and higher may produce errors or unexpected behavior.

So, yes, PHP 5.6.14 is going to affect your Drupal site, especially if you installed third-party modules or themes.

Bear in mind that Drupal 6 core code will not be changed, after Drupal 8 will get its first official and stable release. If they don't fix Drupal 6 code before, it will not get fixed. Once Drupal 6 code is not fixed, it is also probable third-party modules stop to get updates too.


Entity Reference Image not rendered I have a content type with an Entity Reference field. The field references multiple images.

Using Display Suite, I can set the display format to "entity id" and when I view the content, I get a list of IDs as expected. But when I change it to "Rendered Entity", I'd expect the rendered images, but nothing is actually rendered. This is not a CSS-issue, the rendered field has no actual HTML in it. Any ideas?

You need to check the "manage display" section of the entity you're rendering and make sure the images are set as visible items in the selected "entity view mode". By default it takes "default".


How to change a collection field value with presave I'm using field_collection module, and $question is a collection field.

$question->value = 'test';
$node_poll->save();

The above code works for update this collection field value. Problem is this cannot be used for presave.

$question->value = 'test';
//$node_poll->save(); // I removed this since it does not need for a presave.

When I use above code for a presave hook. The value did not change.

How to set a value for this collection field with presave with D8?

This code worked for me need to add  in presave hook
//field collection field
  $item = $entity->get('field_items')->value;

$fc = FieldCollectionItem::load($item);

foreach ($fc as $fckey => $field) {
    if ($fckey == 'field_name') {
      $value = $field->getValue();
      $value = strip_tags($value[0]['value']);
      $summary_value = $entity->get('field_fc_child')->value;
      $entity->set('field_fc_child', $value);
    }
  }


Trigger #states via custom jQuery I have a form using #states which is great, but once a hidden field is made visible I would like the user to be able to hide it again by clicking a close button, rather than deselecting the original checkbox - hopefully by triggering the original states function. Is there a Drupal way to do this?

If "#edit-radiobutton" should launch the state, just do:

jQuery('#edit-radiobutton').click().trigger('change');


Rest Export View multilingual content taxonomy filter fails I am going to create a REST API using Drupal 8 Rest Export with Views.
It is working fine so far. I am showing some fields from content type article and added contextual filters for language and tags.

I get results like this

[
   {
      "title": "Autem Camur Inhibeo Typicus",
      "field_tags": "restapi, test",
      "field_image": "http://localhost/drupal_8_api/sites/default/files/2016-12/gen5431.tmp.gif"
   }
]

I made every field of my article translatable except the tags (they should be the same in every language). This works fine, too, the correct translation is shown and the tags change for all translations if I change them in one translation (I have english and german right now)

My problem:
When I filter by language it works fine and I get only german/english nodes. But if I filter for the tags and for german language I get no results. I could locate the problem a bit. If I set the tags-field to translateable, it works. So I think the problem might be that the german translation has no "own" tags and the filtering fails with this. The strange thing is that the JSON result is correct. (If I just filter for language I can see the correct tags in the german JSON)

Any help is appreciated (the tags should really not be translatable)

Pretty sure that's "just" yet another variant of the bug that this issue is trying to fix: Views should not condition joins on the langcode of fields that are not translatable


Drupal Services Bad request I have a drupal7 Site, in which I activated the services module to expose a SOAP service.
The problem is that I set up everything, the endpoints, the handling of the request, load the WSDL and set the class to get th efunctions, but I always get an error

function tigoapi_server() {

require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '/wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
$server->setClass('ServicePort');

error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
$server->handle($HTTP_RAW_POST_DATA);

I always get:

curl http://server/tigoapi?wsdl
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode><faultstring>Bad     Request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope

Now, if I try it , same server, same WSDL, same ServicePort class, just not going throug the Drupal router it works:

    require_once 'ServicePort.php';
global $HTTP_RAW_POST_DATA;
//$server = new SoapServer(drupal_get_path('module', 'tigoapi') . '\wsdl\TigoAPIService_1.wsdl',array('encoding'=>'UTF-8'));
$server = new SoapServer('wsdl/TigoAPIService_1.wsdl');
ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL after the server is initiated
    $server->setClass('ServicePort');

    error_log(print_r($server->getFunctions(),true),3,"/var/www/sites/tigo/sites/all/modules/services/tigoapi/tigoapi.log");
//$server->handle();
$server->handle($HTTP_RAW_POST_DATA);

This works perfectly.

I'm using nginx and php-fpm, it would seem that the difference is in the way the requests gets here as with drupal I have a $_GET variable called 'q'

any ideas on this?

Ok it seems I'm implementing it wrong.
The SoapServer::handle() source code shows why:

 if (SG(request_info).request_method &&
        strcmp(SG(request_info).request_method, "GET") == 0 &&
        SG(request_info).query_string &&stricmp(SG(request_info).query_string, "wsdl") == 0) {.....

the Get parameter must be wsdl, which Drupal rewrites.
Also in essence using the SoapServer drupal module you get around this.
references to implement this properly:

example
More info
Soap server module


How to get user data when I provide the uid or username - Services I am using postman.
I want to provide the username or uid and fetch the user's information.
What should be the URL.

URL to fetch the user information by providing uid as follows.

http://[yourdomain]/[endpoint]/user/[uid]

Example: http://www.example.com/rest/user/2 will fetch user information, having user id 2.

You can get the user data by providing username, you can use pass name (username) as a parameter to the service URL like follows

http://example.com/<endpoint path>/user?parameters[name]=krishna

If you have enabled session authentication you might have to pass X-CSRF-Token in headers.
For session authentication you can find my answer here


Drupal(.module file) <?php
/**
Provides a block with query and store in database
*/
/**
* Implementation of hook_help().
*/
function demo_help($path,$args)
{
if($path=='admin/help#demo')
{
return t('To use this module, go to block page and turn on the       demo');
}
}

function demo_block_info()
{
$blocks=array();
$blocks['demo_member']=array(
'info'=>t('Demo member'),
'cache'=>DRUPAL_NO_CACHE,
);
return $blocks;
}

/**
* Implements hook_block_view().
*/
function demo_block_view($name)
{
if($name=='demo_member')
{
//$format2 = 'g:i a';
$content=db_query("SELECT entity_id FROM     {field_data_field_category_status}")->fetchField();
            $content.='';
            $block=array(
            'subject'=>t('Member'),
            'content'=>$content,
            );
            return $block;
    }

}
?>

i need to display 3 records by fetching array(.module file)
i am getting single record:
Member
1
i should get below
Member
1
2
3

Change

$content=db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchField();
$content.='';

to

$records = db_query("SELECT entity_id FROM {field_data_field_category_status}")->fetchCol();
$content = implode('<br />', $records);

At the moment you're just getting the first record from the result set, not all of them.

As a side note, going directly into field tables isn't the best idea. Have a look at EntityFieldQuery for an alternative.


Set default value for taxonomy list using form_alter how do I Set default value for taxonomy list?
I have tried altering form with the following line included, but it didn't work:

$form['taxonomy'][3]['#default_value'] = 6;

3 is my VOC ID and 6 TID that I want to select as default

If you are using hook_form_alter I believe this will work

$form['taxonomy'][3]['#default_value'] = array(0 => 6);


Are node data stored in the render array $page? Are node data (e.g. title, body, comments) stored somewhere in the renderable array $page, and converted into HTML during rendering? Or does a renderable array just contain properties that indirectly cause to load particular templates files?

Where are variables that store these values printed?

Yes, it's probably in there somewhere. However, it much easier to get the current node object (if there is any) with the menu_get_object() function:

if ($node = menu_get_object()) {
  // Do stuff with $node.
}


How do I assign a specific role to each newly registered user? Is it possible in Drupal 8 to assign a specific role to each newly registered user?

I had to implement a similar feature in a site, where:

Users are not required to verify their email address
When users create an account, they get the unverified account role
Once the users verify their email address, the unverified account role
is removed, and they get a confirmed user role

It is pretty similar to what drupal.org does nowadays; I am just using different roles, and custom code that is different from what drupal.org uses.

I didn't use the Auto Assign Role module, since there isn't a working version for Drupal 8. I didn't use the Registration Role module, since it adds the roles to every account being edited, including the accounts with the administrator role.

I used a custom module (which I was already using for other purposes), where I implemented hook_ENTITY_TYPE_presave() with code similar to the following one.

function mymodule_user_presave(UserInterface $user) {
  if ($user->isNew() && !$user->hasRole('unverified account')) {
    $admin = FALSE;

    foreach ($user->getRoles(TRUE) as $id) {
      $role = Role::load($id);
      if ($role->isAdmin()) {
        $admin = TRUE;
        break;
      }
    }

    if (!$admin) {
      $user->addRole('unverified account');
    }
  }
}

hook_ENTITY_TYPE_insert() and hook_entity_insert() are the wrong hooks to use, since they are invoked when the entity is already saved in the database. Calling the save() method on the entity passed to those hooks will cause all the hooks invoked when an entity is saved to be invoked again, causing an infinite loop.


Stop Varnish from caching 302 redirect from POST responses drupal_goto() uses a 302 redirect by default, which means a lot of redirects, including form redirects, get served with a 302 response code.

Having a issue in Varnish that is caching 302 response from user submitted forms for anonymous traffic.

It caches the first 302 redirect but then if the customer selects different options on the form it should be redirected to another url.

Not being able to cache product pages on our Drupal commerce site amounts to millions of cache misses a month and excessive performance issues. Drupal based page level caching is not a option as we have over 4,500 stores deployed.

How can this be fixed?

Disable caching in fetch if response status is 302

sub vcl_fetch {
set beresp.grace = 24h;

if (beresp.status >= 400) {
     return (hit_for_pass);
}

// New Set Longer Cache
if (req.http.user-agent ~ "(Googlebot|msnbot|Yandex|Slurp|Bot|Crawl|bot|Baid|Mediapartners-Google)") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
if (req.request == "GET" && req.url ~ "\.(css|xml|txt)$") {
    set beresp.ttl = 5d;
    unset beresp.http.set-cookie;
    return (deliver);
}
// multimedia
if (req.request == "GET" && req.url ~ "\.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|img|tga|woff|eot|ttf|svg|wmf|js|swf|ico)$") {
    unset beresp.http.set-cookie;
    set beresp.ttl = 5d;
    return (deliver);
}
//Fix to stop caching 302 responses
if (beresp.status == 302) {
  remove beresp.http.Cache-Control;
  set beresp.http.Cache-Control = "private, no-cache";
  set beresp.ttl = 0s;
}
set beresp.ttl = 5d;
return (deliver);

}

Setting cache control for 302 redirect:

sub vcl_deliver {
// Remove Varnish identifying information from headers
// Note: Both cache hits and cache misses will use this subroutine.

set resp.http.Access-Control-Allow-Origin = req.http.X-Saved-Origin;

remove resp.http.Via;
unset resp.http.Server;
remove resp.http.Age;
remove resp.http.X-Powered-By;
remove resp.http.X-Varnish;
remove resp.http.X-Generator;
remove resp.http.X-Mod-Pagespeed;
remove resp.http.X-Drupal-Cache;
remove resp.http.Link;
set resp.http.Server = "Prism";
// Stop Caching 302 redirects
if (resp.status == 302) {
  remove resp.http.Cache-Control;
  set resp.http.Cache-Control = "private, no-cache";
}

if(req.http.host ~ "printsites.net"){
     set resp.http.X-Robots-Tag = "noindex, nofollow";
}

return(deliver);

}


Drupal using panels with ajax I have two questions.

I wish to build a website that will use a three column look. I was told to use panels, I found it easy to use.

My question is I have a menu bar, all menus point into different panels, the reason I do this every page I have has different blocks in it, some of these blocks point to sub-panels. (A., is there a "smarter way" of doing this?)

B., my main question how can I use ajax, so when somebody clicks any of the links on my menus only the panels reload, not the full site?

Regards,

For this to work you might have to restructure some of your blocks into mini panels but you could implement this module, Panels Ajax Tabs. Ajax can now be used when loading content via panels, either as a tab or container.

  Provides the ability to have a tabbed panel-pane that displays mini-panels within it.

If you require more control; instead you could utilize Ctools AJAX. Of course this is a much more hands on approach.

Hope this helps,


Set value in $form_state['storage'] seems to change before validation I am sure that I do not understand something fundamental about Drupal's form API but I hope that someone can help me with that:

I want to create some kind of custom CAPTCHA as the CAPTCHA module states that with caching enabled on your project problems could appear and my project really needs caching via the Boost module. The idea was the following in my forms building array:

  $number1 = rand(0, 10);
  $number2 = rand(0, 10);
  $form['numbercheck'] = array(
    '#type' => 'numberfield',
    '#title' => 'Please fill in the sum of '. $number1 .' and '. $number2,
    '#required' => TRUE,
  );
  $form_state['storage']['checksum'] = $number1 + $number2;

Then in validation I wanted to do the following check:

 if($form_state['storage']['checksum'] != $form_state['values']['numbercheck']) {
  form_set_error('numbercheck', 'The sum was not correct');
}

But every time I fill in the form the following happens: say the first random number is 1 and the second number is 2 - I fill in the correct value "3" but get an error "The sum was not correct". Using Devel module and dpm()-function to get the values of $form_state['storage']['checksum'] and the single random numbers I realize that this value changed after submitting the form - while viewing the form the value is correctly "3" but when validation starts the value change to let's say 4 because the then newly created numbers in the then newly created form are maybe 1 and 3.

I tried

$form_state['rebuild'] = FALSE;

in form building function as I thought that the form may be rebuild before validation starts and therefore the random numbers were newly created as well as the $form_state array may be changed but this did not solve my problem.

I hope that somebody can help me out with that - thank you very much in advance!

Best,
Tobias

I don't like the cache method as it is quite complicated. If cache method is the only way to do that. I would recommend using Session Cache API.

In this case, exposing the answer to the form and collecting it from $form_state['input'] would be my choice.

function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];

  $number1 = rand(0, 10);
  $number2 = rand(0, 10);
  $form['numbercheck'] = array(
    '#type' => 'textfield',
    '#title' => 'Please fill in the sum of '. $number1 .' and '. $number2,
    '#required' => TRUE,
  );

  // hidden field is only hidden to user but you still can inspect it
  // from source. So hash function is used to encrypt here.
  $form['checksum'] = array(
    '#type' => 'hidden',
    '#value' => isset($input['checksum']) ? $input['checksum'] : hash('sha256', $number1 + $number2),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

function mymodule_custom_form_validate(&$form, &$form_state) {
  $hash = hash('sha256', $form_state['values']['numbercheck']);

  // compare the hash result.
  if ($form_state['values']['checksum'] != $hash) {
    form_set_error('numbercheck', 'The sum was not correct');
  }
}


Drupal 8.0 to 8.1.8 upgradation is not working When i tried to update drupal to latest version (8.1.8) am getting  the following error

But in the status report page it shows as upgraded to 8.1.8

Any idea how to resolve this ??

The message is a notice not a error so updating of core just went on. So you core is now on the latest version.

You should however solve the error.


Limit the menu level on node add/edit page On node add/edit page we have a menu settings option. This option by default show all the nodes in the main menu under Parent Item tab. Is there a way we can limit the nodes in the menu(under parent item) to only first two levels.

Menu Performance Module does exactly that.

Drupal is already aware of this issue and has a variable menu_override_parent_selector which can be leveraged by other modules to come up with their own implementation of the menu handlers on node edit page.

As the project page reads

  Menuperformance takes advantage of this, and sets the variable when
  installed. It then proceeds to add its own AJAX based parent menu item
  selector widgets for the node edit, node type edit and vocabulary edit
  pages.

How to Use from README.txt

  Enable the module.
  Go to /admin/config/user-interface/menuperformance , and activate the  module. Checking the checkbox sets Drupal variable
  menu_override_parent_selector.
  After the module is activated, the menu item selectors on the above  mentioned pages should have been replaced with a multiple dropdown
  AJAX-powered selector instead of the standard single dropdown.


REST Serialization escapes URLs Since updating to 8.3 we've noticed that some URL's in our REST responses are being escaped (this may have been happening before but I don't think so as it is now causing issues with the Android parser).

The URL's are escaped like this;

{"_links":
    {"self":
        {"href":"http:\/\/example.com\/api\/resource\/80?_format=hal_json"}

Those w's (//) and v's (/) are killing things and I'd like to remove this escaping.

BTW, this API is password protected and used by a controlled app only. While removing this escaping may introduce issues with public API's and security/stabiliy, we don't need this level of control.

Can I just override the Serialize class and use that?

Actually, I can't see how this could have been different prior to 8.3 - PHP's json_encode seems to have been escaping / by default forever, and neither Drupal nor Symfony seem to have overridden that in the past.

The service ID and class you would need to override is serializer.encoder.json (Drupal\serialization\Encoder\JsonEncoder), adding a JSON_UNESCAPED_SLASHES to the options bitmask in the constructor. (Confusingly, there's a separate service named serialization.json, which isn't the one that's used here.)

However, note that \/ is a valid escape sequence in JSON (if not strictly required), and a JSON parser must interpret this as a literal forward slash character to be working correctly. There should be no backslashed URLs in the parsed values. Is it possible that your client's parser library has a bug?


Difference between bootstrap carousels and how to set up? I have tried to add the bootstrap_carousel to the Bootstrap Business template. I have researched every possible forumpost about this slider, but can't get it to work.
Now, the slider works perfectly just as content, but I want to create a view in order to implement it on every page as a banner. Therefore, I followed this guide.
My view does not work. I get to see this:

My settings for that view are:

Anyone with an idea about what's going wrong? Again, my content type itself is displaying fine, as you can see in the following screenshot. It is the view that is not working.

UPDATE
I inserted a custom block with PHP code, but now I have a new problem. Sometimes, two images become active:

Do not use Views Bootstrap module. Rather just display the node (of type Carousel) full content.

Construct your view as follows:

Format: Unformatted list, show Content, Full Content

Filter Criteria: Content:type (= Carousel)

Pager: show 1 item only.

Set jQuery update to 1.9 and load jquery-migrate

Your theme pulls Boostrap from CDN. Bootstrap Carousel requires another Bootstrap library in libraries folder. Is this optimal? I don't think so.


Data selectors for custom fields I have two node types: Item and Order. I have an entity reference (field_items) set up on the Order content type which references Item (1 Order to N Items).

The Item has a field (field_reservation_status) which is a drop-down list of strings.

I am trying to set up a rule so that when I allocate an Item to an Order on the Order form, the reservation status on the related Item will be set to "Reserved".

I am doing this with a reacting rule and a rule component as follows.

Rule component

Condition: Node is of type "Item"

Action: Set a data value (this should set field_reservation_status on the node that the component is actioning to "Reserved")

Reacting rule

Event: When a content node is saved

Condition: Node is of type "Order"

Action: Add a variable (this should store field_items for the current Order node)

Then

Action: Call the rule component

Questions

In the rules config UI I can't see any "Add Loop" button - is this to be expected in version D8 Alpha 3?
What data selector should I use for accessing field_items on the Order node that has just been saved?
What data selector should I use in the rules component to access field_reservation_status on the current object from field_items?
How do I set up a loop over the variable that is created in the reacting rule?

No doubt I'll have more questions.

In the rules config UI I can't see any "Add Loop" button - is this to be expected in version D8 Alpha 3?

yes ... as per the issue about Implement Loop UI.

  What data selector should I use for accessing field_items on the Order node that has just been saved?

I doubt this is possible in the D8-alfa3 release of Rules. Though you may want to retry using the D8-dev release ...

  What data selector should I use in the rules component to access field_reservation_status on the current object from field_items?

Refer to my answer to "2." above ...

  How do I set up a loop over the variable that is created in the reacting rule?

Refer to my answer to "1." above ...

PS: No doubt you'll run into more-of-the-same issues using any of the currently available releases of Rules for D8. However, using the D8-dev release is currently your best bet/alternative.


How to make a reset form button without type 'markup'? My situation:

I built a form with FAPI. I display the results in a table like this:

function grap_contact_repository_form_submit($form, &$form_state) {
  ...
  $form_state['results_table'] = array('#markup' => grap_contact_repository($matches));
  $form_state['rebuild'] = TRUE;
}

The grap_contact_repository function returns a theme_table.

My problem:

Because of the results_table that already uses a #markup type, I can't build a reset button for my form using '#type' => 'markup' too. (Because all the results table will be clickable too).

I'm looking for an alternative to make this button work. I tried this:

$form['clear'] = array(
  '#type'       => 'button',
  '#value'      => 'Réinitialiser',
  '#attributes' => array('onclick' => 'this.form.reset();'),
);

or this: (http://www.blue-bag.com/blog/drupal-form-api-reset-button)

  $form['reset'] = array(
    '#type' => 'button',
    '#button_type' => 'reset',
    '#value' => 'Réinitialiser',
    '#validate' => array(),
    '#attributes' => array(
      'onclick' => 'this.form.reset(); return false;',
    ),
  );

But it doesn't work. The onclick works if I put another JavaScript like alert. I have nothing in my JS errors console.

Does someone have an idea to make it work?

Thanks a lot :-)

Type should be reset, not button.

  http://www.w3schools.com/tags/att_button_type.asp

You right, there is no such type. I was able to get this working with 2 submit buttons and return false (similar to your original implementation).

function drupalform_form($form, &$form_state) {

  $form['name']=array(
    '#type'=>'textfield',
    '#title'=>t('Enter your name'),
    '#description'=>t('Your first name goes here')
    );

  $form['submit_button1'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    );

  $form['reset_button'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
    '#validate' => array(),
    '#attributes' => array(
        'onclick' => 'this.form.reset(); return false;',
        ),
      );

  return $form;
}

If it still doesn't work there is this alternative solution: How to reset specific form elements


Composer, git and update core and modules I started working with Drupal 8 and tried to find out the best way for developing and administrating projects. As Drupal 8 with all its dependencies is very big (more than 60 MB) I like the suggestion not to commit all the Drupal core, modules and dependencies into a git repository but to let Composer deal these things. The idea is to set everything (Drupal core version, installed modules with their versions) in the composer.json, commit this file to a GIT repository and when a remote colleague wants to work on the project he/she just checks out the composer.json from the repo locally, starts composer install and all the needed PHP files (Drupal core, modules and dependencies) get downloaded (as far as I understand).

For me this seems to be an interesting way to start new projects but I feel that this could be some kind of bottleneck for the everyday project management. For example when I define the modules and the core in composer.json usually it seems to be done in a more general way in terms of the version. Usually not the specific version seems to be defined in composer.json:

"drupal/core": "8.0.*"

When I start composer install locally earlier as my colleague he/she might get a newer version of Drupal which may lead to different behaviors of our working copies (although it should not with regards to versioning rules - I know). But if we define a specific version:

"drupal/core": "8.0.0"

so we can be sure that every remote colleague will have the exact same version we can not use composer update to update to newer versions automatically - we would need to look for the latest version and change the version in composer.json manually.

The same appears with contributed modules or themes.

To be honest, I never worked with Composer before; maybe someone with more composer experience could explain to me how to deal with these issues.

Is it correct that "composer install" does install the versions as defined in composer.lock which gets created after "composer install" is run the first time?

The composer.json file describes which versions can be installed, while the composer.lock module contains the version of the installed libraries.

For example, the composer.json file could contain the following, which would say that is only acceptable to install any version that is greater or equal to 1.0 but lower than 1.1.

"require": {
    "monolog/monolog": "1.0.*"
}

The composer.lock file could contain a "monolog/monolog": "1.0.2" line, since that is the higher version available of the Monolog library that respect the restrictions of the composer.json file.

So, simplifying:

The composer.json file is used from composer install
Both the composer.json and the composer.lock files are used from composer update

  When I start composer install locally earlier as my colleague he/she might get a newer version of Drupal which may lead to different behaviors of our working copies (although it should not with regards to versioning rules - I know).

Yes, that can happen, but it is not a problem, since you just need to run composer update to get the same versions your colleague has. That is, if both of you have the same composer.json file, and neither of you installed other libraries that could cause any conflict.


Add a view with a contextual filter not on a node/taxonomy page Druapl 7 - I have a taxonomy vocabulary called ‘Destinations’ and an entity created called “accommodation”. The accommodation entity contains names of individual accommodations, to simplify, let’s use hotels. So:

Entity type: accommodation

Hotel X - San Diego
Hotel Y - Barcelona
Hotel Z - Rome

What I want to do is create pages that show which accommodation is available in which city. So I need to create a page for each:

/san-diego/accommodation
/barcelona/accommodation
/rome/accommodation

I can do this by adding a custom page:

/admin/structure/pages/add

I have created a view but can’t quite get my head around how to use contextual filters and relationship to show only the hotels available at each accommodation page.

How will Drupal “know” that this page should show hotels in San Diego:

/san-diego/accommodation

I understand contextual filters and relationships and use them all the time, but can’t figure out how to do this in the case.

What is the best way to create these pages and add the view?

You already have Views that list all the content tagged with a Taxonomy term. The Views is called Taxonomy term, but it is a Content type Views listing nodes that have been tagged with a particular term.

You can Clone the Taxonomy term view and edit the clone to adjust it to your specific needs for Accomodation. Keep the original Taxonomy term View disabled if you don't need it. But you can keep it enabled along with the cloned instance too.

You want to change the Path to accommodation/%, the first part shouldn't be variable.

Also add a new Filter Content: Type and choose Accommodation only.

You can also change to use Fields instead of Content for more control over what is shown in each Accommodation result.

With this setting you will get pages that take term ID as the argument. If your San Diego term has ID 12, then if you visit the page /accommodation/12 you will see Accommodation nodes tagged with San Diego.

You don't have to create those pages in any other place than Views, they're already working when you type the correct path with term ID into your browser location bar.

If you want to list all the available terms you can use the Summary in the When the filter value is NOT in the URL option of the Contextual filter. This way when users visit the /accommodation path they see a list of locations. When they click on a location they see accommodation nodes associated with it.

You can use the Menu option to add the page to a menu of your choice.

Use term names instead of IDs

To get the term name to appear in the path instead of the TID you have to add the Relationship to the term, and use a Contextual filter Term name that uses that Relationship. (Remove old Contextual Has term ID.)

I've covered details in another Question: How to setup view to filter based on second URL parameter?

Be careful about the Case settings, use dashes ;)

With this configuration your path will be /accommodation/san-diego.


Unable to set Singularity grid total to 16 I’m having a problem using the Singularity grid framework. I set the total number of columns to 16 but it seems not to be reading this setting. instead the total seems to be 12.

the details are as follows.
I’m using the Omega theme and have correctly implemented a sub-theme
i’m using SASS and in the grid partial, _grid.scss have this code

@import "singularitygs";
$tab: 44em; /*704 pixels */
$desk: 70em; /* 1120 pixels */
$grids:16;
$gutters:1/4;

for test purposes i set a div to be 16 columns with this code.

.someDiv {@include grid-span(16, 1); }

this div then breaks out of the main page div, in this case .l-page and in the inspector it reads as

width:133%;

to trouble shoot i’ve searched via grep ‘grids:12’ and cleared the .sass-cache file. but so far nothing is working. has anyone had this same problem?

Make sure that you aren't overwriting your grids variable.  I believe that by default, it's overwritten when the browser reaches the $tab size via: $grids: add-grid(12 at $tab); so searching for that line would be a start.

To help visualize your grid, singularitygs has the @include background-grid($color: blue); option that might be helpful while testing.

Lastly, you can always set your grids on the fly with a 3rd argument in your grid-span calls.  For example:

// Override the default $grids variable to use 16 grids
@include grid-span(16, 1, 16);


Force all links to be absolute I've a custom module I'm sending the content of node and views by email. The module first render the node/view and wrap the results around common template.

But when my views and node content are build, they contain links are relatives. I'm looking for a way to force these links to be absolute (ie. with domain and protocol).

The url() and l() functions can be used to output absolute links, but I don't see a way to force this behavior on all links. I'm planning to process the content as an HTML string to extract all links and complete the URL when required. But this doesn't seem very efficient.

Is there another way to ensure absolute URL ?

Here is the code used to render the content for nodes and views:

//For nodes
$node = node_build_content($node, FALSE, FALSE);
$node->body = drupal_render($node->content);
unset($node->teaser);
node_invoke_nodeapi($node, 'alter', FALSE, FALSE);
$content = $node->body;

//For views
$content = $view->preview($display_id, $arguments);

Have a look at this module: Pathologic

  Pathologic is an input filter which can correct paths in links and
  images in your Drupal content in situations which would otherwise
  cause them to “break;” for example, if the URL of the site changes, or
  the content was moved to a different server. Pathologic can also solve
  the problem of missing images and broken links in your site’s RSS
  feeds. See more example use cases on the documentation page.


How to pass variable to a view after submitting? Why does the below code not work?  I am trying to pass the $_POST value to example_page() when I submit the form:

function example_menu () {
  $items['example'] = array(
    'title' => 'Example',
    'page callback' => 'drupal_get_form',
    'page_arguments' => array('example_form'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function example_page($arg) {
  return "hello, $arg!";
}

function example_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'text',
    '#default_value' => t('Enter your name')
  );
  return $form;
}

function example_form_submit($form,&$form_state) {
  //BELOW DOES NOT WORK, and forget about passing raw HTML to output
  return example_page($form_state['values']['name']);
}

I'm only assuming but I would imagine that the form is redirecting somewhere after your submit handler, that's why the result of example_page is not being displayed. Also I'm not sure if you're copying the code or written it on StackExchange but you're missing a return from your hook_menu

This is how you'd normally pass variables to pages:

function example_menu () {
  $items['example'] = array(
    'title' => 'Example',
    'page callback' => 'drupal_get_form',
    'page_arguments' => array('example_form'),
    'type' => MENU_CALLBACK
  );

  $items['example/page/%'] = array( // % means variable
    'title' => 'Example arg',
    'page callback' => 'example_page',
    'page_arguments' array(2), // 0 is example, 1 is page, 2 is the % variable
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function example_page($arg) {
  return '$arg is: ' . $arg;
}

function example_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'text',
    '#default_value' => t('Enter your name')
  );
  return $form;
}

function example_form_submit($form,&$form_state) {
  // No return from submit handler, but set redirect
  $form_state['redirect'] = 'example/page/' . $form_state['values']['name'];
}


How to define an intermediate admin user as the default install profile on fresh drupal 7? When generating a new drupal site (multisite), I would like to define the default user profile as an admin user without acces to administration menu.

How can I create this new user as an install profile with default login infos, keeping at the same time the admin user?

You need to create a new role

$admin_role = new stdClass();
$admin_role->name = 'myadminwithoutmenuaccess';
user_role_save($admin_role);

//This will give them all perms
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

Then you just revoke administration menu

 user_role_revoke_permissions($admin_role->rid, array $permissions = array('administration menu'))

if you need to get the $rid at a later time you can do
user_role_load_by_name()


remove save button on a particular page I am creating a form which consists of 3 tabs.In the first tab form submit is by clicking on save button of type submit,in the second tab the submit is by jQuery,in the third tab the submit is by clicking on save button of type submit.My problem is i want the save button to appear on only two tabs i.e., only on first and third tab.I dont want the save button to appear on second tab bcoz that second tab form i submit using jquery.how can i remove save button in second tab?plz help

jQuery(document).ready(function() {
 if (window.location.pathname == '/recruiterForm/2') {
      jQuery('input#edit-submit').hide();
      }
});

i have solved this problem using jquery.I have used window.location.pathname.This property returns the pathname of current page.if pathname is equal to the required url then i am hiding the save button by using the save button id.This solution works for me.


Managing different view modes for a single content type I have three different view modes for a single content type on my site. Besides the default and teaser view modes, using Display Suite, I made a custom one called "simplified" . What I need is to make a page view with a list of node titles which would link to the nodes in  the simplified view mode, which would themselves contain a link to the full content view mode.

I am not sure as to what the best way to do this would be. It could be something very simple which I failed to think of, since I am relatively new to Drupal.

I also found the View Mode Page module, which is a great idea, but it doesn't seem to work at all.

One way to do it:

Set up the default view mode to be a simplified version
Enable display suite extras, then "View mode switcher" under "Other"
In the detailed and simplified view modes, add the "Switch view mode" field
Configure the Switch view mode in each instance to provide links to the other view mode

Your view then should link to your content type with the simplified view and give the user links to toggle the view back and forth between detailed and simplified.

Note that Display suite extras also has a feature called "Switch View Mode", which allows you to set the initial view mode on a node by node basis.

More info in this video: https://www.youtube.com/watch?v=tiUzobRKKco

Edit: I notice that if you enable "Switch View Mode" in DS extras, there is also the option to use view mode switching by URL, by appending ?v=viewmode to the URL. So, that's another option for linking to a specific view mode from your view. In that case, you'd need to use the Rewrite feature of views to build your own Title links that include the extra view mode parameter.


Multiple Voting in One Node I couldn't come up with much constructive title, as
The Title could also be: Separate Voting system for Fields in same Node

In a Content Type I have 3 fields

Mind
Body
Soul

all are Longtext as in the picture below.

At the moment in this content type, I am using Plus1 Module with VotingAPI for vote, but this doesn't seem to fulfill my need.

What I am trying to acheive is to have 3 voting system, one for each field (Mind, Body and Soul), so, any individual can vote in any of these field.

I have tried using the Fivestar Module and adding it as field, but it breaks my Page Layout due to JavaScript Conflict. I will post that as different question.

My question is: is there any readymade module which can help me acheive this, so, I can have Voting system for Individual Field item and store the votes in Database.

I've not had much luck with the plus1 module.  The 7 version is wonky.  If you're just looking for a plus 1 or like function and your fixed on the voting api then vote up/down May work for you.  You can create multiple voting fields and they are tracked separately as a field.  The widget may cause some layout issues so may I suggest using flags instead.

Why?  It's easy to add a plus1 type feature and flags can be formatted using views or flag_create_link() so you can put it every where and wrap it in any CSS div or span.  You can have as many as you'd like and it's all in the db and available to views.  You can even use rules so the system can react on a flag.  I've moved away from voting api in favour of flags.


how to rewrite field in view I have following Html code, I want to rewrite two field .1st is  [field_poster_hover_image] and 2nd is [field_team_image] .This is my HTML Code.

and I have written code like this but its not working

You don't want to use [field_team_image] in the src ,just put the [field_team_image] you can get the image and print $data in views custom php field to get the another image to get the url.


Loading bootstrap.inc in external PHP file in a subdirectory I'm trying to check if there is a user logged into drupal in a PHP script that resides within a subdirectory of the drupal root. I know that there can be issues with calling the bootstrap anywhere apart from in the drupal root, so I've created a drupal_bridge.inc.php file inside the root containing the following code, which I then call in the PHP script using include.

<?php

define("DRUPAL_ROOT",     "/var/www/vhosts/mysite.com/httpdocs/");

$current_wd = getcwd();

chdir(DRUPAL_ROOT);

print getcwd();

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';

global $base_url;

$base_url = (array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

chdir($current_wd);

global $user;

if ($user->uid) {
    print "Logged in";
} else {
   print "Logged out";
}

echo 'INCLUDED';

?>

However, when I visit the PHP script in the browser it says I am logged out. Strangely though if I visit the drupal_bridge.inc.php file directly it can access the user information and it says that I am logged in.

I have set $cookie_domain = .mysite.com in the settings file as well. I have password protected the directory containing the PHP script but I didn't think that made a difference at this level.

Any ideas?

Also, I have looked into turning this in a module but it is not really practical so I would appreciate it if you did not advise doing so.

UPDATE: I just did a print_r($GLOBALS); to see if I could find out what was actually available and I found the following errors, if that helps.
http://pastebin.com/YtHPGD75 (too long to post here)

The bare minimum required is:

define('DRUPAL_ROOT', '/var/www/vhosts/mysite.com/httpdocs/');
$_SERVER['HTTP_HOST'] = 'mysite.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

If you don't want to fully bootstrap and only get the session, see the technique defined in Getting the current user without bootstrapping to DRUPAL_BOOTSTRAP_SESSION


How can I maintain redirects from a non-existing path to an existing one? With Drupal 7, the Global redirect module provided end users with a great interface to input redirects from a non-existing path to an existing one. I have installed and enabled the Redirect module for Drupal 8, but I do not see where end users can maintain a list of redirects. We are migrating an old site to Drupal 8 and we will need a method to redirect old URLs to new ones.

How can I maintain these redirects using the Redirect module?

After you've installed and enabled the "Redirect" module (https://www.drupal.org/project/redirect), you can manage your redirects by going to the redirect list page at /admin/config/search/redirect:

You can find this route and all the other routes provided by the "Redirect" module in redirect.routing.yml:

redirect.list:
  path: '/admin/config/search/redirect'
  defaults:
    _entity_list: 'redirect'
    _title: 'URL redirects'
  requirements:
    _permission: 'administer redirects'


Writing Drupal 7 queries using drupals DB abstract. (Similar to an entity wrapper) Drupal (7) uses an abstact for handling DB-s.

I'd like to write dynamic queries where i can use drupals abstract.

There's entity wrapper for entities and I'm
Looking for something similar to DB-s.

Is there anything like that?

If by level of abstraction close to the one given by entity wrappers, you mean a module/library that would allow to write code similar to the following, no, there isn't anything like that.

$field_value = database_wrapper('table')->table_field;
database_wrapper('table')->set('table_field', $new_value)->save();

The level of abstraction that would offer, in the case of reading the database, would not be worth the code you would write to implement it, and it would just save a few method calls. In fact, $field_value = database_wrapper('table')->table_field; would be equivalent to the following Drupal 7 code.

$result = db_query("SELECT table_field FROM {table}");
foreach ($result as $record) {
  // Use $record->table_field;
}

Also for writing, the Drupal 7 code is not much complicated to require a wrapper.

db_insert('table')
  ->fields(array(
    'table_field' => $new_value,
    ))
  ->execute();

Real code would be more complicated than this, but a wrapper that should consider every case would be even more complicated.


How to create custom View template? I want to create a simple php template for Views in Drupal 7, but I think I'm missing a crucial element to this puzzle, as every time I try to get to the content of Views' output in the template's php code, even if I use the default views-view.tpl.php file as a template for that particular view, I get

  Undefined variable: fields in include() ...

How do I get around this?

How is your override requirement? Is it for all the views or for a certain views?

For certain views:
In that views admin page : go to Advanced -> Theme: Click on Information

you will see the active templates for 'Display output' in bold (views-view.tpl.php) and rest available theme suggestions for overridden (comma separated).

Now copy views-view.tpl.php from views contrib module theme folder and put it in your site theme folder, rename it to one of the name suggestion available in views. Make changes to your template.

Clear cache and check.


Restrict User Type to buy a Product Type in Drupal Commerce I am selling membership type without using subscription module as it doesn't fit into my scenario. I am assiging role by help of rules as per Randy screencast & it works nice for me.

Now the problem is with renewal of the membership. So I have to set up another kind of product type, which will work for renewing the membership.

So is there any way to restrict usertype to buy any product type ?

Thanks :)

You can create a different product display type (i.e. content type) for the renewal product (at admin/structure/types). Then you can restrict that content type to those with the members role (in admin/people/permissions).

Or, if you want to show the product display type, but restrict the actual purchase, I think you have to resort to custom code like this:

<?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the Commerce 'Add to Cart' form.
 */
function custom_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  global $user;
  $roles_allowed_to_buy = array(
    'Some Custom Member Role',
    'administrator',
  );
  if (!array_intersect($user->roles, $roles_allowed_to_buy)) {
    // Display a help message.
    $form['help'] = array(
      '#markup' => t('You do not have permission to buy this product.'),
    );
    // Disable the whole form.
    $form['#disabled'] = TRUE;
    // Remove any submit button(s).
    unset($form['submit']);
  }
}

(that's an example you would put inside a module called custom_module)


How to change background color in my Tao subtheme We have a custom sub theme built on Tao and I tried adding

body {
  color:#fff;
  background:#333;
  }

to the style.css file, but to no avail. In Chrome dev tools I started inspecting elements and changing their backgrounds individually, but I cannot figure out how to change the background color for all divs, form elements, blocks, etc without some super complicated CSS.

I'm trying to avoid doing this, if possible:

#main-content {
  background: #333;
}

#page {
  background: #333;
}

#page-title {
  background: #333;
}

#branding {
  background: #666;
}

div.limiter {
  background: transparent;
}

div.region {
  background: #333;
}

span.fieldset-title {
  background: #333;
}

div.tabs {
  background: #333;
}

fieldset.collapsible {
  background: #333;
}

.collapsed .fieldset-legend a {
  background: #333;
  color: #fff;
}

Further, when implementing this code, I cannot get some divs to change color, for instance <div id="page-title">

It depends on the structure of the theme. If your can´t see any change after apply this, there are two possible reasons:

body {
  color:#fff;
  background:#333;
  }

There are other elements, like divs, upon your body elemnts.
The change that you made is not reflected on your site. Check if you are working in the correct css file. If it is a .sass file, maybe it needs to compile. Other reason for that, is for the cache, try to delete by going to admin/config/development/performance

Good luck!.


How do I test for node type to print a variable from template.php? In Drupal 7, you can use the following in template.php to test for the presence of a node type:

function MYTHEME_preprocess_node(&$variables) {
if ($variables['type'] == 'NODETYPE') {
***CUSTOM CODE****
}

In Drupal 7, you can use the following in template to create a variable which can be printed out in your page.tpl.php file:

function MYTHEME_preprocess_page(&$variables) {
      $variables['greeting'] = 'Custom Greeting';
}

But how do you combine the two, to create a variable inside of template.php (that can be printed in page.tpl.php) which changes according to the node type?

I would have thought the following would work:

    function MYTHEME_preprocess_page(&$variables) {
              if ($variables['type'] == 'NODETYPE') {
  $variables['greeting'] = 'Custom Greeting';
    }
    }

But it doesn't work. Why is this? (Using the same code on MYTHEME_preprocess_node also does not work).

Thanks for any help!

Each template has a different set of variables available. The variables available in a given theme is generally documented in the comment section at the top of the file. You can consult this documentation on http://api.drupal.org.

The node type is not directly available as a variable in the page.tpl.php. However, you have the $node object which has a type property:

function MYTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) && $variables['node']->type == 'NODETYPE') {
    $variables['greeting'] = 'Custom Greeting';
  }
}


Migrating a site with a module that doesn't have a version for latest core version I'm working on migrating a site from Drupal 7 to Drupal 8. All content and other things are migrated successfully excepts a module (the Field collection module) that is available for Drupal 7, but not for Drupal 8.

Please give guidelines if have any experience with it.

You simply cannot. If the module has a Drupal 8 version you can use it just after enabling the module. But if it doesn't contain a Drupal 8 version you cannot enable or use with your Drupal 8 site installation. Only thing you can do is find an alternative module for the unsupported module that you have used. Or you can change the unsupported modules codes with supported Drupal 8 syntaxes. But I never encourage to do so. Because

It effect authors copyrights.
You wouldn't be able to update anymore or if you update your module forcefully all the changes you have done will revert back to the original state.

So think twice before doing a change like that. Hope this helps for your question.


Migrating a Drupal Node.js website from localhost to web server Due to specific website feature requirements, which do not seem to be possible in Drupal 7 without Node.js integration, I am strongly considering to integrate Drupal 7 with Node.js modules offering real time interactivity. I understand the basic concepts however I have never actually used Node.js on a website before. I have installed Node.js on my computer under Program Files (Windows) and begun testing the integration with a test website on localhost (WAMP).

My concern is for when I later will need to migrate a client's website to an actual web server. I would like to ask those who have had some experience with such Drupal/Node.js integration, what is a streamlined workflow for migration. For example, I am wondering if Node.js should be installed into the same folder as the website directory instead of Program Files, so that when testing is finished I will be able to ftp the entire website directory with the Node.js installation without needing to reinstall Node.js and reconfigure everything. I am not sure if copying everything over would work or if Node.js needs to be installed again separately on the web server?

I would like to get a clearer understanding of this process before I make the leap into Node.js integration with future client websites. I believe Node.js integration introduces some great new features however it could potentially be a giant can of worms if not handled properly.

The typical NodeJS setup usually involves a Linux server and a nginx web server/proxy that delegates the requests to the application running on a specific/semi-random unprivileged port. In other words, nginx will have a site declaration (vhost) for your Drupal and a another site declaration for your NodeJS application. Your NodeJS application runs in the backgrounds and listens for requests from nginx.

NodeJS itself is usually installed through the Linux distribution's packaging system, similarly to PHP.

On the filesystem, I would treat the two applications as separate projects, in two separate directories on the server. It's pretty rare to find developers who have a good understanding both Drupal/PHP and NodeJS, so keeping it separate will make it easier for other people eventually working on that project to familiarize themselves with the environment.


How do I open up a YAML Form in a bootstrap modal window I have a form made in the YAML Form module and I would like it to open up in a bootstrap modal window.

Can I just put the Bootstrap html into my page.hmtl.twig file and print out the form somehow?

This would be sufficient for my purposes as I want to form to be accessible from all pages on the website.

If this is not the Drupal way could someone please point me in the right direction

The drupal way to do this would be to use blocks. The YAML Form module has the feature to put form in blocks. Place the form block in a region, where you want to have it on the page. Then style it in a block template:

block--my-form.html.twig

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

                {{ content }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


Hooks Alter not called in Template.php for I run into strange thing today. I have some custom hook declared in a custom module as following:

drupal_alter('strange_thing', $shared_var, $vars);

then in template file(template.php) I got the function:

function THEME_strange_thing_alter(&$shared_var, $vars){
    //do something with $shared_var
}

The THEME_strange_thing_alter() is called if i have unchecked " Use the administration theme when editing or creating content" in the admin/appearance in the "Administration Theme" section, but it is not otherwise.

To satisfy curiosity, I moved all the logic from tempalate.php into custom module/.module file and it works like expected...the hooks are called not matter if the box is checked or unchecked for " Use the administration theme when editing or creating content"

It would be great that the hooks work in template.php no matter if there is some box checked or unchecked in the UI. Is there way to make it so? Thank You

Hooks are only invoked for enabled modules, and the current theme. So code in template.php for theme1 won't be used when theme2 is active (unless theme2 is a subtheme of theme1, thanks @greggles).

The reason is obvious when you think about it: if you've explicitly said you want one theme on a certain page, code from another theme shouldn't be allowed to interfere. It could cause all sorts of problems.

If you have code that should run independently of the theme that's being used to display the page, the proper (and only) place to put it is in a module.


How can I filter specific user on Views list? Using Views 3.

I have User view and here, list all user by post count. It's working. But I want, ignore admin user post count in this view. How can I filter my views to not show admin in the view list?

Add a filter criteria of type User: Roles,
Select the operator Is none of:
Select Administrator from the listbox.
Save the settings

This will block the display of all the users with role as administrators. If you only want to limit a certain user you can select the filter criteria of User: Name, or User: The User ID, whatever suits you.


Attach a handler to the "event" of autocomplete select with jQuery I'm using Views Autocomplete Filters on an exposed node title field. I would like to attach a handler to the "event" when the user selects one element from the autocomplete list without applying this patch which would actually trigger a "real" event.

For the simplest example: if the user has selected one element from the autocomplete list, show an alert() message. (I wouldn't do that because it's ugly, but it's the easiest demonstration of the solution.)

I had a similar issue with a Drupal autocomplete field I had created, where I wanted the form submitted when an item from the dropdown was selected.

This blog post addressed the issue for me:  http://othermachines.com/blog/smart-autocomplete-navigation-drupal-7

The relevant JQuery code you'll want to look at on that page is this:

(function ($) {

  Drupal.behaviors.programmeSearch = {
    attach: function (context) {

      $('#edit-autocomplete-field').focus(
        function(){
          $(this).val('');
      });

      $("#edit-autocomplete-field", context).bind('autocompleteSelect', function(event, node) {

        var key = $(node).data('autocompleteValue');
        var label = $(node).text();

        // If matches found...
        if (key != '0') {

          // Set the value of this field.
          $(this).val(label);

          // Redirect user to entity path.
          window.location = Drupal.settings.basePath + key;
        }
        else {

          // If no matches, reset.
          $(this).val('');
          $(this).focus();
        }
      });
    }
  };

})(jQuery);

You probably won't need all of that code.  Whatever you want to happen on the select event, put in the condition beginning with if (key != '0') {


Move file to specific folder after upload in forum I am using Drupal 7 with Organic Group and Forum Module.

I have added facility to attach files in Forum posts. Now after forum(node) is submitted, I would like to move the file (which is with forum node) to specific folder.

Actually I would like to move/copy to other folder during node submit only, is is possible with hook_node_submit()

Here is how I implemented it using hook_node_insert() function.

function modulealter_node_insert($node) {
    // See if a file has been added
    if ($file_items = field_get_items('node', $node, 'field_file_attachment')) {
        // Get the first file item
        $file_item = array_shift($file_items);

        // Load the file object from the cache/database
        $file = file_load($file_item['fid']);

        // The path to the file is in $file->uri
        //var_dump($node->group_audience['und']['0']['gid']);

        //Set the destination folder where do you want to move it
        $destination = "private://filedepot/filedepot/test/".$file->filename;
        $file = file_copy($file, $destination, FILE_EXISTS_REPLACE);
    }
}


How to create a empty module? What is the most basic valid module one can create in Drupal?

It would be useful to have a simple blueprint available, for anyone just getting started with Drupal.

The below instructions allows one to create an empty module, and is helpful for anyone just getting started with module building. If you have troubles getting your first module working, or even showing up in Drupal, ensure you've read all the instructions below.

Drupal 8

A project must at least have

A machine name.
An yaml info file named after the machine name, in the form module-machine-name.info.yml with the following attributes:

name: A humanly readable name
type: A type, defining to be a module.
core: The major Drupal core version the module is compatible with, 8.x, in this case.

An empty module file, name in the form module-machine-name.module

Drupal looks for modules in these locations, as seen from the web root:

/modules/
sites/[example.com]/modules
sites/default/modules
profiles/[install-profile]/modules

Technically, Drupal also looks for modules in core/modules, but one should never, place modules there, hence it's not on the list above.

An example module structure, for a module with the machine name helloworld, would look like this:

/modules/helloworld/helloworld.info.yml

/modules/helloworld/helloworld.module

Notice that both the info and module file as named exactly the same as the machine name, which is important.

The module file may be empty, but the info file must contain a few minimum values for Drupal to recognize it as a module. For our helloworld module, that could look like:

name: 'Hello world module to demonstrate module building'
core: 8.x
type: module

If you follow the above instructions, you should be be able to get a new module listed in your Drupal site, although it won't do anything, at this stage.

Drupal 7

A module must at least have

A machine name.
A humanly readable name
An info file named after the machine name.
An empty module file.

To be loadable by Drupal, it must also define which core version it is compatible with.

Further Drupal looks for modules in these locations:

sites/all/modules/
sites/[example.com]/modules
sites/default/modules
profiles/[install-profile]/modules

Technically, Drupal also looks for modules in modules, but one should never, place modules there, hence it's not on the list.

An example module structure, for a module with the machine name helloworld, would look like this:

sites/all/modules/helloworld/helloworld.info

sites/all/modules/helloworld/helloworld.module

Notice that both the info and module file as named exactly the same as the machine name, which is important.

The module file may be empty, but the info file must contain the humanly readable name of the module, and the core version the module is compatible with.

For our helloworld module, that could look like:

name = Hello world module to demonstrate module building
core = 7.x

If you follow the above instructions, you should be be able to get a new module listed in your Drupal site, although it won't do anything, at this stage.


block_admin_display_form_submit not getting called I am having trouble saving my block regions(admin/structure/blocks).

Problem:
I am doing my thing on block admin page, saving blocks, moving them around and what not. but the changes i make are not being saved.

What i found: after some debugging efforts, i figure out that the function *block_admin_display_form_submit* is not called when the block form submits.

the site i am having problem is on a lamp server somewhere. i have another copy of this site on my local machine, which has no problem saving block regions.

any idea on how to fix this? thank you.

I'm having the same issue, I cannot call function block_admin_display_form_submit($form, &$form_state).

I've set a custom variable that should be updated if I change block region.

Everything works if I do it from the block edit page(admin/structure/block/manage/menu_block/ID/configure), but if I try to do it in the block admin display form (admin/structure/block), It will not work.

I've tried to increase max_input_vars with no success.

Have you solved it?


Views UI affected due to multiple modules jquery.once is perfectly working, I placed console.log inside it, but I still get this error especially when I load the Views UI without even before I press any button

When I press any button, a progress animation appears and again this error appears

views-admin.js?op2hqg:164 Uncaught TypeError: $form.once is not a function
    at Object.Drupal.behaviors.addItemForm.attach (views-admin.js?op2hqg:164)

When I investigates I found that the following jquery select returns 0 objects

var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();

How to solve this, should I disable any modules?

This might happen when you use jQuery Update, I faced the same and solved using CDN providers

Use jQuery CDN Provider in your jQuery Update Settings should solve this issue

Load your settings as yoursite.com/admin/config/development/jquery_update, You will see the option jQuery and jQuery UI CDN with None in the dropdown list.

Choose jQuery and Save Configuration


Using hook_form_alter(), how do I write a multi-select field? So I have a field that displays locations a list of multi-select locations.

The select has a name of field_location

I want to turn access to this off, and then rebuild the field with a limited list of  locations that I will populate.

function rm_report_form_alter(&$form, &$form_state){
    if (arg(0) == 'node' && $form['form_id']['#value'] == 'c_node_form') {
        $form['field_location']['#access'] = FALSE;
    }
}

The problem:  Not sure how to rewrite a multi-select field.

I think you are searching for the #multiple attribute:
multiple
Used by: select
Description: Indicates whether the user may select more than one item.
Values: TRUE or FALSE
<?php
return array(
  '#type' => 'select',
  '#title' => $title,
  '#default_value' => $value,
  '#options' => $options,
  '#description' => $description,
  '#multiple' => $multiple,
  '#size' => $multiple ? min(12, count($options)) : 0,
  '#weight' => -15,
);
?>


How do I alter the route defined by another module? In other words, what is the Drupal 8 equivalent of hook_menu_alter()?

Drupal 8 still uses hook_menu(), but for what I can see, the information returned by the hook is different from what the hook returned in Drupal 7. For example, the definition given in user_menu() for user is the following.

  $items['user'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'weight' => -10,
    'route_name' => 'user_page',
    'menu_name' => 'account',
  );

The route_name property links to an entry in the user.routing.yml file.

user_page:
  pattern: '/user'
  defaults:
    _content: '\Drupal\user\Controller\UserController::userPage'
  requirements:
    _access: 'TRUE'

This is different from what done with Symphony, and it confuses me about how a module can alter the route defined from another user.

The only function that is still invoking hook_menu_alter() is menu_router_build(), but that function still contains code that needs to be updated, since it is still using the now deprecated drupal_alter().

  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);
  foreach ($callbacks as $path => $router_item) {
    // If the menu item is a default local task and incorrectly references a
    // route, remove it.
    // @todo This may be removed later depending on the outcome of
    // http://drupal.org/node/1889790
    if (isset($router_item['type']) && $router_item['type'] == MENU_DEFAULT_LOCAL_TASK) {
      unset($callbacks[$path]['route_name']);
    }
    // If the menu item references a route, normalize the route information
    // into the old structure. Note that routes are keyed by name, not path,
    // so the path of the route takes precedence.
    if (isset($router_item['route_name'])) {
      $router_item['page callback'] = 'USES_ROUTE';
      $router_item['access callback'] = TRUE;
      $new_path = _menu_router_translate_route($router_item['route_name']);

      unset($callbacks[$path]);
      $callbacks[$new_path] = $router_item;
    }
  }

Allow views to override existing routing items just uses existing functionality.
If you want to change the information attached to a route, not the menu,
like the actual used controller, or the requirements (permission/role etc.)
you can use an event provided by Drupal:
  <?php

  use Drupal\Core\Routing\RouteBuildEvent;
  use Drupal\Core\Routing\RoutingEvents;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class RouteSubscriber implements EventSubscriberInterface {

   /**
    * {@inheritdoc}
    */
   public static function getSubscribedEvents() {
      $events[RoutingEvents::ALTER] = 'alterRoutes';
     return $events;
   }

  /**
   * Alters existing routes.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The route building event.
   */
  protected function alterRoutes(RouteBuildEvent $event) {
    // Fetch the collection which can be altered.
    $collection = $event->getRouteCollection();
    // The event is fired multiple times so ensure that the user_page route
    // is available.
    if ($route = $collection->get('user_page')) {
      // As example add a new requirement.
      $route->setRequirement('_role', 'anonymous');
    }
  }

  }

Additionally you have to register a service with the tag 'event_subscriber' for this class.


Progress bar in drupal admin area for long running scripts I have a custom module that has visual representation in admin area of my Drupal 7 installation.

Script that runs via that module executes pretty long time (some syncing process), and i would like to implement some kind of Progress bar (like when you run some cron job etc in Drupal, you see progress bar and even messages of the script parts).

How i can implement this ? Basicially, i would like to track a foreach loop, and iteration through foreach loop would be visible as progress bar.

Script is being triggered via hook_form_submit.

Thanks!

Grab a copy of Examples and checkout the batch_example module.

It's got several code examples for various scenarios using the batch API, which Drupal uses internally to produce pages with progress bars (like the upgrade check page for example). The module is very well commented, and it should give you everything you need to get started.


Drupal custom page template based on the title of the page I have the following page:

About us

Whose path is:

site.com/node/6

Theme suggestions for the template files are:

page--node--6.tpl.php
page--node.tpl.php

You should already know that it is too weird to create custom template files based on the node's id, thus I like to have my custom page template based on the page's title (of course, converted to machine name, for instance "About us" to be "about-s"). What should I do?

I don't think this is an optimal solution at all, because node titles can easily be changed (and duplicated), but here you go:

function MY_THEME_preprocess_node(&$vars) {
  // This assumes that you are using Pathauto for generating clean URLs.
  // Get the "clean" title.
  $title = pathauto_cleanstring($vars['node']->title);
  // Replace all dashes with underscores. This is necessary for recognizing the
  // template filenames.
  $title = str_replace('-', '_', $title);
  // Add new template variation.
  $vars['theme_hook_suggestions'][] = 'node__' . $title;
}

Note: to make this bulletproof for different languages, alphabets and special characters, make sure you have the Transliteration module installed and set to transliterate strings prior to creating URL aliases. This way if a node title has non-standard character (e.g. Č) it will be transliterated to Latin alphabet (in this case C).


Grouped exposed filter is not available I'm trying to create a filter within a view, which has multiple ranges;

i.e.

0-99
100-399
400-699
700-1000

I have seen this before when you Add filter criteria, you can select grouped exposed filter and I can set up the ranges in there. But in this instance, this option is not there and I'm not sure why not.

In the drupal code I found Drupal API which counts the options in $this->operator_options() - But I don't know what $this->operator_options() is meant to contain, or how you go about adding items to it through the back-end.

Did you try Facet API filters? check the Facet API module

The Facet API module allows site builders to easily create and manage faceted search interfaces. In addition to the UI components that come out of the box, themers and module developers can build their own widgets that can optionally be contributed back to Drupal.org. Facet API works with the core Search, Search API, and Apache Solr Search Integration modules (including Acquia Search) meaning that code and configuration can be reused as-is with the most popular search solutions available to Drupal. Refer to the documentation for more details.


Pre-Populate Dropdown in WebForm from link I have a Drupal 7 webform with a dropdown list of Products
 - Product A
 - Product B
 - Product C
 - etc...

I want to place a button link on another page "How to Buy Product A" that will bring up the webform with Product A selected in the dropdown.

The Field Key in the Webform for the dropdown is: railing_system_model

Do I just add something to the link URL??

I have no idea where to begin, is there a module that will do this?

Regards,

John

hook_form_alter() or hook_form_form_id_alter() is what you're looking for here.

First your link how ever it's constructed should have a query parameter kind of like "/webformurl?product=a". This would be a link back to your webform.

In one of the hook form alters, you'd check for the value in the url if it doesn't exist do nothing. If it does change the default value for the form field.

If you're not sure how to alter the field on your form maybe check out this link for additional details - Programmatically modifying a webform with hook_form_alter()


Add html to wrap views programaticly I need to wrap field in views. I use views with module Responsive grid and have this html.

Responsive html

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.

I want to have this html

Responsive html

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.

I know that i should use this function hook_preprocess_views_view, hook_preprocess_views_view_fields or hook_preprocess_views_view_field but i don't know how to do it correctly.
So how can i have this html without creating *tpl.php file

It can be done in the views admin interface in the next way:

Exclude existing fields from display
Add new field Global: Custom text
Display new fields in Custom text filed using tokens

See example


Commerce Extra Pane wont drag in checkout UI I have created a Drupal Commerce pane using the Commerce Extra Panes module. I created a group and field and they show up on the UI. However, its listed in the Disabled section. I tried to drag it into the Checkout pane and when I save it reverts back to the Disabled section.

When I look in the database it does list it correctly in the Checkout pane, but it doesn't actually appear on any page pane.

What is happening here and what can I do to debug more?

It looks a bit odd, but the only thing I can come up without more information is that you might have the node disabled in the commerce extra panes tab:

If that's not the case, try also to disable the js in the checkout configuration form, click on "show row weights" so you can select the page for each pane without dragging and dropping.


How to create a views display that is not a block or a page? I often use views_embed_view() in various places. I find myself creating views with multiple displays, each with slightly overridden settings for different purposes. I end up creating a lot of "Block" displays just because I need multiple displays. But I don't actually need it to provide a block, and I don't want all of those blocks cluttering up my system.

My question: is there a "generic" display (like Master) that I could use to create multiple displays without resorting to "block" or "page" displays?

May be you can create Attachments for the view.


Put eform's label and textfield(input) separate I'm working on creating a table with eForm in Drupal 8.

Since label and textfield(input) stick together, can I insert label and textfield(input) into separate <td>?

The Render API, similar in Drupal 7, allows you to add a #theme property to use a hook_theme defined template. The theme definition should use "render element", and that will be available in the template preprocess function. The way that it's usually done is to modify or create the render array in the preprocess function, and set #theme to table (in Drupal 7 calling theme('table') was possible).

Edit: Removed second paragraph which referred to modifying the theme.


Translate View footer I'm trying to translate a link in footer on my views .
the code is :

<?php
$link = l(t('Click to view all the writing categories'), 'somewhere', array('attributes' => array('class' => array('read-latest'))));
print $link;
?>

The problem is after tranlate it from admin/config/regional/translate .
the output is <div> no link and no <a> tag .
Any idea ?

by this module String Overrides you can translate strings .
That's it


Contextual filter has no results when using entity translation of non default language I have a view that shows content with an entity reference field referencing the currently displayed node.
This is a scenario often used, just a block (pane in my case) that shows content (child nodes) that belongs to the current node (parent node).

This uses the contextual filter (Content entity referenced from field_section_reference) Content: Nid
with 'provide default argument': content ID from URL'

The view is filtered with 'Field Language:Current user's language'

This works fine for the default site language, showing all content of the language (url language selection)
But when I use the language switcher, the view does not show anything any more. Translated content of current language is not shown.

I removed the contextual filter and added a normal filter, selecting manually a language other than the default site language. This worked, translated content shows fine.

If you are reading this and have entity translation enabled in a similar setup, please do me a favor and test if I'm right. I have spend quite some hours trying to find alternatives and workarounds, but can't display a view of translated content that is referencing the currently displayed node, when using a not-default language.

not sure if I had the exact problem, but I solved my views / ET woes by adding 'entity translation' relationship. then you can filter by 'entity translation: language' and then select to user the user's current language. hopefully this helps!


Properly override template_preprocess_book_navigation function in Drupal 8 Book module I'm trying to find what is the proper way to override the template_preprocess_book_navigation function from the Drupal 8's core Book module. I want to add only two lines (bolded), but don't know how this should be done in "Drupal 8 way". Should I create a custom module or add something in the mytheme.theme file?
Thank you and be healthy!

function template_preprocess_book_navigation(&$variables) {
  $book_link = $variables['book_link'];

  // Provide extra variables for themers. Not needed by default.
  $variables['book_id'] = $book_link['bid'];
  $variables['book_title'] = $book_link['link_title'];
  $variables['book_url'] = Url::fromRoute('entity.node.canonical', ['node' => $book_link['bid']])->toString();
  $variables['current_depth'] = $book_link['depth'];
  $variables['tree'] = '';

  /** @var \Drupal\book\BookOutline $book_outline */
  $book_outline = \Drupal::service('book.outline');

  if ($book_link['nid']) {
    $variables['tree'] = $book_outline->childrenLinks($book_link);

    $build = [];

    if ($prev = $book_outline->prevLink($book_link)) {
      $prev_href = Url::fromRoute('entity.node.canonical', ['node' => $prev['nid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'prev',
        'href' => $prev_href,
      ];
      $variables['prev_url'] = $prev_href;
      $variables['prev_title'] = $prev['title'];
    }

    /** @var \Drupal\book\BookManagerInterface $book_manager */
    $book_manager = \Drupal::service('book.manager');
    if ($book_link['pid'] && $parent = $book_manager->loadBookLink($book_link['pid'])) {
      $parent_href = Url::fromRoute('entity.node.canonical', ['node' => $book_link['pid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'up',
        'href' => $parent_href,
      ];
      $variables['parent_url'] = $parent_href;
      $variables['parent_title'] = $parent['title'];
      $variables['prev_depth'] = $prev['depth'];
    }

    if ($next = $book_outline->nextLink($book_link)) {
      $next_href = Url::fromRoute('entity.node.canonical', ['node' => $next['nid']])->toString();
      $build['#attached']['html_head_link'][][] = [
        'rel' => 'next',
        'href' => $next_href,
      ];
      $variables['next_url'] = $next_href;
      $variables['next_title'] = $next['title'];
      $variables['next_depth'] = $next['depth'];
    }
  }

  if (!empty($build)) {
    \Drupal::service('renderer')->render($build);
  }

  $variables['has_links'] = FALSE;
  // Link variables to filter for values and set state of the flag variable.
  $links = ['prev_url', 'prev_title', 'parent_url', 'parent_title', 'next_url', 'next_title'];
  foreach ($links as $link) {
    if (isset($variables[$link])) {
      // Flag when there is a value.
      $variables['has_links'] = TRUE;
    }
    else {
      // Set empty to prevent notices.
      $variables[$link] = '';
    }
  }
}

You can put a template_preprocess() function in a custom module or your theme mytheme.theme file.
It depends on what you want to achieve.
If this preprocess function is specific to the theme (for example, the results are used in a theme template), then you should put it in mytheme.theme.
But, if you put the code in mytheme.theme and then change themes, your book navigation will no longer behave as expected.
So, if the preprocess function does general processing that you might want to use in multiple themes, and it doesn't do anything theme-specific, then it's better to put it in a custom module.  (This is probably your use case.)


How to create report to list users who change only specific field? I have a content type with several fields which are updated manually over time by different users.

Let's say, for example, the content type name is Ticket
and the fields in this content type are:

Ticket Status
Ticket Resolved Date
Ticket Escalation Date (default empty)

Every time a user changes a field, a revision is created automatically.

How can I create a report (using the Views module) to list the users who only change the field "Ticket Escalation Date" from empty to some value?

Note: The site exists for quite some time already and contains data. So a report about these cases that were created in the past is needed also, based on the current design and existing data.

Part 1 - Intercept these cases from now on

If you're willing to also consider using the Rules and Flag module, then it'll be a peace of cake to use Views for creating the view you're looking for. Below are the main steps to do so ...

Step 1: Create a flag to prepare for reporting such users

Using the Flag, create a non-global flag that will be used to get the users flagged that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value).

Step 2: Use Rules to flag such users

Using the Rules module, create a rule to "automatically flag users" that fit your specs (= users who only change the field "Ticket Escalation Date" from empty to some value). Here are the specs of such rule:

Rules Event: after updating content (of type = ticket)
Rules Condition: only the field "Ticket Escalation Date" was changed from empty to some value (this will need some refinements from your part to actually specify such condition, refer to (*) for some guidance on this).
Rules Action: flag such user (with the flag from step 1). But make sure to use the userid of the updater, which may be different from the node author ... Probably you want to use "current user".

(*): Some more details on those Rules Conditions (ALL conditions must apply):

Add an "entity has field" (with field = Ticket Escalation Date), to make that field available in your rule. If such field (machine name) is only used for "tickets", then there is no need in the Rules event to refine with the "(of type = ticket)".
BEFORE saving the content (= value before the edit started) "Ticket Escalation Date" is blank.
AFTER saving the content (= value after the edits will have been saved) "Ticket Escalation Date" is NOT blank.
"Ticket Status" is unchanged (value BEFORE saving is equal to value AFTER saving).
"Ticket Resolved Date" is unchanged (value BEFORE saving is equal to value AFTER saving).

Step 3: Create your view

Using the Views module, create a view of "users", which were "flagged" with the flag from Step 1.

Part 2 - Report about similar cases in the past

What is explained in Part 1 can be used as a solution if it was put in place from the beginning (when the site was launched), or to intercept these cases from now on. For existing sites, you could "report" about similar cases using a custom SQL query (based on the current design and content of your Drupal tables), combined with using the Forena module (disclosure: I'm a co-maintainer of it). This module comes with quite some Community documentation. Here is a summary of this module:

  Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

  Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

  Visit the Forena HowTos page for some links (near the bottom) to some , and there is a live demo site of it.

Assume you have a query which looks like so (as in your comment to this answer):

  SELECT r.title, u.name
FROM field_revision_field_expedite_date re, node_revision r, users u
WHERE r.nid=re.entity_id and r.vid=re.revision_id and u.uid=r.uid
GROUP BY re.entity_id
HAVING min(revision_id)

It'd be straight forward to transform the query results of this SQL in a report (and/or even chart if you'd want ...). Refer to the example in my answer to "How to retrieve data directly from a Drupal database" to get an idea of what it is like to use Forena, such as the SQL query and the source of the "custom report" there.

PS: not sure what you'd want to "do" with such list (created as explained in "Part 1"), but if at some point you want to reset/re-init such list, you could do so easily using the VBO module also (= unset the flag for all users in my View).