2

I'm running Symfony 3.4 LTS. Among my entities I get :

  • UserEntity
  • ProductEntity

In the ProductEntity :

/**
 * @var array
 *
 * @ORM\Column(name="experts", type="simple_array")
 */
private $experts;

/**
 * Set groupexperts
 *
 * @param array $groupexperts
 *
 * @return Product
 */
public function setGroupexperts($groupexperts)
{
    $this->groupexperts = $groupexperts;

    return $this;
}

/**
 * Get groupexperts
 *
 * @return array
 */
public function getGroupexperts()
{
    return $this->groupexperts;
}

For example, the column experts in database could be [2,7,9] where #2, #7 and #9 and IDs of users considered as experts for the related product. In my ProductForm :

$builder->add('experts', EntityType::class, array(
    'class' => 'AppBundle:User',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('u')
        ->orderBy('u.username', 'ASC')
        ->andWhere('u.active = 1')
    },
    'choice_label' => function($user) {
        return $user->getFirstname();
    }
));

I don't want to make a ManyToMany relationship because I don't want another SQL table. The form displays well in the front-end and visitors can select one or several users in a HTML list. BUT users #2, #7 and #9 are not selected by default.

The generated select list looks like fine with good ID:

<select>
    <option value="1">John</option>
    <option value="2">Matthew</option>
    <option value="3">Brad</option>
    <option value="4">Georges</option>
    <option value="5">Luke</option>
    ...
</select>

How to make the mapping between the users list (generated by the createQueryBuilder()) and the user IDs array stored in the database ?

1 Answer 1

1

I think you need to configure the choice_value option to return entity id. The default choice value for EntityType is the entity object but you need only id.

'choice_value' => function (?UserEntity $user) {
    return $user ? $user->getId() : '';
},

https://symfony.com/doc/3.4/reference/forms/types/entity.html#choice-value

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for the answer. The generated select is already returning the good ID of users. Moreover, I can't use the choice_value option (multiple errors). I updated my code in the original topic with the full source and more details.
PS: the probleme disapears if I set multiple = false and set only 2 for example in the database field. I don't understand why. Is the issue on the side of the entity getters/setters ? I updated original post with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.