Symfony 2预填充表单,包含数据库中的数据

时间:2015-09-30 08:56:04

标签: php database forms symfony

我正在尝试使用数据库中的数据填充表单字段以进行编辑。我已经在google上搜索过了。

这是我的控制器返回空字段

public function userViewAction($id,Request $request){

    $em = $this->getDoctrine()->getManager()->getRepository('BFVMailingBundle:MailingList');
    $user = $em->findById($id);

    $form = $this->get('form.factory')->createBuilder('form',$user)
        ->add('unsubscribed','checkbox')
        ->add('name','text')
        ->add('givenName','text')
        ->add('additionalName','text',array('required'=>false))
        ->add('familyName','text',array('required'=>false))
        ->add('emailValue','text')
        ->add('language','choice',array(
            'choices'  => array('en_GB' => 'en_GB', 'es_ES' => 'es_ES', 'fr_FR' => 'fr_FR'),
            'required' => true,
        ))
        ->add('commentary','textarea',array('required'=>false))
        ->add('save','submit')
        ->getForm();


    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            // perform some action, such as save the object to the database
            $em->flush();
            return $this->redirect($this->generateUrl('user_view',array('id'=>$id)));
        }
    }

这是我的模板

<div class="cell">  
    {{ form_start(form, {'attr': {'class': 'form-horizontal'}}) }}
    {{ form_end(form) }}
</div>

我错过了什么吗?

编辑 - 请阅读此解决方案

正如John Noel暗示的那样,我使用命令

构建了一个外化形式
php app/console doctrine:generate:form BFVMailingBundle:MailingList

我的实体是MailingList而不是User

MailingListType是在BFV \ MailingBundle \ Form中生成的表单模板。我自己添加了数据类型。

<?php
namespace BFV\MailingBundle\Form;

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

class MailingListType extends AbstractType
{
/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $str = date("U");
    $codeValue = sha1($str);

    $builder
        ->add('secretCode','hidden',array( 'data' => $codeValue ))
        ->add('name','text')
        ->add('givenName','text')
        ->add('additionalName','text',array('required'=>false))
        ->add('familyName','text',array('required'=>false))
        ->add('emailValue','text')
        ->add('language','choice',array(
            'choices'  => array('en_GB' => 'en_GB', 'es_ES' => 'es_ES', 'fr_FR' => 'fr_FR'),
            'required' => true,
        ))
        ->add('unsubscribed','checkbox')
        ->add('commentary','textarea',array('required'=>false))
        ->add('save','submit')
    ;
}

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

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

在重新格式化的控制器中,我添加了表单生成器,添加了MailingList $ user [0]的实例而不是$ user。我在许多网站上看到,通常你将$ variable直接放在表单生成器中,但会产生以下错误:

The form's view data is expected to be an instance of class 
BFV\MailingBundle\Entity\MailingList, but is a(n) array. You can avoid 
this error by setting the "data_class" option to null or by adding a
view transformer that transforms a(n) array to an instance of 
BFV\MailingBundle\Entity\MailingList

因此在控制器中:

    public function userViewAction($id,Request $request){
    if (!$id) {
        throw $this->createNotFoundException('No id !!');
    }

    $em = $this->getDoctrine()->getManager()->getRepository('BFVMailingBundle:MailingList');
    $user = $em->findById($id);
    if (!$user){
        throw $this->createNotFoundException('No user with the id selected');
    }

    $form = $this->createForm(new MailingListType(), $user[0]);

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em->flush();
            return $this->redirect($this->generateUrl('user_view',array('id'=>$id)));
        }
    }

    return $this->render('BFVMailingBundle:Default:user_view.html.twig',array(
        'user'=>$user,
        'form'=>$form->createView()
            ));
}

结论:我从数据库中获取了填充数据的视图表单。

2 个答案:

答案 0 :(得分:1)

要执行此操作,您需要查看form classes,然后Symfony forms将充当您提供的数据的视图(并且还会填充)。因此,在您的示例中,您将创建一个表单类UserType

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('unsubscribed','checkbox')
            ->add('name','text')
            ->add('givenName','text')
            ->add('additionalName','text',array('required'=>false))
            ->add('familyName','text',array('required'=>false))
            ->add('emailValue','text')
            ->add('language','choice',array(
                'choices'  => array('en_GB' => 'en_GB', 'es_ES' => 'es_ES', 'fr_FR' => 'fr_FR'),
                'required' => true,
            ))
            ->add('commentary','textarea',array('required'=>false))
            ->add('save','submit')
        ;
    }

    public function getName()
    {
        return 'user';
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Your\Entity\Class',
        ));
    }
}

然后在您的控制器中,您可以执行以下操作:

$form = $this->createForm(new UserType(), $user);

然后你的控制器的其余部分。绝对可以阅读表单类,因为这是{{3}}的许多高级功能的起点。

答案 1 :(得分:0)

我不确定这是否有所不同,但你是否尝试过:

-(void)purchaseItem:(SKProduct *)product {

     NSLog(@";Buying %@...", product.productIdentifier);

    if (product == nil) {
        [self noProductsFound];
    } else {

        SKPayment *payment = [SKPayment paymentWithProduct:product];
       [[SKPaymentQueue defaultQueue] addPayment:payment];// here getting the crash warning...

    }
}

您还可以检查是否从数据库中正确读取了您获得的用户。

例如:

$form = $this->createFormBuilder($user)
             ->add(...)
             ->getForm()