If there is a unlimited user text field named "user_log_field", How can I add a new value for it?
I'm planning to log the IP and location for each user every time they login. Is using an unlimited user text field a good idea for this purpose?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIf there is a unlimited user text field named "user_log_field", How can I add a new value for it?
I'm planning to log the IP and location for each user every time they login. Is using an unlimited user text field a good idea for this purpose?
Architectually speaking, it would be much better if you use custom table for this functionality.You can take a look for inspiration (or even use) the following module:
https://www.drupal.org/project/uiplog
From the description of the project: User IP Log is a simple module that logs the IP address of users on login event to table {uiplog}.
Updated answer: Since you want to do it yourself. You can implement a hook_user_login in your custom module. https://api.drupal.org/api/drupal/core%21modules%21user%21user.api.php/function/hook_user_login/8.2.x
Inside you can just paste the following code.
Assumptions/ notes :
I have added quite a few sanity checks that I think would be helpful on the long run.
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
// The machine name of the field.
$field_name = 'field_field_1';
// Sanity check against the machine name of the field.
if ($user->hasField($field_name)) {
$field_config = \Drupal\field\Entity\FieldStorageConfig::loadByName('user', $field_name);
// Checks if has unlimited cardinality, otherwise the appendItem will throw
// weird error.
if ($field_config->getCardinality() == '-1') {
// This is a fancy way to return $_SERVER['REMOTE_ADDR'].
// Keep in mind that on localhost, this will return ::1.
$a = \Drupal::request()->getClientIp();
$user->$field_name->appendItem(\Drupal::request()->getClientIp());
}
$user->save();
}
Regards,
Oleg
An unlimited user text field would be best in my opinion. The way I would implement it would be to write a hook to alter the user login form. In this hook you would assign an IP address to your user field and save it.
Edit: This is the best option, in the absence of a module wich already provides this functionality. If a module already exists, use it.