# Question
Title: Make quiz link look like a button or apply css style
I have rendered the quiz entity teaser display into a content type and would like to know how to apply a css class to the "download certificate" and "take quiz" links.

Usually this would be done by editing the content type display, and in this case, the teaser for the quiz. The only options I am given is to show or hide the link.

Furthermore, I can't find the settings for the "download certificate" link, which doesn't show up in the display settings at all. They are called buttons but do not look like buttons.

What I've tried:

* looking for the settings where I can apply CSS to these buttons.
* used Chrome browser inspection tool to see that there is a style class already being applied to `a href`, called `quiz-start-link`; I tried creating some custom css for both `a.quiz-start-link` and just `.quiz-start-link` to no avail.

Would I just need to figure out how to harness `quiz-start-link` or can I edit this to apply my own?

# Answer
I just needed to apply custom CSS to `a.quiz-start-link` and `.certificate-link` respectively and then it worked.

I also learned about templates and this SE Post was helpful for creating a custom template for quizzes, so I could change the class that was being used like I originally wanted to: How to theme a quiz in D7?
> 0 votes

---
Tags: 7, quiz
---


# Question
Title: How do I stop the site content from being internally indexed?
I have a Drupal 6 website, which is indexing the content for internal use. I don't use the Search module to search in the nodes, but The Search module is installed and enabled, since it seems to be required by the Google CSE module.

Is there anyway to stop Drupal indexing the content of the site?

# Answer
> 0 votes
Go to admin/settings/search and set "Number of items to index per cron run" to 0.

---
Tags: 6, search
---


title: I log in and then I am anonymous?

text:
# Question
Title: I log in and then I am anonymous?
I've been trying to debug an app where I am utilising ajax and trying to post content via services. However, I can't. What am I missing?

```
 $.ajax({
      url: 'http://7.webcinizim.com/services/user/token.json',
      type: 'post',
      dataType: 'json',
      success: function(token) {
        console.log(JSON.stringify(token));
        $.ajax({
            url: 'http://7.webcinizim.com/services/user/login.json',
            type: 'post',
            dataType: 'json',
            data: {
              username: "tolga",
              password: "tolga123"
            },
            success: function(user) {
              console.log(JSON.stringify(user));
              $.ajax({
                url: 'http://7.webcinizim.com/services/node.json',
                type: 'post',
                dataType: 'json',
                data: 'node[type]=page&node[title]=Hede',
                success: function() {
                  console.log("Node created");
                },
                error: function(err) {
                  console.log(err);
                }
              });
            });
        }
      });
  }
});

```

UPDATE: My query looks like this now and I am getting Invalid JSON:

```
$.ajax({
  url: 'http://7.webcinizim.com/services/user/token.json',
  type: 'post',
  dataType: 'json',
  success: function(token) {
    console.log(JSON.stringify(token));
    localStorage.setItem("token", token.token)
    $.ajax({
      url: 'http://7.webcinizim.com/services/user/login.json',
      type: 'post',
      dataType: 'json',
      data: {
        username: "tolga",
        password: "tolga123"
      },
      success: function(user) {
        console.log(JSON.stringify(user));
        $.ajax({
          url: 'http://7.webcinizim.com/services/node.json',
          type: 'post',
          dataType: 'json',
          data: {
            "node[type]": "page",
            "node[title]": "Hede"
          },
          headers: {
            "X-CSRF-Token": localStorage.getItem("token"),
            "Content-Type": "application/json"
          },
          success: function() {
            console.log("Node created");
          },
          error: function(err) {
            console.log(err);
          }
        });
      },
    });
  },
});

```

# Answer
> 1 votes
When using Services after login request in response You should get a X-CSRF-Token. You have to use it in header of next requests to keep "being logged in".
It should be in header for second (and all possible future) requests like:

```
headers: {
    "X-CSRF-Token":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    "Content-Type":"application/json"
}

```

---
Tags: ajax, services
---


# Question
Title: Best Way to Handle Variables Per Environment
I have a custom module. It's FormBase to create a form. And on submit, I post values to an API. All this works. But I want to change the base URL variable (which is used in multiple methods) so that when you on any environment besides live you get a different URL.

I want to figure out the Drupal 8 way of doing this.

```
class EventSuggestionForm extends FormBase {
  // Needs to be different if not the live site...
  private $baseUrl = 'https://www.example.com';
  private $apiUrl = '/api/v1/';
...

```

Can I get some advice?

# Answer
You can create a new setting in your `settings.local.php` or `settings.php` file like:

```
$settings['event_base_url'] = 'https://www.example.com';

```

or some people are adding switch block based on the server host, e.g.:

```
switch (@$_SERVER['HTTP_HOST']) {
  default:
  case 'dev.example.com':
     $settings['event_base_url'] = 'http://dev.example.com';
     break;
  case 'stage.example.com':
     $settings['event_base_url'] = 'https://test.example.com';
     break;
  case 'www.example.com':
  case 'preprod.example.com':
     $settings['event_base_url'] = 'https://live.example.com';
     break;
}

```

Then reference it in the code like:

```
use Drupal\Core\Site\Settings;
$baseUrl = Settings::get('event_base_url', '');

```

So your code would look like:

```
use Drupal\Core\Site\Settings;
class EventSuggestionForm extends FormBase {
  private $baseUrl;
  private $apiUrl = '/api/v1/';

  function __construct() {
    // Read value from the settings file.
    $this->$baseUrl = Settings::get('event_base_url', '');
  }
...

```

Then change this setting per environment in the settings file, similar as you've different database credentials per different environment. This is the same concept as it's used for the existing `$settings['file_public_base_url']` parameter.
> 14 votes

---
Tags: 8, configuration
---


# Question
Title: How to insert Google Tag Manager code into pages with variable account value
I need to insert the Google Tag Manager snippet code into each page just after the opening `<body>` tag. This is fine, except I would also like the user to specify the account number in an admin form, so what is put in this form will be output in the snippet.

In the snippet, the account number is required twice:

```
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=<ACCOUNT NO HERE>"
...
(window,document,'script','dataLayer','<ACCOUNT NO HERE>');</script>

```

Setting up the admin form and storing and retrieving it by `variable_set()` and `variable_get()` is no problem, but what's the best way to insert it into the template?

My thought is to use `hook_preprocess_page()`, but I'm not sure if this is the right hook to use, and if it is - what part of the array I would need to change to get this to appear? Or would a better way would be to make a variable available to the `tpl.php` file and insert it there? In which case, how would this be achieved? Thanks!

# Answer
> 2 votes
you should use these two modules:

https://www.drupal.org/project/google\_tag

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

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

User Id is part of default data added to dataLayer by data layermodule on each page, so you'll have it there.

Regarding your noscript part, you'd have to alter the module i think.

# Answer
> 0 votes
Bala, I think it would be best to update `html.tpl.php` in the appropriate `<head>` (script) and `<body>` (noscript) positions. This is where our GTM code is located, and it appears on all pages.

Typical location is `.../sites/all/themes/<theme-name>/templates/html.tpl.php`

Regarding how to make the variable available, perhaps this info from the header of `html.tpl.php` will provide all the information you need:

```
* Complete documentation for this file is available online.
* @see https://drupal.org/node/1728208

```

---
Tags: 7, theming
---


# Question
Title: Exposed filters of a view printed in different places
How can I get a view to expose filters that are drunk rendering separately.

Have three filters exposed but I do not know how to get it to fit the layout correctly.

Is it possible to achieve this type of layout with drupal 7?

I have an image that explains:

Thanks.

# Answer
> 0 votes
My first instinct would be to create a custom template for that specific View. However, based on the screenshot, it looks like you only want to move 2 of the 3 exposed filters to the side.

Had you wanted to move all of the exposed filters to the side, it likely could have been done with a custom views-view.tpl.php file.

Perhaps give the Better Exposed Filters a try!

I haven't personally tested this module, but a Google search lead me to this. Hope this helps.

# Answer
> 0 votes
in "exposed form settings" on third column in views ui, select: display as a block: yes, then configure the block in blocks admin page (or panels if you are usuing it) to display it in your page. BEF module is a good one, try with and without it.

---
Tags: 7, views
---


# Question
Title: REST Services module - Access denied for user anonymous
I'm Using `Drupal 7`, I installed `Services` module with all the requirements, according to this question and this video.

I'm trying to get all users with Postman where I give my credential, but I'm getting back that I'm an anonymous user.

1. How do I pass my credentials?
2. How to add a filter to that call ,for example get all users with specific role?

# Answer
You need to make the user login who have the permission to view the list of user details using following Service API

```
http://yourdomain/endpointname/user/login

```

with follwing json data as arguments

```
{
"username":"username of the user who have the permission to view the users list",
"password":"password which matched with username"
}

```

After the successful login you need to get the CSRF token which will play the key role in all authenticated request. To get the token call the below mentioned API,

```
http://yourdomain/endpointname/user/token

```

You will receive a token, then add the token to your postman header for the key named **X\_CSRF\_TOKEN**. Then you can start to make the authenticated requests.
> 3 votes

# Answer
As per latest changes... Please follow this thread.

And most important **token key** should be **X-CSRF-Token**.

It can be achieved from below URL also.

```
http://somehost/services/session/token

```
> 1 votes

# Answer
Worth mentioning that now you'd also have to set the following header:

```
Name     Value
Cookie   [session_name]=[sessid]

```

You'll be finding the values for session\_name and sessid in the login response, right before the token-value for your X-CSRF-Token.
> 1 votes

# Answer
If you're looking to list your users you should create a view in drupal and choose the type to display as users. You can't show lists otherwise from the rest api unless you first create a view to display the list. The other points only let you create,edit, or delete them.
> 0 votes

---
Tags: 7, services
---


title: Programatically use search api

text:
# Question
Title: Programatically use search api
I want to do something like this

```
    $index = search_api_index_load("node_index");
    $myQuery=new SearchApiQuery($index);
    $myQuery->condition('type', 'blog', '=');
    $data=$myQuery->execute();
    $results=$data['results'];
    print_r($results);

```

but for Drupal 8, using the search api. Is that possible?

# Answer
```
$query = Index::load('my_index')->query();
$query->addCondition('search_api_language', $language);
$query->keys($search_string);
$query->range(0, 25);
$data = $query->execute();

```

Also I have a custom parsing function for the results:

```
function parse_results(array $results) {
$list = [];
  foreach ($results AS $item) {
    // The pattern is "entity:[entity_type]:[entity_id]:[language_code]".
    // For example "entity:node/1:en".
    $data = explode(':', $item->getId());
    $data = explode('/', $data[1]);
    $list[] = $data[1];
  }
  return $list;
}

```
> 8 votes

# Answer
Here is a gist of an idea I was working on a few months ago. Basically a custom module has a router (i.e. /search) and this handles it. I had not yet moved to the point of implementing a custom search form, but this got me to a starting point of a page with results, and a pager.

```
namespace Drupal\velirsearch\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\velirsearch\Service\PagerService;

class SearchResults extends ControllerBase {

  /**
   * @var \Drupal\velirsearch\Service\PagerService
   */
  private $pager_service;

  /**
   * SearchResults constructor.
   * @param \Drupal\velirsearch\Service\PagerService $pager_service
   */
  public function __construct(PagerService $pager_service) {
    $this->pager_service = $pager_service;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    $pager_service = $container->get('velirsearch.pager_service');
    return new static($pager_service);
  }

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   * @return array
   */
  public function build(Request $request) {
    /* @var $search_api_index \Drupal\search_api\IndexInterface */
    $index = $this->getSearchIndex('new_solr_test');

    // Create the query.
    $query = $index->query([
      'limit' => 10,
      'offset' => !is_null($request->get('page')) ? $request->get('page') * 10 : 0,
      'search id' => 'velirsearch:1',
    ]);

    if (!is_null($request->get('keyword'))) {
      $query->keys(['body' => $request->get('keyword'), '#conjunction' => 'AND']);
    }

    $results = $query->execute();

    $output = '';

    foreach ($results as $result) {
      $value = $result->getField('view_mode_teaser')->getValues();
      $output .= $value[0];
    }

    $render[] = [
      '#markup' => $output,
      '#type' => 'remote',
    ];

    $render[] = $this->attachPager($results->getResultCount(), 10);

    return $render;
  }

  /**
   * Title callback.
   *
   * @param Request $request
   *   The request.
   *
   * @return string $title
   *   The page title.
   */
  public function title(Request $request) {
    if (!is_null($request->get('keyword'))) {
      return $this->t('Search results for %keyword', ['%keyword' => $request->get('keyword')]);
    }

    return $this->t('Search results');
  }

  /**
   * Load and return a search index.
   * @param $id
   * @return \Drupal\Core\Entity\EntityInterface|null
   */
  protected function getSearchIndex($id) {
    return $this->entityTypeManager()->getStorage('search_api_index')->load($id);
  }

  /**
   * Convenient method to obtain a pager to attach from the pager service.
   * @param $totalRows
   * @param $limit
   * @return array
   */
  protected function attachPager($totalRows, $limit) {
    return $this->pager_service->getPager($totalRows, $limit);
  }
}

```

The `attachPager` method simply returns:

```
pager_default_initialize($totalRows, $limit);
return ['#type' => 'pager'];

```

I was separating it out in case I wanted to build more than 1 custom search without duplicating old pager code.

Also note that I am simply concatenating the value of a record in Solr as my result, I am storing view mode renderings in Solr. You would likely have to render them on the fly unless you did the same.

This was also done in a version of Search API that is not current, YMMV. But it did work for me.
> 7 votes

# Answer
The official document is here: Executing a search in code

> The following shows how to execute a Search API search programmatically, with some example code:

```
$index = \Drupal\search_api\Entity\Index::load('INDEX_ID');
$query = $index->query();

// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  ->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);

// Set fulltext search keywords and fields.
$query->keys('alea iacta');
$query->setFulltextFields(['title', 'name', 'body']);

// Set additional conditions.
$query->addCondition('status', 1)
  ->addCondition('author', 1, '<>');

// Add more complex conditions.
// (In this case, a condition for a specific datasource).
$time = \Drupal::service('datetime.time')->getRequestTime();
$conditions = $query->createConditionGroup('OR');
$conditions->addCondition('search_api_datasource', 'entity:node', '<>')
  ->addCondition('created', $time - 7 * 24 * 3600, '>=');

// Restrict the search to specific languages.
$query->setLanguages(['de', 'it']);

// Do paging.
$query->range(20, 10);

// Set additional options.
// (In this case, retrieve facets, if supported by the backend.)
$server = $index->getServerInstance();
if ($server->supportsFeature('search_api_facets')) {
  $query->setOption('search_api_facets', [
    'type' => [
      'field' => 'type',
      'limit' => 20,
      'operator' => 'AND',
      'min_count' => 1,
      'missing' => TRUE,
    ],
  ]);
}

// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('custom_search');

// Execute the search.
$results = $query->execute();

echo "Result count: {$results->getResultCount()}\n";
$ids = implode(', ', array_keys($results->getResultItems()));
echo "Returned IDs: $ids.\n";
$facets = $results->getExtraData('search_api_facets', []);
echo 'Facets data: ' . var_export($facets, TRUE);

```
> 4 votes

---
Tags: 8, search
---


title: Overriding field values in Drupal 8

text:
# Question
Title: Overriding field values in Drupal 8
I am attempting to override a node field value in Drupal 8 (on output) using template\_preprocess\_node. Specifically, I am attempting to override the text of a long text field. I am currently using this:

```
function THEMENAME_preprocess_node(&$variables) {
  $variables['content']['field_content'] = array(
    '#type' => 'markup',
    '#markup' => '<p>Testing 123</p>',
  );
}

```

And that works, but it totally overrides the field, removing the classes I added to the field wrapper, etc.

Does anyone know how to just set the value only, without replacing the entire field theming, etc? I do *not* want to manually add the field wrapper classes to #markup.

# Answer
After doing a quick test, turns out that **hook\_preprocess\_node** will always override **hook\_preprocess\_field**'s attributes.

Therefore, instead of adding the class in **hook\_preprocess\_field**, and if you don't want to use `'#markup'`, you could add it in **hook\_preprocess\_node** like this:

```
function THEMENAME_preprocess_node(&$variables) {
    $variables['content']['field_test'] = array(
    '#type' => 'processed_text',
    '#text' => 'Test 123',
    '#prefix' => '<div class="your-class">',
    '#suffix' => '</div>',
  );
}

```
> 2 votes

---
Tags: theming, hooks
---


title: How to use jQuery with Field?

text:
# Question
Title: How to use jQuery with Field?
I have Form alter for (loan) management.. If i want to add new loan i have to fill 3 fields .. (total\_amount - installment\_amount per month - installment\_num) as the following code ..

```
function custom_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'loan_node_form') {
    $total_amount           = $form['field_total_amount']['und'][0]['value']['#default_value'];
    $installment_amount     = $form['field_installment_amount']['und'][0]['value']['#default_value'];
    $installment_num        = $form['field_installment_num']['und'][0]['value']['#default_value'];
    $installment_num_res    = $total_amount/$installment_amount;
    $installment_amount_res = $total_amount/$installment_num;
    //Field for return $installment_amount_res
    if (empty($form['field_installment_num']['und'][0]['value']['#default_value'])) {
        $form['field_installment_num']['und'][0]['value']['#default_value'] = $installment_num_res;
    }
    //Field for return $installment_num_res
    if (empty($form['field_installment_amount']['und'][0]['value']['#default_value'])) {
        $form['field_installment_amount']['und'][0]['value']['#default_value'] = $installment_amount_res;
    }
}

```

How to get the result of any field before click save.. I think it something with `jQuery on change` but I haven't use any `jQuery` before..

# Answer
https://stackoverflow.com/a/13418999

I found this really helpful answer on stack overflow. This one is for dynamically created inputs. I assume that this is what you're after. You would retrieve the value for testing by using the .val() function.

```
//Static inputs
$('.fieldclass input').on('change', function (){
  $(this).val();
});
//Dynamic inputs (source above)
$(document).on('change', '.fieldclass input', function(){
  $('.fieldclass input').val();
});

```

There is also a shortcut for the on change method, as well really good documentation found here: https://api.jquery.com/change/

Hope this is helpful to you :)
> 1 votes

# Answer
It's pretty easy with jQuery.

```
$('.form-actions input').on('click', function(event) {
  event.preventDefault(); //prevent normal submit action

  var fieldvalue = $('.field-name input').val(); //get the field value

  $('form#myForm').submit(); //submit the form

});

```

Hope it will help You. Ask if You need more help :)
> 1 votes

---
Tags: javascript
---


title: always include language code in url

text:
# Question
Title: always include language code in url
For SEO reason I need my site to always use language code in the URL. At the moment mysite.com/en/news is also accessible through mysite.com/news, according to my SEO contact, mysite.com/news should return content.

How do I achieve this behavior?

# Answer
Using the Global Redirect module with the default options. You can redirects all URLs without a language prefix to the correct URL with the default language prefix contained.
> 3 votes

# Answer
This is what you have (for example):

* mysite.com (default)
* mysite.com/fr (French)

This is what you are looking for (for example):

* mysite.com/en (default)
* mysite.com/fr (French)

This can be accomplished in your language settings. For each language you can set a Path prefix, use en and fr (for my example).

To redirect mysite.com to mysite.com/en you can use the Global Redirect module
> 2 votes

# Answer
In Drupal 8 you can go to Manage \> Configuration \> Regional and language \> Languages \> Detection and selection \> URL (configure). Here you can add a prefix for the URLs for every language.
> 0 votes

---
Tags: 7, i18n-l10n, uri
---


title: sort specific field last modified date

text:
# Question
Title: sort specific field last modified date
I have content type named recipe, Recipe have some fields like name, image, description. And also have a Boolean field name editors picks. I want to get last checked 3 posts of editors picks field in a view. or i want to limit this field can check only in 3 post. How can i do this. Please help me

# Answer
> -1 votes
I searched for SORT CRITERIA to sort by last modified date there is a field named "Content revision: Updated date". This field helped me to sort by modified date.

Credits: @ismini (for posting the comments that helped me).

---
Tags: 7, views
---


# Question
Title: How declare my service via dependency injection in construct?
i have a class

> Paybox

This class is declare as a service.

In my controller class, i inject this service like this :

```
public function __construct($payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

```

This declaration work fine, but i see sometime this in the constructor :

```
public function __construct(Paybox $payboxService) {
    $this->paybox = $payboxService;
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('paybox_services'),
    );
}

```

They add the Type Paybox before $payboxService.

The 2 method work.

Can someone explain me the difference ? and what is the right way for inject the service ?

# Answer
Both code snippets work indeed, the second one uses type declaration:

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

You can use type declaration to force specific arguments in your methods parameters. If, for instance, someone should create a new class from your first code snippet and inject something other that your `Paybox` class your class will not throw errors. In the second example you are enforcing the first parameter to be of type `Paybox`. If something else is passed PHP will throw errors. If you make your code available as an API for other people they can see what kind of parameters are required without checking the full logic of your encapsulated code.

Furthermore, your IDE will play nice with type hinted parameters providing you with suggestions and better doc block generation.
> 9 votes

---
Tags: 8
---


# Question
Title: Is there a way to send emails when someone logs in?
Logins on my sites are very infrequent and are normally done by myself. I would like a way of getting email notification when someone logs in. This way I might be able to spot someone hacking into the site early on.

I am using Drupal 7.

# Answer
> 5 votes
A possible solution is to use the Rules module and create a custom rule like so:

* Rules Event = After a user logs in.
* Rules Action = Send an eMail.

That's really it (a kind of Rules 101 also if you want ...).

Here is a rule (in Rules import format) that should answer your question:

```
{ "rules_notify_about_login" : {
    "LABEL" : "Notify admin about login",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "New login",
          "message" : "Some user just completed a login to [site:name], located at [site:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

The rule will be triggered (Rules Event) right after login was completed. For any user who does not have the role that matches "`role id = 3`" (= Rules Condition), aka for any user who is not an administrator, it will send an appropriate eMail to the admin user of the site.

If you have the Rules UI enabled, you can just import the above rule. As an alternative just use the Rules UI to create a similar rule from scratch.

Some further refinements you may want to apply to the above sample rule:

* Adapt the value (=3) of the role id to fit your needs or just omit the Rules Condition if you want to perform the Rules Action for any role.
* Include relevant info about the user who performed a login (using available tokens about that user).
* Adapt the eMail subject and content to fit your needs.

PS: This answer applies to D7, though for D8 it should be similar.

# Answer
> 0 votes
Sending eMails to be informed about such logins is perfectly possible, as explained in my prior answer. However, eMails may get lost, or may not ever arrive at its destination. So therefor, as an alternative (or supplement?), you might also want to create a "*custom log*" using the Message module, as further detailed below.

### 1. Create a Message Type

Use the Message module and create a custom Message Type for creating custom log records whenever a user performs a login. Here is a sample of such message type (in export format, which you should be able to import in your own site also):

```
{
  "name" : "users_performing_login",
  "description" : "Users performing login",
  "argument_keys" : [ "@login_user_name", "@login_user_id" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "\u003Cp\u003EUser with name =\u0026nbsp;@login_user_name and uid =\u0026nbsp;@login_user_id just performed a login.\u003C\/p\u003E\r\n",
        "format" : "filtered_html",
        "safe_value" : "\u003Cp\u003EUser with name =\u00a0@login_user_name and uid =\u00a0@login_user_id just performed a login.\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

```

Some details about this Message Type:

* Description:
> Users performing login
* Message Text:
> User with name = @login\_user\_name and uid = @login\_user\_id just performed a login.
* Replacement tokens (\*):
> @login\_user\_name, @login\_user\_id

(\*): The usage of these "*Replacement tokens*" is crucial here. For way more details about this (amazing) feature, refer to What's the purpose of "Replacement tokens" of a Message type?.

### 2. Create a rule for creating messages

Create a rule with a Rules Action "Create entity" (of type "Message", and with Message Type the one created in the previous step). Here is a sample of such rule you could use (in Rules export format, which you should be able to import in your own site also if you have the Rules UI enabled):

```
{ "rules_logging_about_logins" : {
    "LABEL" : "Custom logging about logins",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "3" : "3" } } } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "users_performing_login",
            "param_user" : [ "account" ]
          },
          "PROVIDE" : { "entity_created" : { "log_record_created" : "Created log record" } }
        }
      },
      { "data_set" : {
          "data" : [ "log-record-created:arguments:login-user-name" ],
          "value" : [ "account:name" ]
        }
      },
      { "data_set" : {
          "data" : [ "log-record-created:arguments:login-user-id" ],
          "value" : [ "account:uid" ]
        }
      }
    ]
  }
}

```

The Rules Event and Rules Conditions are similar to the rule in my prior answer. While the Rules Actions will take care of creating an appropriate Message. Also note the last 2 Rules Actions: these are to assign the appropriate values to the "Replacement tokens" used in the Message type.

### 3. Create a view for browsing messages

The rule in the previous step will create a message (with a Message Type "Users performing login"). What is left is to create an appropriate view to browse these messages that get created.

Here is a (rather basic) view to "Show all existing messages." (in Views export format, which you should be able to import in your own site also if you have the Views UI enabled):

```
$view = new view();
$view->name = 'message';
$view->description = 'Show all existing messages.';
$view->tag = 'Message';
$view->base_table = 'message';
$view->human_name = 'Message';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'administer message types';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '30';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'timestamp' => 'timestamp',
  'message_render' => 'message_render',
  'name' => 'name',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'timestamp' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'message_render' => array(
    'align' => '',
    'separator' => '',
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['sticky'] = TRUE;
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['content'] = 'No messages created yet.';
$handler->display->display_options['empty']['area']['format'] = 'filtered_html';
/* Relationship: Message: User uid */
$handler->display->display_options['relationships']['user']['id'] = 'user';
$handler->display->display_options['relationships']['user']['table'] = 'message';
$handler->display->display_options['relationships']['user']['field'] = 'user';
/* Field: Message: Timestamp */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'message';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'short';
/* Field: Message: Render message (Get text) */
$handler->display->display_options['fields']['message_render']['id'] = 'message_render';
$handler->display->display_options['fields']['message_render']['table'] = 'message';
$handler->display->display_options['fields']['message_render']['field'] = 'message_render';
$handler->display->display_options['fields']['message_render']['label'] = 'Text';
$handler->display->display_options['fields']['message_render']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['message_render']['hide_alter_empty'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'user';
$handler->display->display_options['fields']['name']['label'] = 'User';
/* Sort criterion: Message: Timestamp */
$handler->display->display_options['sorts']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['table'] = 'message';
$handler->display->display_options['sorts']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['sorts']['timestamp']['order'] = 'DESC';
/* Filter criterion: Message: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'message';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['exposed'] = TRUE;
$handler->display->display_options['filters']['type']['expose']['operator_id'] = 'type_op';
$handler->display->display_options['filters']['type']['expose']['label'] = 'Message type';
$handler->display->display_options['filters']['type']['expose']['operator'] = 'type_op';
$handler->display->display_options['filters']['type']['expose']['identifier'] = 'type';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['path'] = 'admin/content/message';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Messages';
$handler->display->display_options['menu']['description'] = 'A list of all messages.';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['name'] = 'management';

```

After you enabled the view, you should navigate to `/admin/content/message` in your site, where you should see some views result similar to this one (assuming some users performed a login after you enabled the view):

```
Timestamp           Text
08/03/2017 - 11:21  User with name = Pierre.Vriens and uid = 3 just performed a login.
08/03/2017 - 10:03  User with name = Dries.Buytaert and uid = 4 just performed a login.
08/02/2017 - 19:17  User with name = Hillary.Trump and uid = 911 just performed a login.
08/01/2017 - 11:55  User with name = Donald.Clinton and uid = 7 just performed a login.

```

So with this Views result, you have a permanent (custom) log, without the risk of eMails getting lost, or eMails that never arrive. Especially at times when you want to investigate possible hacking, this is IMO a much more solid solution as compared to just "sending an eMail" ... Which IT auditors must love also.

### 4. Bonus features

**a) Tuning the layout of the custom log records**

The Message Text in the above scenario is rather basic (apart from some fixed text, it only includes the user's name and user's id). However, the real magic is in the "Replacement tokens": virtually any token that you have available in the custom rule, can be passed along to the Message text to be created. Combined with the zillion of tokens already made available via the Message module, it implies that you can make your Message Text to be whatever you want.

**b) Receiving eMail notifications**

By using the Message module, you may also combine it with using the Message Notify module. Some details about it (from its project page):

> ... provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.
>
> Message Notify is part of the message stack, a suite of modules that provide a framework for messaging and notifications.

### 5. More info about the Message module

There is *not a lot of documentation* available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:

PS: This answer applies to D7.

---
Tags: users, emails, security
---


# Question
Title: How can I track all Flagging/Unflagging history for statistics?
Is there any way to track the flag/unflagging of a node/user without the Heartbeat module? Or a way to track all user/node interaction to use it after for statistics?

# Answer
> 3 votes
***Yes there is a way*** ... using a combination of these (commonly used) modules:

Long story short:

1. Create a "Message Type" that you'll use for creating some type of custom logging (for the events you're asking about).
2. Use the Rules module to capture the events, with rules actions to create appropriate messages (= records in your custom log).
3. Use the Views module to browse the messages that got created.

For a variation of your question, where a similar technique can be used, refer to my answer to "Is there a way to send emails when someone logs in?".

PS: this answer applies to D7 ...

---
Tags: 7, flags, nodes, heartbeat
---


# Question
Title: Dynamic default values in WebForm Drupal 8.x
We are working on our web projects with Drupal 8 and WebForm. Now we have a small problem ...

We have a **webform** that allows people to sign up for a workout. We would need to provide dynamic dates, so that the exercisers can register at that time.

Starting position: There are different groups that have a workout at different times. There is a fixed number per workout group. That can not be exceeded. People can sign out or sign in.

When a workout group is full, no one can register. Therefore, we must provide a selection of possible dates. This must be reprocessed every day.

**Our problem**: How can we **create a dynamic ad on WebForm** before viewing? Using element types, templates, preprocess or any else? Any hints or tips?

# Answer
You can place a webform anywhere in code, examples are a controller, a block or a preprocess hook in a theme. Put the dynamic default values in `#default_data`:

*/src/Controller/WebformController.php*

```
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * A webform controller.
 */
class WebformController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function webform() {

    // generate dynamic default values
    $name = 'John Doe';
    $message = 'This content is generated dynamically.';

    // add this to a webform
    $build['form']  = [
      '#type' => 'webform',
      '#webform' => 'contact',
      '#default_data' => [
        'name' => $name,
        'message' => $message,
      ],
    ];

    return $build;
  }

}

```

*mymodule.routing.yml*

```
mymodule.webform:
  path: '/mywebform'
  defaults:
    _controller: '\Drupal\mymodule\Controller\WebformController:webform'
    _title: 'My Webform'
  requirements:
    _permission: 'access content'

```
> 1 votes

---
Tags: webforms
---


# Question
Title: How to debug Batch API more efficiently?
I've some issues with Feeds importing (I don't want to focus on particular case) and I'd like to find the way of able to debug Batch API processing more efficiently. Given the fact of complexity of Feeds module (a plethora of classes), I can't easily implement one-time processing in a short time.

Here are the methods which I'm aware so far:

* using `dd()` from Devel and `tail -f drupal_debug.txt` (minus: not time efficient)
* using `watchdog()` like `watchdog('foo', '<pre>'. print_r($foo, TRUE). '</pre>');` then `drush watchdog-show --tail --full` to monitor in real-time
* using XDebug and its `xdebug.auto_trace` (minus: non-interactive excess of trace logs)

but they're not helpful in particular case and at the same time I'd like to learn something new.

Ideally I'm looking for some easy way to convert Batch API into standard non-AJAX processing, so I can do old-school `var_dump($var); exit;` and refreshing the page by sending the same POST requests over and over again, unless there are some more efficient ways. I'm also considering temporary core hacks to achieve that.

Any ideas?

# Answer
Here are some workarounds which I've found so far which makes life easier.

### Using `curl`

You need: `drush` and `curl`.

1. Add `var_export($name); exit;` into the batch code place of interest, so batch won't be set to finish state.
2. In the web browser open Network console (e.g. DevTools in Chrome).
3. Start batch process as usual (in Feeds it's at: `/import`).
4. Stop the batch processing just before the redirect by pressing Escape. Then note the URI.

Alternative way is to fetch `id` directly from the `batch` table:

```
$ drush sqlq "SELECT bid FROM batch"

```
5. Click on the previous 302 request and take a note of your session cookie from Request Headers, you need only `SESS0X=Y` cookie, e.g.

```
Cookie: SESS0F00=B4R

```
6. Run `curl` as below (you need to replace `id`, session cookie and your host):

```
$ curl -X POST -d "id=124&op=do" --cookie "SESS0F00=B4R" "http://myhost.local/batch"
your_debug_data_here

```
7. Previous step is repeatable after each code change which makes it easy to debug variables in no time.

For ever more efficiently, you can map it (e.g. in `vim`), so the output can be executed each time when you need it.

### Using repeatable XHR requests

1. Add `var_export($name); exit;` into the batch code place of interest, so batch won't be set to finish state.
2. In the web browser open Network console (e.g. DevTools in Chrome).
3. Start batch process as usual (in Feeds it's at: `/import`) and it should fail, because of `exit;` added in step 1.
4. Note the `batch?id=x&op=do` request and do Replay XHR (at least in Chrome).
5. Now on each code change you should be able to repeat the last step over and over again.

There are probably more ways of doing similar thing (including use of some plugins such as Postman, etc).
> 1 votes

# Answer
Using xdebug will be able to do the debug during the batch process. Here is a tutorial I just found in Youtube for people who don't know how to use xdebug: PhpStorm & Xdebug: Installation and Configuration, I didn't look at that video but hope it will be helpful.
> 0 votes

---
Tags: 7, debugging, batch-operations
---


# Question
Title: Scheduled rules execute a hour after they are supposed to
I have created a scheduled rule that sends a email based on a date field in nodes of a certain content type. The rule executes as scheduled and the email is sent but for some reason it only fires exactly a hour after its supposed to.

E.g on the admin/config/workflow/rules/schedule page the item is scheduled to execute at Thu, 2017-08-03 15:30 but I only receive the email at 16:30.

I could fix this by adding a offset to the trigger time but I would rather want to understand why this is happening and fix the problem accordingly.

# Answer
> 1 votes
### Cause 1:

After a rule is scheduled (using the Rules Scheduler submodule), it will only actually *execute* **next time cron runs**. Example:

* schedule a rule to execute at `timestamp X`.
* if the next time that cron runs is at `Y mins after timestamp X`, then the Rules execution will only happen then (= at `Y mins after timestamp X`).

### Cause 2:

If your site is set to the correct timezone, but your users are set to a timezone that is 1 hour ahead, then that might also explain what's happening. In that case, correct the timezone accordingly.

---
Tags: cron, rules
---


# Question
Title: How do I implement hook_form_alter() in a module?
I am trying to alter a form for the *Question* content type, whose ID is *node-question-form*.

I set up a module and tried to implement `hook_FORM_ID_alter()`, but it's not invoked. Even the simplest implementation as the following is not working.

```
function constellator_form_alter(&$form, &$form_state, $form_id) {
  echo "alter the form";
  exit;
}

```

I have been stuck with this since this morning. Nothing is working for me.

# Answer
Here is a working example I have pulled from a project and altered to have your module name.

Add this at the top of your .module file:

```
use Drupal\Core\Form\FormStateInterface;

```

Then copy this in

```
/**
 * Implements hook_form_alter().
 */
function constellator_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Adding custom validation for the welcome page type field.
  if ($form_id == 'node_article_edit_form' || $form_id == 'node_article_form') {
    // Do some stuff.
  }
}

```

I think most likely what you aren't doing is clearing the Drupal cache to register the hook. You can click on "clear all caches". Or better yet, install the drush command line utility and use "drush cr".
> 14 votes

# Answer
If you have set up a custom theme, then without adding any namespace requirement you can easily alter your form using `hook_form_form_id_alter()` in your theme\_name.theme file.

```
function bootstrap_ga_form_user_login_form_alter(&$form, &$form_state, $form_id) {
  global $base_url;
  $form['#validate'][] = '_bootstrap_ga_form_user_login_form_validate';
}

```

I added a custom validation to the user login form. *bootstrap\_ga* is the custom theme name.
> 4 votes

# Answer
Try this it in your custom module

Use the Below Namespace

```
    use Drupal\node\Entity\Node;
    use Drupal\Core\Form\FormStateInterface;

```

Use this hook\_form\_alter for the particular node

```
    //constellator_form_node_question_form_alter
function modulename_form_Form_ID_form_alter(&$form, &$form_state, $form_id){
  //echo <pre>; print_r($form); die;
}

```

And this hook will be used to edit the particular node form id
> 2 votes

---
Tags: forms, hooks
---


title: Fast 404 showing page not found

text:
# Question
Title: Fast 404 showing page not found
I have enabled fast\_404 and added the following line in settings.php

```
/**
* Fast 404 settings:
*/
// This path may need to be changed if the fast 404 module is in a different location.
include_once('./sites/all/modules/fast_404/fast_404.inc');

# Disallowed extensions. Any extension in here will not be served by Drupal and
# will get a fast 404.
$conf['fast_404_exts'] = '/^(?!robots).*\.(txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';

# Array of whitelisted URL fragment strings that conflict with fast_404.
$conf['fast_404_string_whitelisting'] = array('cdn/farfuture', '/advagg_');

# Default fast 404 error message.
$conf['fast_404_html'] = '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>';

# Call the extension checking now. This will skip any logging of 404s.
fast_404_ext_check();

# Check paths during bootstrap and see if they are legitimate.
# By default, a very plain 404 page is used, because usually errors like this are shown to browsers that only look at the headers. Uncomment this link to use a custom 404 page; this page needs to be in your docroot.
#$conf['fast_404_HTML_error_page'] = './page_not_found.html';

# By default, the custom 404 page is loaded only for path checking. Load it for all 404s with the below option set to TRUE, especially if you are only using fast_404_ext_check().
$conf['fast_404_HTML_error_all_paths'] = FALSE;

$conf['fast_404_path_check'] = TRUE;
fast_404_path_check();

```

If I access the wrong path it shows page not found. If I access the path http://example.com/news/test. It shows page not found, but it is a valid path. and admin menu also breaks after adding above lines.

# Answer
> 1 votes
A year late but since I just ran into all these and no answer has been given then here is how I made things work:

1. Verify that your settings.php has the correct include path.

include\_once('./sites/all/modules/fast\_404/fast\_404.inc');

// You may be using something like

include\_once('./sites/all/modules/contrib/fast\_404/fast\_404.inc');
2. Setting the following to TRUE, I found out, does not work with some path aliases:

$conf\['fast\_404\_path\_check'\] = FALSE; // If set to TRUE some aliases do not work
3. Regarding admin menu there is a line of code in admin\_menu.module that if you change then it works. Current version is line 66. You are looking for:

$items\['js/admin\_menu/cache/'\] = array(

// Change it to

$items\['js/admin\_menu/cache/%'\] = array(
4. I enabled fast\_404\_ext\_check() and fast\_404\_path\_check() without any issues. Do remember that fast\_404\_path\_check() only works with MySQL.

Remember to flush caches after changing 3. Hope this helps anyone that bumbs into these issues.

---
Tags: 7, configuration
---


# Question
Title: How to display the username instead of the UID?
I created a view to display content in a table. I want to show the author of the last comment. So I added the field "Comment Statistics: Uid of the last comment", but I wish to have the username in place of the UID.

How to do this ?

# Answer
> 0 votes
You'll need to add a relationship to users in your view and then you should be able to access something like the username.

---
Tags: views, 8, nodes, users, comments
---


# Question
Title: How to use "replacement tokens" created for a Message type in Views?
In my case a user with the role ("team member") flags a node created by normal user. I want to display "`@team member_id flagged @node_id created by @user_id`". Maybe later on I would like to add profile pics of both user/team member or the email or any information in the view about them.

Is this possible?

Here is an export of the Message type (created with the Message module):

```
{
  "name" : "utilisateur_finalise_intervention",
  "description" : "Utilisateur finalise intervention",
  "argument_keys" : [ "@utilisateur", "@equipier" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "fr",
  "arguments" : null,
  "message_text" : { "fr" : [
      {
        "value" : "@utilisateur a finalis\u00e9 une intervention avec @equipier",
        "format" : "filtered_html"
      }
    ]
  },
  "rdf_mapping" : []
}

```

And the rule I created looks like so:

```
{ "rules_link_set_finaliser_une_intervention" : {
    "LABEL" : "Rules link: Finaliser une intervention rules set",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "user" : { "label" : "user", "type" : "user" },
      "node_id" : { "label" : "node_id", "type" : "node" }
    },
    "RULES" : [
      { "RULE" : {
          "PROVIDE" : { "entity_created" : { "log_fin_intervention" : "log_fin_intervention" } },
          "DO" : [
            { "flag_unflagnode" : {
                "flag" : "accepter_invitation",
                "node" : [ "node-id" ],
                "flagging_user" : [ "user" ],
                "permission_check" : "1"
              }
            },
            { "flag_flagnode" : {
                "flag" : "fin_intervention",
                "node" : [ "node-id" ],
                "flagging_user" : [ "user" ],
                "permission_check" : "1"
              }
            },
            { "entity_create" : {
                "USING" : {
                  "type" : "message",
                  "param_type" : "utilisateur_finalise_intervention",
                  "param_user" : [ "node-id:author" ]
                },
                "PROVIDE" : { "entity_created" : { "log_fin_intervention" : "log_fin_intervention" } }
              }
            },
            { "data_set" : {
                "data" : [ "log-fin-intervention:arguments:utilisateur" ],
                "value" : [ "node-id:author:uid" ]
              }
            },
            { "data_set" : {
                "data" : [ "log-fin-intervention:arguments:equipier" ],
                "value" : [ "user:uid" ]
              }
            },
            { "mail" : {
                "to" : [ "user:mail" ],
                "subject" : "Votre collaboration sur [node-id:title] est termin\u00e9e",
                "message" : "Votre collaboration avec [node-id:author:field-prenom] [node-id:author:field-nom] sur le projet  [node-id:title] est maintenant termin\u00e9e",
                "from" : [ "" ],
                "language" : [ "" ]
              }
            },
            { "drupal_message" : { "message" : "Votre collaboration avec  [user:field-prenom] [user:field-nom]  est maintenant termin\u00e9e" } },
            { "redirect" : { "url" : [ "node-id:url" ] } }
          ],
          "LABEL" : "Finaliser intervention"
        }
      }
    ]
  }
}

```

And also the view I created:

I also have an error displayed above the view

```
Notice : Undefined variable: table dans ViewsUiBaseViewsWizard->default_display_filters_user()

```

# Answer
"*To add profile pics of both user/team member or the email or any information in the view ...*" (as in your question), you cannot use the *replacement tokens* (= `@utilisateur` and `@equipier` in your case). These tokens can only be used as part of your *Message Text* (as you are already doing), as indicated also via `... which the message text makes use of ...` on the Message Types form where you enter those tokens.

However, Messages are fieldable entities. So what you can do is like detailed in the steps below ...

### Step 1:

Define a field in your Message Type corresponding to each of those tokens. As an example, add fields similar to these (for `equipier` and for `utilisateur`), with machine names like so:

* `field_equipier_user_name`.
* `field_equipier_user_id`.
* `field_utilisateur_user_name`.
* `field_utilisateur_user_id`.

Your replacement tokens appear to be `uid` values, note that I'm using a similar `uid`, but also the `name` as an alternative (it could as well be an eMail field, etc).

### Step 2:

Extend your rule to also perform a Rules Action like "Set a data value" (for each of your fields you added in the previous step). To continue the example, add these actions in your existing rule:

```
 ,
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-equipier-user-id" ],
    "value" : [ "user:uid" ]
  },
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-name" ],
    "value" : [ "user:name" ]
  }
},
{ "data_set" : {
    "data" : [ "log-fin-intervention:field-utilisateur-user-id" ],
    "value" : [ "user:uid" ]
  }

```

### Step 3:

Extend your view to also add those extra Message Type fields to your view (as extra fields of your view. Be aware: if later on you add more fields to your Message Type (and rule and view afterwards also), you'll only have actual values in the corresponding columns of the Views results for message that were created after you added those extra fields.

BTW, the Views error near the end of your question seems like a different question (not addressed in this answer ...).

PS: this answer applies to D7 ...
> 3 votes

---
Tags: views, flags, message-subscribe
---


# Question
Title: Why don't CAS users show up in users_field_data?
I have a simple multisite setup in Drupal 8. I installed the CAS module and verified that at least one user logged in successfully using our university's CAS server.

I can see the user at /admin/people, but I cannot see his entry in the database. I looked in the tables users, users\_data, and users\_field\_data, and all I can see is the admin user (me).

Where are the users located in the database?

I need to know for a custom module I am developing. FWIW I do have "Auto Register Users" enabled in the module configuration.

# Answer
> 1 votes
For D8, CAS requires External Authentication module.

* External Authentication maintains a db table called authmap.
* CAS maintains a table named cas\_login\_data.

I suspect the data you're looking for is in one of those tables.

---
Tags: users
---


# Question
Title: Composer Not Getting Latest Version of Module
I am one of the maintainers of Bootstrap Paragraphs. The module is currently set as the 2.0 branch to be the default and the 1.0 branch is set to unsupported. The 1.0 had a Beta Release but the 2.0 is currently in Alpha.

When I run `composer require drupal/bootstrap_paragraphs` composer downloads the 1.0 release (`"drupal/bootstrap_paragraphs": "^1.0@beta",`) instead of the 2.0 release.

What do we have to do to make the 2.0 branch be downloaded when running `composer require drupal/bootstrap_paragraph`. Want to avoid as many people as possible from using the 1.0 branch.

# Answer
> 2 votes
Composer does not default to the "latest" it defaults to the "Most stable" when there isnt a stable release. In this case 1.0-beta1 is "more stable" than 2.0-alpha1.

---
Tags: composer, community-official-site
---


# Question
Title: How do i fill custom field types when i programmatically create a node
I'm trying to create nodes pragmatically but I haven't been able to fill content for fields that aren't title or body. For example if i had an event type with a field called "ActivityId" how would i fill in that field pragmatically? The machine name for that field is field\_activityid

```
function createNode($CalObj){
     global $user;

     $node = entity_create('node', array(
    'type' => 'event',
    'uid' => 1,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  ));
     $entity = entity_metadata_wrapper('node', $node);
     $entity->language(LANGUAGE_NONE);
     $entity->title = (string)$CalObj->ActivityName;
     $entity->body->set(array(
    'value' => (string)$CalObj->ActivityId,
    'summary' => 'PROGMATIC SUMMARY',
    'format' => 'full_html',
  ));
  $entity->save();
 }

```

adding the following line:

```
$entity->activityid->set(array(
      'value' => "HJSDJHSJSKNJSDNJKSDNKJDSFJKN",
    ));

```

gives me the following error message:

EntityMetadataWrapperException: Unknown data property activityid. in EntityStructureWrapper-\>getPropertyInfo() (line 354 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

EDIT:

```
$entity->field_activityid->set(array(
      'value' => "HJSDJHSJSKNJSDNJKSDNKJDSFJKN",
    ));

```

this makes the original error go away but the new error is:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at node()-\>field\_activityid: . in EntityMetadataWrapper-\>set() (line 122 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

the field is just a simple text field(the single line without a body or summary and 255 character limit)

# Answer
You create a node pro like that.

```
$complaint_body = 'Your node complaint body text';
$node = new stdClass();  // Create a new node object
$node->type = 'company';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = 'Your node title';
$node->body[$node->language][0]['value'] = $complaint_body;
$node->body[$node->language][0]['summary'] = text_summary($complaint_body);
$node->body[$node->language][0]['format'] = 'full_html';

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;
// Set created date
$node->date = 'complaint_post_date';
$node->created = strtotime('complaint_post_date');

$path = 'content/mytest-' . date('YmdHis');
$node->path = array('alias' => $path);
// Save the node
node_save($node);

```

Add custom fields

```
$node->field_complaint_address[LANGUAGE_NONE][0]['value'] = 'This is custom cck filed to get complaint address';

```

Add a node reference to a node

```
$node->field_review_company_name[$node->language][0]['nid'] = 'company_node_id';

```

Add a term reference to a node

```
$node->field_company_industry[$node->language][0]['tid'] = 'company_term_id';

```

Thankyou
> 0 votes

# Answer
Thanks to clive for the tip.

```
$entity->field_activityid = "HJSDJHSJSKNJSDNJKSDNKJDSFJKN";

```

Essentially just the full machine name and setting it equal to the value you are storing it as. Using Set and an array pair didn't work for me.

This example worked for custom text field that was added to the content type using the Drupal UI.
> 0 votes

---
Tags: nodes
---


title: Render blocks in custom page

text:
# Question
Title: Render blocks in custom page
I followed steps given in this link to create a custom Page.

Page is created and 'Hello world' is printing in the page, now i want to render some blocks in that page. How can I achieve this task?

# Answer
> 2 votes
Given that you're using a custom controller for your page, you have the option to load the block from your controller, or place the block in another region outside of that part of the page that the Controller controls.

For blocks such as global elements such as headers and footers, I would recommend you place them through the CMS at /admin/structure/block

For blocks that sit above or below the content that your controller loads, you can also place them from /admin/structure/block or you can load them from within the the controller.

If you need to place content above and below your block, you'd probably want to load it programmatically in your controller.

Here's a guide on loading blocks programmatically.

basically in your myPage() method that is returning the build array, you'd want the build array for the block you want to load.

```
$build['events'] = \Drupal::service('plugin.manager.block')
  ->createInstance('my_events_block')
  ->build();

$build['recent_insights'] = \Drupal::service('plugin.manager.block')
  ->createInstance('recent_articles', ['title' => 'Some Recent Articles', 'offset' => 0])
  ->build();

return $build;

```

The code above works for the types of blocks that you custom create in your module, such as at /mymodule/src/Plugin/Block/RecentArticles.php

It doesn't work for loading an instance of a block that was created through the CMS.

For those you need to use:

```
$block = \Drupal::entityTypeManager()->getStorage('block')->load('myblock');
$build['myblock'] =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

```

# Answer
> 1 votes
To render block on your custom page, go to *Structure*, then *Block Layout*, from there you can either create a custom new block (enable *Custom Block* for that), or configure the existing block. To place on your page, in *Configure* page, go to *Pages* under *Visibility* section and add path of your custom page to the list, then save. Your block should be shown according to assigned region.

If your custom page uses Twig template, see: How to render a template in Drupal 8.

If you'd like to create your own block programatically, see: Block API overview.

---
Tags: 8, blocks, page-controller
---


# Question
Title: Drupal 7 Form API not returning all values into $form_state
I have a form with multiple similar fields like so:

```
<?php

example_form($form, &$form_state) {

   for($i = 0; $i < 10; $i++){
       $form[$i]['name'] = array(
           '#title' => t('Name'),
           '#type'  => 'textfield',
       );
   }

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

   return $form;
}

```

This outputs ten fields and a submit button. However, inside `hook_form_submit` and viewing the values from `dpm($form_state['values'])`, there is only one instance of `name`.

I can easily fix this problem by uniquely naming the field `$form[$i]["name-{$i}"]` but this solution does not seem pragmatic. What is the work around for not individually naming each field uniquely? Why is the not naming the container qualify as unique?

# Answer
Submitted values are flattened by default. To change that, set the `#tree` property on the container (in this case the form):

```
$form['#tree'] = TRUE;

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Mysql query that performs sums between different tables
I am struggling to make a query in a custom service function in Drupal 7, which should make 3 sums. In each table (3), there are 2 records saved with the following values:

* field\_data\_field\_monto\_15pts with field \[field\_monto\_15pts\_value\] data: 5 and 6
* field\_data\_field\_monto\_14pts with field \[field\_monto\_14pts\_value\] data: 3 and 4
* field\_data\_field\_monto\_13pts with field \[field\_monto\_13pts\_value\] data: 1 and 2

The service function that performs the query and returns data in the JSON format is the following.

```
$cantidad = db_query('
  SELECT SUM(field_monto_15pts_value) AS 15pts,
         SUM(field_monto_14pts_value) AS 14pts,
         SUM(field_monto_13pts_value) AS 13pts
  FROM {field_data_field_monto_15pts},  {field_data_field_monto_14pts},  {field_data_field_monto_13pts}')
  ->fetchAssoc();

return $cantidad;

```

What I expect from the function is the following values.

```
{
  "15pts": "11",
   "14pts": "7",
   "13pts": "3"
}

```

What the function returns is this.

```
{
   "15pts": "44",
   "14pts": "28",
   "13pts": "12"
}

```

What is wrong in the code I am using?

# Answer
> 0 votes
Well ... Since no one had this problem, or nobody has a solution, I put the solution that I have given on the site https://www.drupal.org/node/2898276

The problem is how I wrote the query to the database. A Cartesian product is produced. After rewriting the query was solved. It was finally written:

```
$lo_que_che= db_query('SELECT (SELECT SUM(field_monto_15pts_value) AS 15pts FROM {field_data_field_monto_15pts}) 15pts, (SELECT SUM(field_monto_14pts_value) AS 14pts FROM {field_data_field_monto_14pts}) 14pts, SUM(field_monto_13pts_value) AS 13pts FROM field_data_field_monto_13pts}') ->fetchAssoc();  return $lo_que_che;

```

---
Tags: database, services
---


# Question
Title: How can I view nodes on my site from Drupalgap?
I am getting started with Drupalgap and trying to access nodes on my Drupal site by node ID from within Drupalgap. I have checked the Node and Node Services documentation. I thought I could use the node\_page\_view(nid) function like this:

```
function mymodule_sample_page() {
  try {
    node_load(11, {
        success:function(node){
        alert("Loaded " + node.title);
      }
    });
    return node_page_view(11);
  }
  catch (error) { console.log('mymodule_sample_page - ' + error); }
}

```

However, when I attempt to test this in my module, I get the alert "Loaded your node" but the content is not actually displayed on the page by **node\_page\_view()**. What do I need to do to display the content?

# Answer
> 2 votes
In `mymodule_sample_page()` just return an empty div container, for example:

`<div id="my_node_11"></div>`

Then attach a `pageshow` handler to your page via `hook_menu()`, then in the pageshow handler call node\_load(), and in its success inject the content into your empty div container.

The `page_callback` can not have any async calls in it, as all async calls have to be handled after the page is actually shown.

FYI, DrupalGap has built in support to view nodes, just navigate to `node/11` in the app. Here's a brief example demonstrating pageshow: http://www.drupalgap.org/node/154

# Answer
> 0 votes
Thanks to Tyler. I put the answer with more detail and proven by my successful experiment. Hope this can do some helps.

```
function mymodule_sample_page() {
  var display_page = '<div id="my_node_11"></div>';

  return display_page;
}

function mymodule_sample_pageshow() {
  try{
        var nid = 11;
        node_load(nid, {
        success:function(node){

         var content = node.content;

         $('#' + 'my_node_' + nid).html(content).trigger('create');
          }
        });
   }
  catch (error) { console.log('mymodule_sample_page - ' + error); }
}

```

---
Tags: javascript
---


# Question
Title: Using the Migrate Source CSV plugin to migrate images
I'm currently importing nodes from a Drupal 7 to Drupal 8 site, using this very helpful tutorial: https://www.drupal.org/docs/8/upgrade/using-the-migrate-source-csv-plugin I have found a fairly good way to import fields. My only stumbling block at the moment is images. I'm finding it very hard to find anything about how I would manage importing of images, whether if I give it the path of the old images it can import from there, or if I give it a file name, then put the image somewhere, I have tried both so far and the image field always just ends up blank in the new nodes that are created. I've got my head around using the above links approach so if anyone has a solution that fits with that, that would be great!

# Answer
You'll need to run a migration of all the files you want first. The file\_copy process plugin is going to be your best friend for this part. To get you started,

```
id: image_migration
destination:
  plugin: 'entity:file'
process:
  uri:
    plugin: file_copy
    source:
      - file_source_uri
      - file_destination_uri

```

Once you have your files migrated, it's actually very easy to tell your image field about the file

```
process:
  field_image:
    plugin: migration
    migration: image_migration
    source: image_id

```

A couple notes:

* image\_migration refers to the migration that imports your images. Make sure to change it if you use a different name.
* image\_id needs to be the key from the image migration. It will be mapped to the new file created during that import.

Very Useful Guide
> 1 votes

---
Tags: nodes, 8, media, migrations, importing-exporting
---


# Question
Title: MODULE_preprocess_block() get rendered region in drupal 8
So I am trying to port a Drupal 7 module to Drupal 8, and am struggling with how to translate a "NAME\_preprocess\_block" method. In the D7 code, it filters by the region a block is getting rendered

```
if ($vars['elements']['#block']->region == "my_region") {
   // Do stuff.
}

```

However, the "\['#block'\]-\>region" object doesn't exist in drupal 8, and I can't seem to find an alternative. Is it still possible to do this?

Thanks!

# Answer
You have to load the block(don't worry, it is already loaded so no performance impact).

```
$block = entity_load('block', $variables['elements']['#id']);
$region = $block->region;

```
> 1 votes

# Answer
So, getting everything working here is the code I got to work.

```
use Drupal\block\Entity\Block;
/**
 * Implements hook_preprocess_block().
 */
function harfang_preprocess_block(&$variables) {
  $block = Block::load($variables['elements']['#id']);
  $region = $block->getRegion();

 // Add classes to all bocks in footer region.
  if($region == 'footer') {
 // Do something.
  }
}

```

added the use statement at the top and removed the non-joiners
> 5 votes

# Answer
Here the correct version for Drupal 8.x:

```
$block = \Drupal\block\Entity\Block::load('block', $variables['elements']['#id']);
$region = $block->getRegion();

```
> 0 votes

# Answer
For drupal 8.2.x the above suggestions don't work anymore here is what worked for me

```
function MODULENAME_preprocess_block(&$variables ){
    $region = $variables['elements']['#configuration']['region'];
    if($region == "my_region"){
        //Do stuff
    }
}

```

Can also be implemented inside your `.theme` file with `THEMENAME_preprocess_block`

**NOTE** it seems that configuration region is available in a module preprocess function only when `context` module is enabled (!?) otherwise the region is only available in a theme preprocess function
> 0 votes

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


# Question
Title: How can I export webform analysis data to excel sheet?
**Screenshot:**

**Problem:** I want to export all `Analysis` datas to `excel sheet`.

I am using drupal `7.53` and `webform 7.x-4.14`.

# Answer
> 0 votes
I wrote a module for this. You can find it here: drupal.org/project/webform\_analysis\_export

---
Tags: 7, webforms, importing-exporting
---


title: Error When Changing User Role in Drush?

text:
# Question
Title: Error When Changing User Role in Drush?
I wanted to see if there is a way to change a user role using drush. I found this post explaining how to do it but I get an error. I replaced the actual username with "USERNAME".

`drush user-add-role administrator USERNAME`

> ```
> > exception 'Drush\Role\RoleException' with message 'Could not find the
> > role:      [error] administrator' in
> > /usr/local/src/drush/lib/Drush/Role/RoleBase.php:46 Stack trace:
> > #0 [internal function]: Drush\Role\RoleBase->__construct('administrator')
> > #1 /usr/local/src/drush/includes/drush.inc(113): ReflectionClass->newInstanceArgs(Array)
> > #2 /usr/local/src/drush/commands/core/role.drush.inc(273): drush_get_class('Drush\\Role\\Role', Array)
> > #3 /usr/local/src/drush/commands/user/user.drush.inc(281): drush_role_get_class('administrator')
> > #4 [internal function]: drush_user_add_role('administrator', 'USERNAME')
> > #5 /usr/local/src/drush/includes/command.inc(368): call_user_func_array('drush_user_add_...', Array)
> > #6 /usr/local/src/drush/includes/command.inc(219): _drush_invoke_hooks(Array, Array)
> > #7 [internal function]: drush_command('administrator', 'USERNAME')
> > #8 /usr/local/src/drush/includes/command.inc(187): call_user_func_array('drush_command', Array)
> > #9 /usr/local/src/drush/lib/Drush/Boot/BaseBoot.php(62): drush_dispatch(Array)
> > #10 /usr/local/src/drush/drush.php(70): Drush\Boot\BaseBoot->bootstrap_and_dispatch()
> > #11 /usr/local/src/drush/drush.php(11): drush_main()
> > #12 {main}
>
> ```

I am using Drupal Commons 7.50 and Drush 7.0.0.

Edit: Things I have tried:

* spelling role correctly and making sure it exists
* clearing cache

# Answer
> 1 votes
Syntax was wrong. It needed quotes and capitalization definitely matters.

`drush user-add-role "administrator" USERNAME`

---
Tags: 7, users, drush
---


title: Add fields to a form with Ajax

text:
# Question
Title: Add fields to a form with Ajax
I have a little problem with my form. I try to create a button that adds dynamically some fields with Ajax.

I created a fieldset in order to group this fields. But it's seems that the form state that handle the number of items is not kept (nb\_package), and it's stuck to 2 when i click on the add button (Ajouter un package).

I tried some example but it didn't work...

```
namespace Drupal\module\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ArmateurAddBoat extends FormBase {

  public function getFormId() {
    return 'armateur_add_boat';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->generationListes();
    $form_state->disableRedirect();
    $form['#attached']['library'][] = 'module/addboat';
    $form['#tree'] = TRUE;

    $form['packages'] = [
      '#type' => 'fieldset',
      '#prefix' => '<div id="packages-wrapper">',
      '#suffix' => '</div>',
    ];

    $nb_package = $form_state->get('nb_package');
    if (!isset($nb_package)) {
      $nb_package = 1;
      $form_state->set('nb_package', $nb_package);
    }

    for ($i = 0; $i < $nb_package; $i++) {

      $form['packages'][$i]['titre_package'] = [
        '#type' => 'textfield',
        '#prefix' => '<div class="package-item"><div class="row">',
        '#title' => $this->t('Nom de la période'),
        '#required' => TRUE,
      ];

      $form['packages'][$i]['date_debut_package'] = [
        '#type' => 'date',
        '#title' => $this->t('Début de la période'),
        '#required' => TRUE,
        '#prefix' => '<div class="col-md-4 col-lg-4">',
        '#suffix' => '</div>',
      ];

      $form['packages'][$i]['date_fin_package'] = [
        '#type' => 'date',
        '#title' => $this->t('Début de la période'),
        '#required' => TRUE,
        '#prefix' => '<div class="col-md-4 col-lg-4">',
        '#suffix' => '</div>',
      ];

      $form['packages'][$i]['horaire_package'] = [
        '#type' => 'select',
        '#title' => $this->t('Horaire'),
        '#options' => $this->_horaires,
        '#required' => TRUE,
        '#prefix' => '<div class="col-md-4 col-lg-4">',
        '#suffix' => '</div></div>',
      ];

      $form['packages'][$i]['cocktail_capacite_max_package'] = [
        '#type' => 'number',
        '#title' => $this->t('Capacité max'),
        '#min' => 0,
        '#required' => TRUE,
        '#default_value' => 0,
        '#prefix' => '<div class="row"><div class="col-md-4 col-lg-4">',
      ];

      $form['packages'][$i]['cocktail_capacite_min_package'] = [
        '#type' => 'number',
        '#title' => $this->t('Capacité min'),
        '#min' => 0,
        '#required' => TRUE,
        '#default_value' => 0,
        '#suffix' => '</div>',
      ];

      $form['packages'][$i]['repas_capacite_max_package'] = [
        '#type' => 'number',
        '#title' => $this->t('Capacité max'),
        '#min' => 0,
        '#required' => TRUE,
        '#default_value' => 0,
        '#prefix' => '<div class="col-md-4 col-lg-4">',
      ];

      $form['packages'][$i]['repas_capacite_min_package'] = [
        '#type' => 'number',
        '#title' => $this->t('Capacité min'),
        '#min' => 0,
        '#required' => TRUE,
        '#default_value' => 0,
        '#suffix' => '</div></div></div>',
      ];
    }

    $form['ajouter_package'] = [
      '#type' => 'submit',
      '#value' => $this->t('Ajouter une période'),
      //'#attributes' => ['class' => ['btn btn-primary'], 'id' => 'add-package'],
      '#ajax' => [
        'callback' => [$this, 'AddPackageCallback'],
        'wrapper' => 'packages-wrapper',
      ],
      '#submit' => [$this, 'AddPackageSubmited'],
      '#limit_validation_errors' => [],
    ];

    if ($nb_package > 1) {
      $form['retirer_package'] = [
        '#type' => 'button',
        '#value' => $this->t('Retirer une période'),
        '#attributes' => [
          'class' => ['btn btn-submit'],
          'event' => 'click',
          'id' => 'remove-package',
        ],
      ];
    }

    $form['ajouter'] = [
      '#type' => 'submit',
      '#value' => $this->t('Créer le bateau'),
    ];

    return $form;
  }

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

  }

  public function AddPackageCallback(array $form, FormStateInterface &$form_state) {
    $i = $form_state->get('nb_package');
    $i++;
    $form_state->set('nb_package', $i);
    \Drupal::logger('debug')->debug($i);
    return $form['packages'];
  }

  public function AddPackageSubmited(array $form, FormStateInterface $form_state) {
    $nb_package = $form_state->get('nb_package') + 1;
    $form_state->set('nb_package', $nb_package);
    $form_state->setRebuild();
  }

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

  }
}

```

Thanks :),

# Answer
I changed the callback and the submit method and now it works :) :

```
namespace Drupal\module\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ArmateurAddBoat extends FormBase {

  public function getFormId() {
    return 'armateur_add_boat';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $this->generationListes();
    $form_state->disableRedirect();
    $form['#attached']['library'][] = 'module/addboat';
    $form['#tree'] = TRUE;
 $form['packages'] = [
      '#tree' => TRUE,
      '#prefix' => '<div id="packages-wrapper">',
      '#suffix' => '</div>',
    ];

    $nb_package = $form_state->get('nb_package');

    if (is_null($nb_package)) {
      $nb_package = 1;
      $form_state->set('nb_package', $nb_package);
    }

for ($i = 0; $i < $nb_package; $i++) {

  $form['packages'][$i]['titre_package'] = [
    '#type' => 'textfield',
    '#prefix' => '<div class="package-item"><div class="row">',
    '#title' => $this->t('Nom de la période'),
    '#required' => TRUE,
  ];

  $form['packages'][$i]['date_debut_package'] = [
    '#type' => 'date',
    '#title' => $this->t('Début de la période'),
    '#required' => TRUE,
    '#prefix' => '<div class="col-md-4 col-lg-4">',
    '#suffix' => '</div>',
  ];

  $form['packages'][$i]['date_fin_package'] = [
    '#type' => 'date',
    '#title' => $this->t('Début de la période'),
    '#required' => TRUE,
    '#prefix' => '<div class="col-md-4 col-lg-4">',
    '#suffix' => '</div>',
  ];

  $form['packages'][$i]['horaire_package'] = [
    '#type' => 'select',
    '#title' => $this->t('Horaire'),
    '#options' => $this->_horaires,
    '#required' => TRUE,
    '#prefix' => '<div class="col-md-4 col-lg-4">',
    '#suffix' => '</div></div>',
  ];

  $form['packages'][$i]['cocktail_capacite_max_package'] = [
    '#type' => 'number',
    '#title' => $this->t('Capacité max'),
    '#min' => 0,
    '#required' => TRUE,
    '#default_value' => 0,
    '#prefix' => '<div class="row"><div class="col-md-4 col-lg-4">',
  ];

  $form['packages'][$i]['cocktail_capacite_min_package'] = [
    '#type' => 'number',
    '#title' => $this->t('Capacité min'),
    '#min' => 0,
    '#required' => TRUE,
    '#default_value' => 0,
    '#suffix' => '</div>',
  ];

  $form['packages'][$i]['repas_capacite_max_package'] = [
    '#type' => 'number',
    '#title' => $this->t('Capacité max'),
    '#min' => 0,
    '#required' => TRUE,
    '#default_value' => 0,
    '#prefix' => '<div class="col-md-4 col-lg-4">',
  ];

  $form['packages'][$i]['repas_capacite_min_package'] = [
    '#type' => 'number',
    '#title' => $this->t('Capacité min'),
    '#min' => 0,
    '#required' => TRUE,
    '#default_value' => 0,
    '#suffix' => '</div></div></div>',
  ];
}

$form['ajouter_package'] = [
  '#type' => 'submit',
  '#value' => $this->t('Ajouter une période'),
  //'#attributes' => ['class' => ['btn btn-primary'], 'id' => 'add-package'],
  '#ajax' => [
    'callback' => [$this, 'AddPackageCallback'],
    'wrapper' => 'packages-wrapper',
  ],
  '#submit' => [$this, 'AddPackageSubmited'],
  '#limit_validation_errors' => [],
];

if ($nb_package > 1) {
  $form['retirer_package'] = [
    '#type' => 'button',
    '#value' => $this->t('Retirer une période'),
    '#attributes' => [
      'class' => ['btn btn-submit'],
      'event' => 'click',
      'id' => 'remove-package',
    ],
  ];
}

$form['ajouter'] = [
  '#type' => 'submit',
  '#value' => $this->t('Créer le bateau'),
];

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

  }

 public function AddPackageCallback(array $form, FormStateInterface $form_state) {
    return $form['packages'];
  }

  public function AddPackageSubmited(array $form, FormStateInterface $form_state) {
    $c = $form_state->get('nb_package') + 1;
    $form_state->set('nb_package', $c);
    $form_state->setRebuild(TRUE);
  }

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

  }
}

```
> 0 votes

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


title: Replace intro with message

text:
# Question
Title: Replace intro with message
I have a custom module that creates a form. I want to display a message to a user, but I don't want to use the normal drupal\_set\_message method. I want to add a div with text and images to the top of the form after submission.

A user may be submitting this form multiple times. So after submission, I want to still be on this page. It's just that after the form is submitted, a new div will appear at the top.

I don't really know how to detect that the form was submitted. It's similar to replacing the form and displaying a thank you message.

What is the best way to achieve that with Drupal 8?

# Answer
You can request a rebuild in form submit and then add the message to the top of the form:

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

    if ($form_state->isRebuilding()) {
      $name = $form_state->getValue('name');
      $form['header'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['form-header-message', 'alert', 'alert-success']],
        'message' => [
          '#markup' => $this->t('Thank you for submitting this form, %name!', ['%name' => $name]),
        ],
      ];
    }

    $form['name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Name'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }

```
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Add content from one content type into another content type
**What is my current site setup:**

I am working on an academic website using Drupal 7 and I'm working on adding content from one content type into another content type.

I have a Books content type and also a People content type.

Book has the following fields:

* Image (image upload field)
* Title (textfield)
* Description (rich text)
* Publisher URL (text field)
* Publish Year (text field)
* People name (entity reference to the title on the People content type (multi select))

People has the following fields:

* Title (the person's full name) (textfield)
* Description (rich text)
* Email (text field)
* Phone number (text field)
* Office location (text field)
* Biography (rich text)
* Research (rich text)

My specific question: How do I relate the book content type to the people content type so that the list of books written by the respective person appear on the public version of the person's people content type page?

# Answer
You can achieve this using reference module

Install this module, enable the references and node reference checkbox in the Module menu.

Create the people and book content type with the respective field

In Book content type, Add the People name field, and choose the node reference , then it will the show all the content types.

Select the People content type, set the widget types as select list.

Then create a content in Book, People Name field will show the people title as options in select list..

DO this thing, Please ask me if you have any queries.

**Before that: Create some contents in People content type.**
> 1 votes

---
Tags: 7, views
---


# Question
Title: How do I add certain Fields to a View (not all fields are showing in Add list)?
I'm creating a view where I'd like to output a custom field. I am basing this off an already existing view, which already uses the said custom field.

However, when I hit the 'Add' button in the View's Fields section I do not see the same Fields as the already-built view.

Is there some way to associate the View with a certain group of Fields so that I can add them?

# Answer
> Is there some way to associate the View with a certain group of Fields

Yes, this is done by adding a **relationship**.

For example, if you create a content view and add a relationship of `Content: Author`, you will now be able to add user fields, such as `User: Picture` or `User: E-mail` to name a few.

Therefore, look if the already built in view is using a relationship. (It's under Advanced, located on the far right of the View's settings).
> 0 votes

---
Tags: 7, views, entities
---


# Question
Title: Missing FieldItem properties while in entity::preSave()
I have a custom **FieldItem** that has a single 'value' property that is also a custom **TypedData**.

This TypedData property holds an object. The `\Drupal\Core\TypedData\TypedDataInterface::getValue()` on the property(TypedData) returns a string fetched from the represented object and `\Drupal\Core\TypedData\PrimitiveInterface::getCastedValue()` returns the represented object.

All is working fine but one thing. In my entity which has this **FieldItem** attached, I update its value in the `entity::preSave()` operation.

And Drupal started to complain `Notice: Object of class ... could not be converted to int in drupal_schema_get_field_value().`

And I couldn't figure out why was the represented object used instead of the "plain" value.

After a bit of debugging I have found that when I set the FieldItem's value(I pass an object) in the `entity::preSave()` **the FieldItem's properties are not loaded** which will cause the `\Drupal\Core\Field\FieldItemBase::__get()` fetching the value from FieldItem `values` array instead of getting it from `properties`.

Any idea why the properties are not loaded? I was thinking that it has something to do with performance maybe but since the field item is just a wrapper around data types it makes no sense that field item would handle the data itself.

Edit: Looking more closely at entity values and properties it seems that only computed properties are initialized by default. But real properties are initialized only when `\Drupal\Core\TypedData\Plugin\DataType\Map::get()` is called. The values are meant for plain values when creating a new entity for example, if I understand it correctly, but I don't get why the properties are not utilized yet.

# Answer
> 0 votes
I will answer my own question...

I am not sure when the property initialization comes to play but adding this code into my field item solved it. The get method will look for the property and initialize it if it does not exists with existing value which will result in the field returning correct data.

```
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    $this->get('value');
  }

```

---
Tags: 8, entities
---


# Question
Title: How can I increase my hit ratio in Memcache?
Memcache has been up and operational on my production site http://goniseko.com for a few months now. After getting everything configured and memory limits where they should be, I noticed that I have a very consistent 70% / 30% hit to miss ratio.

How can I improve this?

Also, I noticed that this is pretty consistent across other Drupal 7 sites where I have memcache installed.

What is it about Drupal, Memcache, or a combination of the two that won't allow for this extra 30% to be stored in the cache bins? How can I figure out what these queries are, and what can I do to get them in the bins?

I am hoping this is similar to APC. I have that configured so that I have a 100% hit rate for this site. I would like to have Memcache that high, or at least higher than 70%. That's almost 1 out of 3 queries that have to hit the db.

# Answer
> 1 votes
I would interpret the numbers in a way that 70% of the traffic to your site are pages that are currently contained in the cache. The other 30% did go stale because the weren't visited frequently enough to stay fresh.

This is a more common problem about "How to cache?". The base Drupal cache is time based. If you don't use more complex methods like Drupal 8 tries to do for you there will always the problem that from time to time hits can't be cached. So probably 99% of you home page are cache hits. The 1% are the hits while the page is refresh. But any other page that is older than your settings on the "performance" settings page will be immediately stale. Means that if you cache for 5 minutes and the page is visited every 6 minutes it will never get a cache hit.

Your cache is currently more or less a protection against traffic spikes or (D)DOS attacks. But not something that really eases the web server in all occasions.

Real solutions for this go above this question and the easiest thing would be to go to Drupal 8. It really tries hard to cache your stuff for ever. http://buytaert.net/making-drupal-8-fly

All in all 70% is not that bad. You could try a module like boost: https://www.drupal.org/project/boost

And than find a way how to cache things until they are updated. But if you use a sidebar with views this will be a big problem if you don't go using asynchronous (AJAX / AHAH) calls by javascript or things like edge side includes (ESI)

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


title: Get url from image field in paragraphs

text:
# Question
Title: Get url from image field in paragraphs
I have a node with a field called "field\_paragraph" which is a paragraph reference. Referencing a paragraph type which has a field called "field\_image"

I'm trying to get the url of the field\_image in a custom module and so far i have this. But i don't seem to get it work.

```
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;
$node = Node::load($nid);
$paragraph_field = $node->get("field_paragraph")->getValue();
$paragraph = Paragraph::load($paragraph_field[0]['target_id']);

```

Here is where the problem occurs

```
$uri = $paragraph->field_image->entity->getFileUri();

```

The above returns nothing.

I used kint to print "$paragraph-\>field\_image-\>entity" and it returns null. What I'm I doing wrong? I tried all answers I could find on here to no avail.

After getting the uri I think calling the below line would be enough.

```
$url = file_create_url($uri);

```

**Question:** How do I get the url of an image field in paragraphs programmatically?

# Answer
> 2 votes
Your pretty much there but when calling the field name use the method get()

```
$uri = $paragraph->get('field_image')->entity->getFileUri();

```

Then once you have the uri you'll be able to get the full url

```
$url = file_create_url($uri);

```

---
Tags: 8, media, paragraphs
---


# Question
Title: View or module that shows which nodes are linking to the current node?
Has anyone found a way to show which pages (nodes) have internal links to another page (node)? This could be a view that shows a listing for each node of a particular content type and then all the nodes that have a link to it, or perhaps a block that shows on each page (when logged in) which shows all the other nodes that link to the currently viewed node.

This would be most valuable if it not only showed links found in a "body" field or even the actual node content type fields, but rather the entire page display including blocks, etc.

For SEO reasons its nice to know what pages you have linking to each other (as well as link text would be helpful). (Its good to know other external pages linking to your website, but that's not what I'm referring to in this question - only internal links.)

Curious if anyone else ever came up with a way to do something like this.

Thanks!

# Answer
Drupal is far too complex to do this in regards of all the modules there are.

You could use a module like this: https://www.drupal.org/project/intlinks

Still not all texts that are available on you page can be applied to this.

Only thing you could use is a rather weird and costly JS thing. I mean Google Analytics tracks any link on your site. So this already happens. But is this a wise idea for your internal linking? imho not.

For reliable links between Drupal Entities please rely on a node or entity reference field. By this you have links you can query and evaluate.
> 0 votes

---
Tags: views, nodes, navigation
---