User field: display "Firstname Lastname" instead of "Username"

Hi,

I use the user field in a page and I would like to display the “Firstname Lastname” instead of the “Username” in the select drop down.

Does someone know how to achieve this ?

Thx

The user field only supports user names. You could, however, create a custom user field that extends the original one.

Ok, thanks for your advice, I’ve decided to create a custom field for my purpose.

For those interested, I have copy/paste the /panel/app/field/user/user.php file to create a custom field call “speaker” /site/fields/speaker/speaker.php

Of course, you can create your own same custom field by replacing the “speaker” occurence by something else.

class SpeakerField extends SelectField {

  public function __construct() {
    $this->type    = 'text';
    $this->icon    = 'user';
    $this->label   = l::get('fields.speaker.label', 'Speaker');
    $this->options = array();

    foreach(kirby()->site()->users() as $user) {
      $this->options[$user->firstName() . ' ' . $user->lastName()] = $user->firstName() . ' ' . $user->lastName();
    }

  }

  public function value() {
    $value = parent::value();
    return empty($value) ? site()->user()->firstName() : parent::value();
  }

}

So that, I can use it in a blueprint like this:

...
fields:
      speaker:
        label: Speakers
        type: speaker
        help: The speaker must be registered to appear into this list.
...

Same custom field but displays username if firstname and lastname are empty and names are sorted alphabetically. And esc() input fields:

class SpeakerField extends SelectField {

  private $speakers = array();

  public function __construct() {
    $this->type    = 'text';
    $this->icon    = 'user';
    $this->label   = l::get('fields.speaker.label', 'Speaker');
    $this->options = array();

    foreach(kirby()->site()->users() as $user) {
      $speaker_firstname = !empty($user->firstName()) ? esc($user->firstName()) : '';
      $speaker_lastname = !empty($user->lastName()) ? esc($user->lastName()) : esc($user->username());
      if (!empty($speaker_firstname) && !empty($speaker_lastname)):
        $this->speakers[$speaker_lastname  . ' ' . $speaker_firstname] = $speaker_lastname . ' ' . $speaker_firstname;
      else:
        $this->speakers[$user->username()] = esc($user->username()) . ' (Firstname and/or Lastname are missing, please complete the profile)';
      endif;
    }

    sort($this->speakers);

    foreach($this->speakers as $user) {
      $this->options[$user] = $user;
    }

  }

  public function value() {
    $value = parent::value();
    return empty($value) ? site()->user()->firstName() : parent::value();
  }

}
2 Likes