php Symfony2,如何向表单添加隐藏的日期类型字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10709773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2, How to add a hidden date type field to a form?
提问by pmoubed
I am trying the scenario below :
我正在尝试以下场景:
In myclassType
在 myclassType
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('day','hidden')
->add('date', 'hidden' )
->add('hours')
->add('comment','textarea')
;
}
In myclass
在 myclass
class myclass
{
//.. Other stuff
/**
* @ORM\Column(type="date")
*
* @var date $date
*/
protected $date;
}
While rendering I get this error :
渲染时出现此错误:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error:
Object of class DateTime could not be converted to string in
C:\wamp\www\PMI_sf2\app\cache\dev\twig\fb57f80f2358a6f4112c3427b387.php line 684") in
form_div_layout.html.twig at line 171.
Any idea how I can make a Date type field hidden !??
知道如何隐藏日期类型字段吗??
回答by a.aitboudad
Form
形式
$builder
->add('day','hidden')
->add('date',null,array( 'attr'=>array('style'=>'display:none;')) )
...
回答by martti
Create a simple DataTransformer from DateTime object to string and a new form type named i.e. 'hidden_datetime' which uses the new DataTransformer and has the hidden form type as a parent.
创建一个从 DateTime 对象到字符串的简单 DataTransformer 和一个名为“hidden_datetime”的新表单类型,它使用新的 DataTransformer 并将隐藏的表单类型作为父级。
<?php
namespace YourProject\YourBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
class DateTimeToStringTransformer implements DataTransformerInterface
{
public function __construct()
{
}
/**
* @param \DateTime|null $datetime
* @return string
*/
public function transform($datetime)
{
if (null === $datetime) {
return '';
}
return $datetime->format('Y-m-d H:i:s');
}
/**
* @param string $datetimeString
* @return \DateTime
*/
public function reverseTransform($datetimeString)
{
$datetime = new \DateTime($datetimeString);
return $datetime;
}
}
..
..
<?php
namespace YourProject\YourBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use YourProject\YourBundle\Form\DataTransformer\DateTimeToStringTransformer;
class HiddenDateTimeType extends AbstractType
{
public function __construct()
{
}
public function getName()
{
return 'hidden_datetime';
}
public function getParent()
{
return 'hidden';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new DateTimeToStringTransformer();
$builder->addModelTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
));
}
}
register the new 'hidden_datetime' form type as a service in services.yml
在 services.yml 中将新的“hidden_datetime”表单类型注册为服务
yourproject.hidden_datetime.form.type:
class: YourProject\YourBundle\Form\Type\HiddenDateTimeType
tags:
- { name: form.type, alias: hidden_datetime }
The new hidden_datetime type can then be used in your form:
然后可以在您的表单中使用新的 hidden_datetime 类型:
// IN myclassType
// 在我的类类型中
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('createdAt','hidden_datetime')
->add('comment','textarea')
;
}
回答by olaurendeau
Even easier. Based on martti solution
更容易。基于martti的解决方案
Simply extends DateTimeType and define parent as 'hidden'.
只需扩展 DateTimeType 并将父级定义为“隐藏”。
<?php
namespace YourProject\YourBundle\Form\Type\HiddenDateTimeType
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
class HiddenDateTimeType extends DateTimeType
{
public function getName()
{
return 'hidden_datetime';
}
public function getParent(array $options)
{
return 'hidden';
}
}
Register form type as a service :
将表单类型注册为服务:
yourproject.hidden_datetime.form.type:
class: YourProject\YourBundle\Form\Type\HiddenDateTimeType
tags:
- { name: form.type, alias: hidden_datetime }
And you will have full access to all specific DateTimeType options
您将拥有对所有特定 DateTimeType 选项的完全访问权限
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('from' , 'hidden_date', array(
'widget' => 'single_text',
'format' => 'Y-m-d',
'label' => 'popin.from',
'required' => true
));
回答by Frédéric Marchal
None of the previous solutions worked with Symfony 3.3. I ended up creating a simple type:
之前的解决方案都不适用于 Symfony 3.3。我最终创建了一个简单的类型:
<?php
namespace <YourProject>\<YourBundle>\Form\Type;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class HiddenDateTimeType extends HiddenType implements DataTransformerInterface
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer($this);
}
/**
* {@inheritdoc}
*/
public function transform($data)
{
return $data->format("Y-m-d H:i:s");
}
/**
* {@inheritdoc}
*/
public function reverseTransform($data)
{
try {
return new \DateTime($data);
} catch (\Exception $e) {
throw new TransformationFailedException($e->getMessage());
}
}
public function getName()
{
return 'hidden_datetime';
}
}
Use it in your form like this:
在您的表单中使用它,如下所示:
<?php
namespace <YourProject>\<YourBundle>\Form;
use <YourProject>\<YourBundle>\Form\Type\HiddenDateTimeType;
class ReportType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('creationTime', HiddenDateTimeType::class, array(
'required' => true,
));
}
}
There is nothing to add to services.yml.
没有什么可添加的services.yml。
回答by Maciej Pyszyński
Form
形式
public function buildForm(FormBuilder $builder, array $options){
$builder
->add('day','hidden')
->add('date')
->add('hours')
->add('comment','textarea');
}
View:
看法:
<form action="{{ path('some-save-action') }}" method="post" {{ form_enctype(form) }}>
<div style="display: none">
{{ form_row(form.date) }}
</div>
{{ form_errors(form) }}
{{ form_rest(form) }}
<input type="submit" value="Save" class="button confirm big"/>
</form>
回答by Ryan
You can control form output more directly than this. It's quite easy to theme specific fields. There are two steps. You need to make sure the form field is expecting a single string representation of the date. So set the date widget to single_text. Then override the date field to output a hidden field instead of a text field.
您可以比这更直接地控制表单输出。为特定领域设置主题非常容易。有两个步骤。您需要确保表单字段需要日期的单个字符串表示形式。因此,将日期小部件设置为single_text. 然后覆盖日期字段以输出隐藏字段而不是文本字段。
Form
形式
$builder->add('date', 'date', array('widget' => 'single_text'));
Twig
枝条
{% form_theme form _self %}
{# Makes all dates hidden, you can also name your field specifically #}
{% block date_row %}
{{ block('hidden_widget') }} {# This is normally 'field_widget' #}
{% endblock %}
See http://symfony.com/doc/current/cookbook/form/form_customization.html#form-theming
请参阅http://symfony.com/doc/current/cookbook/form/form_customization.html#form-theming

