Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Symfony2获取symfony表单中未映射的字段值_Php_Mysql_Forms_Symfony - Fatal编程技术网

Php Symfony2获取symfony表单中未映射的字段值

Php Symfony2获取symfony表单中未映射的字段值,php,mysql,forms,symfony,Php,Mysql,Forms,Symfony,在一个symfony2房地产项目中工作,我需要弄清楚如何在数据库中以动态创建的表单存储提交的数据表单 class OptionValues { protected $value; // Many-to-one protected $option; } 这是我到目前为止所做的工作,我有一个带有一组预定义字段的房地产属性addListings表单,我在其中嵌入了一组来自options的附加字段。这些“附加字段”由管理员动态决定,他可以添加x个字段,他可以在下拉列表、复选

在一个symfony2房地产项目中工作,我需要弄清楚如何在数据库中以动态创建的表单存储提交的数据表单

class OptionValues
{
    protected $value;


    // Many-to-one
    protected $option;
}
这是我到目前为止所做的工作,我有一个带有一组预定义字段的房地产属性
addListings
表单,我在其中嵌入了一组来自
options
的附加字段。这些“附加字段”由管理员动态决定,他可以添加x个字段,他可以在下拉列表、复选框或文本类型之间进行选择

这里是选项和类别表单类型,一切都很好,不用担心,只是您提交到数据库的常规表单值

/**
 * Inside OptionsType.php
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('value')
        ->add('submit', 'submit', ['label'=>'Create Option'])
    ;
}

/**
 * Inside CategoriesType.php
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name')
        ->add('required')
        ->add('isMultiple')
        ->add('isText')
        ->add('submit', 'submit',['label'=>'Create Category'])
    ;
}
这里是表示附加字段
PropertyCategory.php
的实体,这里有getter和setter,不用担心

<?php
 namespace path\to\Entity;

 use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="property_category")
 * @ORM\Entity
 */
class PropertyCategory {

/**
 * @var type integer
 * 
 * @ORM\ID
 * @ORM\Column(name="id", type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="University", inversedBy="propertyCategory")
 */
protected $university;

/**
 * @ORM\ManyToOne(targetEntity="Property", inversedBy="propertyCategory")
 */
protected $property;

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="propertyCategory")
 */
protected $category;

/**
 * @ORM\OneToOne(targetEntity="Options", inversedBy="propertyCategory")
 */
protected $options;
这是控制器
AdditionalDetailsController.php

class AdditionalDetailsController extends Controller
{
   /**
    * @Route("/AddCategory", name="addCategory")
    * @Template()
    */
 public function addCategoryAction(Request $request) {

    $em = $this->getDoctrine()->getEntityManager();
    $category = new Category();
    $form = $this->createForm(new CategoryType(), $category);
    $form->handleRequest($request);

    if($form->isValid()){
        $em->persist($category);
        $em->flush();

        return $this->redirect($this->generateUrl('addOption', array('id'=>$category->getId())));
    }
    return array('form'=>$form->createView());
}

/**
 * @Route("/AddOption/{id}", name="addOption")
 * @Template()
 */
public function addOptionAction(Request $request, $id){

    $em = $this->getDoctrine()->getEntityManager();
    $options = new Options();
    $form = $this->createForm(new OptionsType(), $options);
    $form->handleRequest($request);

    if($form->isValid()){
        $category = $this->getDoctrine()->getRepository('EduflatsBundle:Category')->findOneById($id);
        $university = $this->getDoctrine()->getRepository('EduflatsBundle:University')->findOneById(siteConfig::$university_id);
        $options->setCategory($category);
        $options->setUniversity($university);
        $em->persist($options);
        $em->flush();

        $this->get('session')->getFlashBag()->set('success', 'Your options have been saved Successfully');
        return $this->redirect($this->generateUrl('addOption',array('id'=>$id)));
    }
    return array('form'=>$form->createView());

}

/**
 * @Route("/form", name="form")
 * @Template()
 */
public function propertyCategoryFormAction(Request $request) {

    $options = $this->getDoctrine()->getRepository('EduflatsBundle:Options')->findAll();

    $em = $this->getDoctrine()->getEntityManager();
    $propertyCategory = new PropertyCategory();
    $form = $this->createForm(new PropertyCategoryType($options), $propertyCategory);
    $form->handleRequest($request);

    if($form->isValid()){
        $property = $this->getDoctrine()->getRepository('EduflatsBundle:Property')->findOneById(1);
        $propertyCategory = new PropertyCategory();

        $propertyCategory->setProperty($property);
        $propertyCategory->setOptions();

        $em->persist($propertyCategory);
        $em->flush();
    }
    return array('form'=>$form->createView());
}
}

我希望我说得足够清楚,我可以澄清评论中的内容。

以下是我的想法。事实上,我有一份工作想要做类似的事情,但我们最终放弃了,因为这是一件很难管理的事情。但这是我的计划

从主实体开始

class Listing
{
    protected $name;
    protected $price;

    //Your custom options (One-to-Many)
    protected $options;

    public function __construct()
    {
        $this->options = new ArrayCollection();
    }

    // Getters and Setters ...
}
然后我们有两个实体负责处理定制选项。与上市相关的期权本身

class Option
{
    protected $name;
    protected $fieldType;
    protected $required;
    // Other form options you may want...

    //Related Values (One-to-many)
    protected $optionValues;

    // Many-to-one
    protected $listings;

    public function __construct()
    {
        $this->optionValues = new ArrayCollection();
    }

    // Getters and Setters ...
}
class ListingType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name' , 'text')
            ->add('price', 'text');
            //Your other standard fields...
            foreach($options['extraFields'] as $field)
            {
                $builder->add($field->getName() , new OptionValueType(), array('mapped' => false, 'options' => array('field' => $field));
            }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired('extraFields');

        $resolver->addAllowedTypes(array(
            'extraFields' => '\Doctrine\Common\Collections\Collection'
        ));

        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Listing',
            'cascade_validation' => true
        ));
    }

    public function getName()
    {
        return 'listing';
    }
}
以及存储在数据库中的该选项的值

class OptionValues
{
    protected $value;


    // Many-to-one
    protected $option;
}
然后,我们从中构建列表

class Option
{
    protected $name;
    protected $fieldType;
    protected $required;
    // Other form options you may want...

    //Related Values (One-to-many)
    protected $optionValues;

    // Many-to-one
    protected $listings;

    public function __construct()
    {
        $this->optionValues = new ArrayCollection();
    }

    // Getters and Setters ...
}
class ListingType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name' , 'text')
            ->add('price', 'text');
            //Your other standard fields...
            foreach($options['extraFields'] as $field)
            {
                $builder->add($field->getName() , new OptionValueType(), array('mapped' => false, 'options' => array('field' => $field));
            }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired('extraFields');

        $resolver->addAllowedTypes(array(
            'extraFields' => '\Doctrine\Common\Collections\Collection'
        ));

        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Listing',
            'cascade_validation' => true
        ));
    }

    public function getName()
    {
        return 'listing';
    }
}
我们要求您传递
$option['extraFields']
,它应该是从控制器中的
$yourListing->getOptions()
获得的
AppBundle\Entity\option
的集合。然后,我们可以循环这些字段并创建一个新的未映射字段,将该字段的其余部分传递给
AppBundle\Entity\OptionValue
表单,就像这样

class OptionValueType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        //Obviously do whatever other settings you need.  The important part is remembering that this belongs in the $value
        //of our OptionValue entity.
        $builder->add('value' , $field->fieldType, array('required' => $field->getIsRequired()));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired('field');

        $resolver->addAllowedTypes(array(
            'field' => '\AppBundle\Entity\Option'
        ));

        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\OptionValue',
            'cascade_validation' => true
        ));
    }

    public function getName()
    {
        return '';
    }
}
有些重要的事情需要注意。在这两种形式中,我们都使用
$resolver->setRequired()
$resolver->setAddAllowedTypes()
来定义额外的选项字段,否则Symfony将抛出错误。此外,在列表表单中,我们设置
'cascade\u validation'=>true
,以确保我们的子表单也得到验证,如果您需要的话。你可能还需要做一些疯狂的自定义验证,这是一整套其他的技巧


这最终允许在我们的控制器中使用的是限制疯狂的自定义表单操作的数量,相反,如果您正确设置持久化以级联到列表和选项实体中,您应该能够持久化列表,它将确保所有选项和OptionValue实体也持久化到数据库中。只要你做得对。我遗漏了很多细节,因为要写的东西太多了,但希望这能给你一些想法。

我必须解决工作中的服务器问题:p如果你需要更多细节,我会尽量扩展这个答案。我有点想看看这是否适合我自己,这样我可以在未来的项目中使用它。@mojo我将尝试构建一个小型项目,完成后我会在这里发布链接。可能需要一到两天的时间,因为我只会在两辈子之间做这件事。或者,如果我的回答已经让你思考,并且你能够开发出一些东西,请告诉我。否则,期待在一天左右的时间里有一个完整的例子。干杯。嘿,我能做到这一点,我用了一种稍微不同的方式,如果我也能得到你的答案,那就太好了,我今天晚些时候会发布一个链接到我的github项目。@mojo好的,很抱歉我最近没有回复,工作太忙了。我很高兴听到你有工作。除非有人突然发明了克隆机,否则我想知道我是否有机会做一个例子。哈哈,我明白了,我会在这里发布我的项目链接,这样任何人都可以使用它,如果我幸运的话,他们可能会对我的git存储库做出贡献。我也有类似的问题。想调查一下吗?