希望我的解释清楚(!),我会尽我所能:
我正在使用Symfony框架,直到现在我已经完成了所有工作。那么我的问题是什么?
我使用表单集合(ProjectType和DocumentType): 一个项目可以有很多文档。
要获取表单,我使用了generate:crud命令,然后调整了此页面上的实体,类型等:http://symfony.com/doc/current/cookbook/form/form_collections.html
这一切都成功了:我可以创建新项目,并以相同的形式添加许多文档。按下提交按钮后,数据将保留在MySQL数据库中。
在我的学说中,我在文档实体中创建了一个外键,名为:project_id。这些关联是正确的,因为当我向表单添加id时,下拉列表会显示现有项目。
但我希望表单还将外键保存在我的文档表中(这当然是新创建的项目PK)。因此,当我使用文档创建一个新项目时,文档的外键是来自新项目的PK。
编辑:当我在数据库中手动添加外键然后删除项目时,带有外键的文档被删除(只是指出关联正确..!)
请帮帮我,谢谢!
----------------- ProjectController.php:
/**
* Displays a form to create a new Project entity.
*
* @Route("/new", name="project_new")
* @Method("GET")
* @Template()
*/
public function newAction() {
$entity = new Project();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Project entity.
*
* @param Project $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Project $entity) {
$form = $this->createForm(new ProjectType(), $entity, array(
'action' => $this->generateUrl('project_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create project'));
return $form;
}
/**
* Creates a new Project entity.
*
* @Route("/", name="project_create")
* @Method("POST")
* @Template("AcmeDemoBundle:Project:new.html.twig")
*/
public function createAction(Request $request) {
$entity = new Project();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$entity->setDateCreated(new \DateTime());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('project_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
----------------- ProjectType.php:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name')
->add('date_executed')
->add('imageprojects', 'collection', array(
'type' => new DocumentType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Project',
'cascade_validation' => false,
));
}
/**
* @return string
*/
public function getName() {
return 'project';
}
--------------- Project.php(实体):
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* @ORM\Column(type="string")
*/
protected $name;
/**
*
* @ORM\Column(type="date")
*/
protected $date_executed;
/**
*
* @ORM\Column(type="date")
*/
protected $date_created;
/**
* @ORM\OneToMany(targetEntity="Document", mappedBy="project_id", cascade={"persist", "remove"})
*/
protected $imageprojects;
public function __construct() {
$this->imageprojects = new ArrayCollection();
}
function __toString() {
return $this->getName();
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Project
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set date_executed
*
* @param \DateTime $dateExecuted
* @return Project
*/
public function setDateExecuted($dateExecuted)
{
$this->date_executed = $dateExecuted;
return $this;
}
/**
* Get date_executed
*
* @return \DateTime
*/
public function getDateExecuted()
{
return $this->date_executed;
}
/**
* Set date_created
*
* @param \DateTime $dateCreated
* @return Project
*/
public function setDateCreated($dateCreated)
{
$this->date_created = $dateCreated;
return $this;
}
/**
* Get date_created
*
* @return \DateTime
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* Add projectimages
*
* @param \Acme\DemoBundle\Entity\Document $projectimages
* @return Project
*/
public function addImageproject(Document $projectimages)
{
//$this->imageprojects[] = $imageprojects;
$projectimages->addProjectimage($this);
$this->imageprojects->add($projectimages);
return $this;
}
/**
* Remove projectimages
*
* @param \Acme\DemoBundle\Entity\Document $projectimages
*/
public function removeImageproject(Document $projectimages)
{
$this->imageprojects->removeElement($projectimages);
}
/**
* Get imageprojects
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getImageprojects()
{
return $this->imageprojects;
}
------------------ Document.php(实体)
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\ManyToOne(targetEntity="Project", inversedBy="imageprojects")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $project_id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank
*/
public $name;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
public function getAbsolutePath() {
return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->path;
}
public function getWebPath() {
return null === $this->path ? null : $this->getUploadDir() . '/' . $this->path;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded
// documents should be saved
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir() {
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'imgupload';
}
/**
* @Assert\File(maxSize="6000000")
*/
private $file;
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
// check if we have an old image path
if (is_file($this->getAbsolutePath())) {
// store the old name to delete after the update
$this->temp = $this->getAbsolutePath();
} else {
$this->path = 'initial';
}
}
/**
* Get file.
*
* @return UploadedFile
*/
public function getFile() {
return $this->file;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->getFile()) {
$this->path = $this->getFile()->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload() {
if (null === $this->getFile()) {
return;
}
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->temp);
// clear the temp image path
$this->temp = null;
}
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
$this->getFile()->move(
$this->getUploadRootDir(), $this->id . '.' . $this->getFile()->guessExtension()
);
$this->setFile(null);
}
/**
* @ORM\PreRemove()
*/
public function storeFilenameForRemove() {
$this->temp = $this->getAbsolutePath();
}
/**
* @ORM\PostRemove()
*/
public function removeUpload() {
if (isset($this->temp)) {
unlink($this->temp);
}
}
/**
* Get id
*
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Document
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName() {
return $this->name;
}
/**
* Set path
*
* @param string $path
* @return Document
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
* Get path
*
* @return string
*/
public function getPath() {
return $this->path;
}
/**
* Add projectimages
*
* @param \Acme\DemoBundle\Entity\Project $projectimages
* @return Document
*/
public function addProjectimage(Project $projectimages) {
$this->projectimages[] = $projectimages;
/*
if (!$this->projectimages->contains($projectimages)) {
$this->projectimages->add($projectimages);
}
*/
return $this;
}
/**
* Remove projectimages
*
* @param \Acme\DemoBundle\Entity\Project $projectimages
*/
public function removeProjectimage(Project $projectimages) {
$this->projectimages->removeElement($projectimages);
}
/**
* Get projectimages
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getProjectimages() {
return $this->projectimages;
}
/**
* Set project_id
*
* @param \Acme\DemoBundle\Entity\Project $projectId
* @return Document
*/
public function setProjectId(\Acme\DemoBundle\Entity\Project $projectId = null) {
$this->project_id = $projectId;
return $this;
}
/**
* Get project_id
*
* @return \Acme\DemoBundle\Entity\Project
*/
public function getProjectId() {
return $this->project_id;
}