在Symfony表单类型中删除空格,可以通过以下步骤实现:
// src/Form/DataTransformer/TrimTransformer.php
namespace App\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
class TrimTransformer implements DataTransformerInterface
{
public function transform($value)
{
// 在输出时不进行任何转换
return $value;
}
public function reverseTransform($value)
{
// 删除输入值中的空格
if (is_string($value)) {
$value = trim($value);
}
return $value;
}
}
// src/Form/YourFormType.php
namespace App\Form;
use App\Form\DataTransformer\TrimTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class YourFormType extends AbstractType
{
private $trimTransformer;
public function __construct(TrimTransformer $trimTransformer)
{
$this->trimTransformer = $trimTransformer;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('yourField', TextType::class)
;
// 将数据转换器应用于字段
$builder->get('yourField')->addModelTransformer($this->trimTransformer);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// ...
]);
}
}
// src/Controller/YourController.php
namespace App\Controller;
use App\Form\YourFormType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class YourController extends AbstractController
{
/**
* @Route("/your-route", name="your_route")
*/
public function yourAction(Request $request): Response
{
$form = $this->createForm(YourFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 处理表单提交的数据
$data = $form->getData();
// ...
}
return $this->render('your_template.html.twig', [
'form' => $form->createView(),
]);
}
}
这样,当用户提交表单时,输入字段中的空格将被删除,并且您可以继续在控制器中处理表单提交的数据。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云