Jan*_*ota 3 forms rest checkbox boolean symfony
我对Symfony(v 2.3.2)表格有一个奇怪的问题.没有关系,这是非常简单的形式.我还应该注意,此表单仅用于REST API.
所以我有一个已发布的字段(布尔值).在实体上,默认设置为false.
在更新时,REST API客户端发送正确的PUT请求...&[entity]published=0&...
.此值也在表单参数中的Symfony分析器中显示.
但是我注意到数据库中的实际值设置为true(或者因为它是tinyint).
所以,为了找出问题所在,我在之后添加了throw语句 $form->submit($request);
throw new \Exception(sprintf('Request: %s, form: %s', $request->get('entity')['published'], $form->get('published')->getData()));
要么
throw new \Exception(sprintf('Request: %s, form: %s', $request->get('entity')['published'], $form->getData()->getPublished()));
异常消息说:Request: 0, form: 1
.这意味着在submit方法的某处,字符串值'0'被转换为1.
该领域是用 $builder->add('published', 'checkbox', [ 'required' => false ])
我也注意到奇怪的事情,这可能是相关的.在Symfony profiler,面板请求中,我收到错误:Warning: json_encode(): Invalid UTF-8 sequence in classes.php line 3758
我没有发送任何奇怪的字符 - 只是单词"test".
小智 5
您不应该在API中使用复选框表单类型,0并不意味着错误.
您应该实现一个新的布尔表单类型,它将1,'1'和true转换为true,其他所有内容都转换为false(例如).
这是一个例子:https://gist.github.com/fsevestre/abfefe0b66e5f5b24c60