简体   繁体   中英

How to combine two entities within one form?

I want to use two entities in one form and despite using tips from previous questions which were similar, it doesn't work. I have following controller:

<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\User;
use AppBundle\Form\UserType;
use AppBundle\Entity\School;
use AppBundle\Form\SchoolType;

class RegistrationController extends Controller
{

  /**
   * @Route("/register", name="user_register")
   */
  public function registerAction(Request $request)
  {
      $user = new User();
      $form = $this->createForm(new UserType(), $user);
      $form->add('status','hidden', array('attr' => array('value' => '0') ))
           ->add('school', new SchoolType());

      return $this->render('AppBundle:Main:register.html.twig', array('form' => $form->createView()));
  }

}

UserType.php

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;

class UserType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
      $builder
          ->add('login', 'text', array('attr' => array(
            'id' => 'login', 'name' => 'login', 'label' => 'Login:',
            'class' => 'form-control', 'required' => true
          )))
          ->add('password', 'password', array('attr' => array(
            'id' => 'password', 'name' => 'password', 'label' => 'Password:',
            'class' => 'form-control', 'required' => true
          )))
      ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_user';
    }
}

SchoolType.php

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SchoolType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array('attr' => array(
              'class' => 'form-control', 'id' => 'schoolName', 'name' => 'schoolName',
              'placeholder' => 'np. Szkoła podstawowa nr. 5 w Warszawie', 'label' => 'Nazwa Szkoły',
               'required' => true
            )))
            ->add('shortcut', 'text', array('attr' => array(
              'class' => 'form-control', 'id' => 'shortcut', 'name' => 'shortcut',
              'placeholder' => 'np. SP5Warszawa', 'label' => 'Skrót', 'required' => true
            )))
        ;

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\School'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'school';
    }
}

and finally twig template:

  {{ form_start(form) }}
    <div class="form-group">
        {{ form_row('form.school.name') }}
    </div>

    <div class="form-group">
      {{ form_row('form.school.shortcut') }}
    </div>

    <div class="form-group">
      {{ form_row('form.login') }}
    </div>

    <div class="form-group">
      {{ form_row('form.login') }}
    </div>

    {{ form_row('form.status') }}
  <span style="display:inline-block;">
    <button type="submit" class="btn btn-default">Create</button>
    {{ form_end(form) }}

Why it doesn't work? I receive following error:

Neither the property "school" nor one of the methods "getSchool()", "school()", "isSchool()", "hasSchool()", "__get()" exist and have public access in class "AppBundle\Entity\User".

Your User class must have a propriety called school.

/**
 * @ORM\Entity()
 * @ORM\Table(name="users")
 */
class User
{

/**
 * @ORM\OneToMany(targetEntity="Bundle\Entity\Schools",mappedBy="user")
 */
protected $school;

Then, generate entities for it,

php app/console doctrine:generate:entities Bundle:User

or write the functions manually:

public function setSchool($school)
{
    $this->school= $school;

    return $this;
}    

public function getSchool()
{
    return $this->school;
}

It's telling you exactly what you need to know. In your User entity, you either don't have a relation to your School entity or you are missing a getter & setter for School. Assuming it is a one to one relationship you should have something like:

   /**
     * @OneToOne(targetEntity="School", inversedBy="user")
     * @JoinColumn(name="school_id", referencedColumnName="id")
     **/
    private $school;

With getter & setter:

public function setSchool(School $school = null)
{
    $this->school = $school;

    return $this;
}

public function getSchool()
{
    return $this->school;
}

Note these should be automatically generated by the doctrine generate entities command . You may simply not have run this if you have the User->School relationship set up correctly and the setter/getter missing.

Please also read the documentation on association mapping

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