skip to Main Content

I’m trying to set by default the username of the user by default in a empty field is the field is empty but I get an error message when I try do so.

->add('username', TextType::class, [
'label' => 'username',
 data'=> function(User $user){
return is_null($user->getUsername()) ? $user->getUsername(): "";}

I’ve tried to do it differently like this way but doesn’t do anything.

$builder->add('username, TextType::class, [
    'attr' => [
        'class' => 'form-control form-opacity',
        'autofocus' => true
    ],
    'data' => (is_null($builder->getData()->getUsername()) ? $builder->getData()->getUsername() : "username"
]);

2

Answers


  1. Your ternary seems false, if is_null($user->getUsername()) you can’t ask for $user->getUsername() because it’s null.

    try:

    return is_null($user->getUsername()) ? "" : $user->getUsername();
    
    Login or Signup to reply.
  2. You need to use callback to get data, use expression and order of arguments wrong, change getUsername to correct one. You also can change somehow cheking:

    data = is_null($un = $user->getUsername()) ? "": $un;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search