简体   繁体   中英

How to set the selected EntityType field in symfony 3

I have EntityType class in my form type which generate data from one of my table.

My problem is when I try to insert it in my database using doctrine way, that entity type field returns {} value.

Here's the exact database error:

An exception occurred while executing 'INSERT INTO sub_agent (company_id, name, email_address, telephone_no, mobile_no, website, registered, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [{}, "test", "test@gmail.com", "test", "test", null, "2017-01-09 09:15:42", "127.0.0.1"]:

When I debug that entity field using var_dump in controller I saw that the company_id is returning an object from my company entity class .

Here's my sub_agent_type form

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('company_id', EntityType::class, array(
        'label' => 'Company',
        'mapped' => false,
        'required' => true,
        'class' => 'SwipeBundle\Entity\Company',
        'choice_label' => 'name',
        'choice_value' => 'id',
        'expanded' => false,
        'multiple' => false,
        'placeholder' => 'Choose a Company',
        'constraints' => array(
            new NotBlank(array("message" => 'Company name is required.')),
        ),            
    ));  
}

How do I set the selected value of my entity field (dropdown) to my form to save in my database? Here's the generated twig of my entity field.

<select id="sub_agent_company_id" name="sub_agent[company_id]" required="required">
    <option value="" selected="selected">Choose a Company</option>
    <option value="20">ABC</option>
    <option value="21">EFG</option>
    <option value="22">HIJ</option>
</select>

Here's my controller:

 if ($form->isSubmitted() && $form->isValid()) {

    $data = $form->getData();

    $sub_agent_name = $data->getName();

    $company_id = $data->getCompanyId();

    var_dump($company_id); exit

In your category entity, you should have:

public function __toString() {
   return $this->id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM