管理员可以编辑其网站的用户,但不能编辑密码。所以我创建了这个EditUserFormType:
namespace CAPUserBundle\Form\Type;
use CAPShopAdminBundle\Repository\DiscountGridRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class EditUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email', EmailType::class);
$builder->add('discountGrid', EntityType::class, array(
'class' => 'CAPShopAdminBundle:DiscountGrid',
'choice_label' => 'name',
'placeholder' => '-- Aucune --',
'required' => false,
'query_builder' => function (DiscountGridRepository $r) {
$qb = $r->createQueryBuilder('d');
$qb->orderBy('d.name', 'ASC');
return $qb;
},
'attr' => array("autocomplete" => "off"),
));
$builder->add('isActive', ChoiceType::class, array(
'choices' => array(
'Actif' => '1',
'Désactivé' => '0'
),
));
$builder->add('name', TextType::class);
$builder->add('firstname', TextType::class);
$builder->add('company', TextType::class);
$builder->add('address', TextType::class);
$builder->add('postcode', TextType::class);
$builder->add('city', TextType::class);
$builder->add('phone', TextType::class);
$builder->add('fax', TextType::class);
$builder->add('save', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'CAPUserBundle\Entity\User',
]);
}
public function getName()
{
return 'edit_user_form';
}
}
但是当我验证表单时,我的User实体的plainPassword字段出错。
This value should not be blank. edit_user
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).data.plainPassword =
实际上,它有一个NotBlank验证约束,以强制用户在注册时设置密码。
我的问题是:如何绕过此约束来编辑我的用户? EditUserFormType上不存在密码字段,因此plainPassword无用。但我被卡住了,因为我使用相同的用户实体设置了NotBlank值。
目前,我强制使用plainPassord字段:
$user->setPlainPassword('Ap@ssw0rd');
但这是一种绕过约束的可怕方法......
答案 0 :(得分:3)
答案 1 :(得分:0)
我选择了一种完全不同的方法,在数据模型中放弃类似注释的验证规则,并使用表单类中的约束。例如:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$dateConstraintFrom = new Date();
$notBlankDateFrom = new NotBlank();
$builder->add('date_from', TextType::class, array(
'required' => true,
'label' => 'bookform.place.date_from',
'constraints' => array($notBlankDateFrom, $dateConstraintFrom),
'attr' => array(
'placeholder' => 'bookform.place.date_from',
'id' => 'bookform_place_date_from',
'required' => 'required',
),
));
...........
}
我习惯于这种做事方式,它比注释和验证组更舒服。