我试图通过Symfony 4文档创建一个具有自己模板视图的自定义表单类型,但搜索和尝试创建一个后出现了许多错误。
以下是我的自定义表单类型文件ImageChoiceType.php
:
<?php
namespace App\Form\Type;
use App\Entity\Media;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ImageChoiceType extends AbstractType
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
// 'data_class' => Media::class,
'class' => Media::class,
'choices' => $this->entityManager->getRepository(Media::class)
->findAll(),
));
}
public function getParent()
{
return EntityType::class;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'image_choice';
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'image_choice';
}
}
这是我的字段模板:
{% block image_choice_widget %}
<div class="image_widget">
<div class="radio">
<label for="post_image_placeholder" class="">
<input type="radio" id="post_image_placeholder" name="post[image]" value=""
{{ form.vars.value == "" ? "checked='checked'" : ""}}> None
</label>
</div>
<div class="image-container">
{% for key,choice in form.vars.choices %}
<div class="radio col-xs-2">
<label for="post_image_{{ key }}" class="">
<input class="image-radio-buttons" type="radio" id="post_image_{{ key }}" name="post[image]"
value="{{ key }}" {{ form.vars.value == key ? "checked='checked'" : ""}}>
<img src="{{ asset(constant('App\\Constants::UPLOAD_MEDIA')~choice.label) }}" class="image-thumbs img-responsive"/>
</label>
</div>
{% endfor %}
<div class="clearfix"></div>
</div>
</div>
{% endblock %}
有趣的是,如果我通过更改第一行为
{% block entity_widget %}
覆盖Symfony的内置类型之一,并在我的表单构建器中使用EntityType
,它可以正常工作。但是,当我开始用自己的自定义类型填充它时,它就会出现很多无关的错误!需要帮助或指示吗?