2017-09-15 47 views
1

我目前正在執行我的第一個Symfony項目,並正在努力使用我想要實現的特殊功能。
我有一個表單,人們必須輸入許可證密鑰以及其他數據以激活某項服務。
當表單提交時,我需要驗證所有數據,驗證的一部分是檢查給定的許可證密鑰是否有效(存在於許可證密鑰數據庫中)。Symfony 3表單驗證:檢查現有數據庫條目

我的形式坐落在一個單獨的表格類,看起來像這樣(剝離下來的重要部件):

<?php 

namespace AppBundle\Form; 

use AppBundle\Entity; 
use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\Extension\Core\Type; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\OptionsResolver\OptionsResolver; 
use Symfony\Component\Validator\Constraints as Constraint; 
use Symfony\Component\Validator\Context\ExecutionContextInterface; 

class Activation extends AbstractType 
{ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults([ 
      'data_class' => Entity\Customer::class, 
      'translation_domain' => 'forms' 
     ]); 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('activationCode', Type\TextType::class, [ 
       'mapped' => false, 
       'constraints' => [new Constraint\Callback(
        function ($object, ExecutionContextInterface $context, $payload) { 

        } 
       )] 
      ]) 
      ->add('firstName', Type\TextType::class) 
      ->add('lastName', Type\TextType::class) 
      ->add('email', Type\RepeatedType::class, [ 
       'type' => Type\EmailType::class, 
       'invalid_message' => 'The E-Mail fields must match.', 
       'first_options' => ['label' => 'E-Mail'], 
       'second_options' => ['label' => 'Repeat E-Mail'], 
      ]) 
      ->add('activate', Type\SubmitType::class); 
    } 

} 

正如你可以看到我的第一個想法是使用一個回調約束和做檢查的關閉。
這是一個足夠的方法來做到這一點?
如果是的話我怎樣才能從該關閉內部訪問數據庫/學說實體管理器?
或者你會推薦一個完全不同的方法?

回答

0

你可以爲這個用例編寫你自己的自定義約束和驗證器類。

https://symfony.com/doc/current/validation/custom_constraint.html

驗證器是一種服務,所以你可以根據你的需要注入任何其他服務。 (i.E. entityManager)。 這樣你的表單不必處理驗證邏輯本身。

+0

作爲服務的驗證器是我錯過的信息。 非常感謝我的工作。 – Hawklan