Symfony2:使用Ajax和Forms创建相关实体而不加载所有实体

时间:2017-05-03 10:34:25

标签: symfony doctrine-orm

我们有一个Symfony2应用程序,允许管理员使用Ajax POST请求通过付款来记入用户的帐户。 POST请求发送由Symfony控制器处理的JSON。控制器应该创建一个"付款"实体,验证它并坚持下去。我们希望利用Symfony表单系统的内置验证。

作为一个例子,信用ID为20的用户100p,POSTed JSON应该看起来像......

{"user":"20","amount":"100","description":"test payment","paymentType":"credit"}

在Symfony端,我们有一个PaymentType表单;

class PaymentType extends AbstractType

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('user', 'entity', [
        'class' => 'OurAppBundle\Entity\User',
        'choice_label' => 'email',
        'multiple'     => false,
        'expanded'     => true,
    ]);
    $builder->add('paymentType', 'choice', [
        'choices' => [ 1 => 'credit', 2 => 'debit'],
        'choices_as_values' => true,

    ]);
    $builder->add('amount', 'number');
    $builder->add('description', 'textarea');
}

付款实体与用户实体相关并包含验证;

class Payment
{
const TYPE_CREDIT = 'credit';
const TYPE_DEBIT = 'debit';

use TimestampableTrait;

/**
 * The ID of the payment
 *
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;


/**
 * the User object
 *
 * @var User
 *
 * @ORM\ManyToOne(targetEntity="User", inversedBy="payments")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
 */
protected $user;

/**
 * payment type
 *
 * either 'credit' - a credit to the user's account
 * or 'debit' - money taken out their account
 *
 * @var string
 *
 * @ORM\Column(name="payment_type", type="string", length=7, nullable=false)
 *
 * @Assert\Choice(choices= {"credit", "debit"}, message="Choose a valid payment type")
 */
protected $paymentType;

/**
 * amount
 *
 * amount of payment, in pence
 *
 * @var int
 *
 * @ORM\Column(name="amount", type="integer", nullable=false)
 *
 * @Assert\Range(
 *      min = 1,
 *      max = 2000,
 *      minMessage = "Payments must be positive",
 *      maxMessage = "You cannot credit/debit more than £20"
 * )
 */
protected $amount;

/**
 * a string describing the transaction
 *
 * @var string
 *
 * @ORM\Column(name="description", type="string", length=255, nullable=false)
 *
 * @Assert\NotBlank(message="Please enter a description")
 */
protected $description;
....

我们在控制器中有代码;

public function creditUserAction(Request $request)
{
      $body = $request->getContent();
      $formData = json_decode($body, true);

      $payment = new Payment();
      $form = $this->createForm(new PaymentType(), $payment);
      $form->submit($data);
      if ($form->isValid()) {
          // persist and flush .....

      } ....

问题是,当createForm加载PaymentType表单时,Doctrine会尝试从数据库加载所有用户,并且有成千上万的用户。

所以,我的问题是 - 是否有更好的方法来创建一个实体,使用Ajax POST请求,该实体与使用Symfony Forms的另一个实体相关,其中相关实体有数千个实例?

1 个答案:

答案 0 :(得分:1)

您可以在不创建表单的情况下验证您的实体

$validator = $this->get('validator');
$errors = $validator->validate($payment);
if(count($errors)) {
    //...
}