我有一個1對n的關係,所以一個Brand
有很多Cars
。我想要做的只是創建一個Web窗體,其中來自兩個實體的所有字段都會顯示出來。要做到這一點,我創建了一個表單類型,但我認爲我做錯了什麼,因爲我試圖在樹枝中打印表單域時出錯。誰能告訴我我在哪裏做錯了?通過附加兩個實體無法生成一個網絡表單
錯誤:
Method "brand" for object "Symfony\Component\Form\FormView" does not exist in CarBrandBundle:Default:both.html.twig at line 1
實體:
class BrandEntity
{
protected $name;
protected $origin;
//Followed by getters and setters
/**
* @ORM\ManyToOne(targetEntity="BrandEntity", inversedBy="car")
* @ORM\JoinColumn(name="brand_id", referencedColumnName="id", nullable=false)
* @var object $brand
*/
protected $brand;
}
class CarEntity
{
protected $model;
protected $price;
//Followed by getters and setters
/**
* @ORM\OneToMany(targetEntity = "CarEntity", mappedBy = "brand")
* @var object $car
*/
protected $car;
public function __construct()
{
$this->car = new ArrayCollection();
}
public function addCar(\Car\BrandBundle\Entity\CarEntity $car)
{
$this->car[] = $car;
return $this;
}
public function removeCar(\Car\BrandBundle\Entity\CarEntity $car)
{
$this->car->removeElement($car);
}
}
表單類型:
namespace Car\BrandBundle\Form\Type;
use Car\BrandBundle\Entity\BrandEntity;
use Car\BrandBundle\Entity\CarEntity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Test\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class BothType extends AbstractType
{
public function builder(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('brand', new BrandEntity())
->add('car', new CarEntity())
->add('button', 'submit', array('label' => 'Add'))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
//'data_class' => 'Car\BrandBundle\Entity\CarEntity',
'cascade_validation' => true
));
}
public function getName()
{
return 'both';
}
}
控制器:
namespace Car\BrandBundle\Controller;
use Car\BrandBundle\Form\Type\BothType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class BothController extends Controller
{
public function indexAction()
{
$form = $this->getFrom();
return $this->render('CarBrandBundle:Default:both.html.twig',
array('page' => 'Both', 'form' => $form->createView()));
}
private function getFrom()
{
return $this->createForm(new BothType(), null,
array('action' => $this->generateUrl('bothCreate')));
}
}
嫩枝:
{{ form_row(form.brand.name) }}
{{ form_row(form.brand.origin) }}
{{ form_row(form.car.model) }}
{{ form_row(form.car.price) }}
我做的事情更簡單[這裏](http:// stackoverflow.com/questions/24316726/using-two-entities-to-create-a-single-form)。 – BentCoder