再會!我剛開始自學 Symfony。
我正在制作一個新聞門戶。管理員可以從 Excel 檔案下載新聞。我正在將檔案轉換為關聯陣列。例如:
[ 'Title' => 'Some title',
'Text' => 'Some text',
'User' => '[email protected]',
'Image' => 'https://loremflickr.com/640/360'
]
接下來,我想將此陣列發送到表單并使用“約束”來驗證它。“標題”、“文本”、“影像”欄位沒有問題。我不知道如何正確檢查“用戶”欄位。檔案中的用戶正在提交電子郵件,但我想檢查資料庫中是否存在具有該電子郵件的用戶。
新聞匯入型別
class NewsImportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, [
'constraints' =>
[
new NotBlank(),
new Length(['min' => 256])
],
])
->add('text', TextareaType::class, [
'constraints' =>
[
new NotBlank(),
new Length(['max' => 1000])
],
])
->add('user', TextType::class, [
'constraints' =>
[
new NotBlank(),
new Email(),
],
->add('image', TextType::class, [
'constraints' =>
[
new NotBlank(),
new Length(['max' => 256]),
new Url()
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'allow_extra_fields' => true,
'data_class' => News::class,
]);
}
}
物體用戶和新聞通過一對多關系連接。
我正在考慮使用 ChoiceType 并以某種方式呼叫 UserRepository,但我不明白如何正確應用它。
請告訴我如何正確地為“用戶”欄位撰寫“約束”。謝謝!
uj5u.com熱心網友回復:
創建自定義約束。通過這種方式,它可以以您想要檢查用戶的任何其他形式重復使用。
在您的專案中創建一個新檔案夾,src/Validator然后將這兩個檔案放在那里。
約束
// src/Validator/userAccountExists.php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
class UserAccountExists extends Constraint
{
public $message = 'User account does\'t exists. Please check the email address and try again.';
}
驗證者
// src/Validator/userAccountExistsValidator.php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User;
class UserAccountExistsValidator extends ConstraintValidator
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function validate($email, Constraint $constraint)
{
if (!$constraint instanceof UserAccountExists) {
throw new UnexpectedTypeException($constraint, UserAccountExists::class);
}
if (null === $email || '' === $email) {
return;
}
if (!is_string($email)) {
throw new UnexpectedValueException($email, 'string');
}
if (!$this->userExists($email)) {
$this->context->buildViolation($constraint->message)->addViolation();
}
}
private function userExists(string $email): bool
{
$user = $this->entityManager->getRepository(User::class)->findOneBy(array('email' => $email));
return null !== $user;
}
}
在您的表單中,您現在可以使用驗證器
->add('user', TextType::class, [
'constraints' =>
[
new NotBlank(),
new Email(),
new UserAccountExists(),
],
記得添加use App\Validator\UserAccountExists;到您的表單中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467717.html
