好吧,這有點複雜,請耐心等待。我會盡量保持清晰和簡潔。symfony表單元素選項
我正在使用Symfony2的非常好的表單生成器系統,但基本的文件上傳元素並不完全符合我的需求,所以我想通過添加縮略圖預覽和其他一些細節來擴展它。
讀這篇文章,我發現我可以創建自己的自定義模板塊渲染文件中的元素:
http://symfony.com/doc/master/cookbook/form/form_customization.html#twig
這是真的很酷,而且似乎是完美的工作。不過,我在此基礎上存儲爲我的文件上傳的路徑在實體單獨的屬性:
http://symfony.com/doc/master/cookbook/doctrine/file_uploads.html
所以,我需要一些方法爲模板訪問的路徑字段。我創建了一個自定義的文件類型的類是這樣的:
<?php
namespace TechPeople\InvoiceBundle\Component\Form\Type;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Extension\Core\Type\FileType as SymfonyFileType;
class FileType extends SymfonyFileType {
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'type' => 'file',
'value' => '',
'path' => $options['path'],
));
}
}
然後,我通過了文件路徑爲表單生成器是這樣的:
<?php
namespace TechPeople\InvoiceBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class InvoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
echo 'test';
$builder
->add('month')
->add('year')
->add('expenses')
->add('due')
->add('paid')
->add('created')
->add('expense_amount', 'money')
->add('total_amount', 'money')
->add('attachment', 'file', array('path'=>$options['data']->getAttachmentPath()))
->add('vendor')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'TechPeople\InvoiceBundle\Entity\Invoice'
));
}
public function getName()
{
return 'techpeople_invoicebundle_invoicetype';
}
}
嗯,這似乎很時髦,但後來我得到這個錯誤加載表格:
The option "path" does not exist. Known options are: "attr", "block_name", "by_reference", "cascade_validation", "compound", "constraints", "csrf_field_name", "csrf_protection", "csrf_provider", "data", "data_class", "disabled", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "intention", "invalid_message", "invalid_message_parameters", "label", "label_attr", "mapped", "max_length", "pattern", "post_max_size_message", "property_path", "read_only", "required", "translation_domain", "trim", "validation_constraint", "validation_groups", "virtual"
500 Internal Server Error - InvalidOptionsException
因此,它看起來像有一個允許的選項列表,但我找不到它。此外,我並不是100%確定InvoiceType中的add()方法正在將選項數組傳遞給FileType中的buildView()方法。我在追查這兩件事情之間的代碼時遇到了麻煩。
是的,允許的選項是在每種類型定義(和它的層次):https://github.com/symfony/Form/blob/master/Extension/Core/Type/FileType.php#L47 – Florian