0

I have a multi-value textfield that stores the user agent string. I want to store the user agent every time the user logs in (this may not in fact be a good idea, but for sake of example).

The following code will save the user agent, but only in the first position. It replaces the old value instead of creating a new one.

function MYMODULE_user_login($account) {
  $account->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
  $account->save();
}

How can I add a new value each time this is called?

1 Answer 1

1

Using this:

$account->get('field_useragent')->appendItem($_SERVER['HTTP_USER_AGENT']);

However, that doesn't seem like a good idea to me. Over time, that list will grow big, multi-value fields don't scale that well. All values are always loaded, on save, all values are inserted again into the database.

Maybe you want a list of unique user agents, but even that is hard to control with versions and so on. If you want a log, then save it somewhere else in your own table.

http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf doesn't have this yet, would probably make sense to add it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.