我创建了一个名为“gamesetting”的新表单字段类型。此类型应根据数据数组的值处理文本输入和复选框。表单构建正确,但是当我提交表单时,如果输入的值不为空,我总是会收到错误“此值无效”。如果未选中复选框或文本字段为空,则表单有效。
表单仅使用键值数组作为数据输入,而不是模型/实体对象。
<?php
namespace asdf\WebinterfaceBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class GamesettingType extends AbstractType {
function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setRequired([ 'field_type' ]);
$resolver->setDefaults([
'label' => false,
'field_type' => 'text',
'required' => false
]);
}
function getName() {
return 'gamesetting';
}
function getParent() {
return 'form';
}
function buildView(FormView $view, FormInterface $form, array $options) {
$view->vars['field_type'] = $options['field_type'];
}
}
Action 方法如下:
public function settingsAction(Request $request) {
$user = $this->get('security.context')->getToken()->getUser();
$game = GameFactory::factory(PortlistFactory::byUserAndActive($user->getUsername()));
// Generate the settings form. Each setting has a internal identifier,
// a type (which form element) and a label. The label is equal to the
// identifier and will be translated with the corresponding i18n key.
$form = $this->createFormBuilder();
foreach ($game->getSettings()->read('config') as $key => $value) {
$sanitized_key = str_replace('.', '_', $key);
$sanitized_value = in_array($value, ['true', 'false']) ? !!($value == 'true') : $value;
$type = (in_array($value, ['true', 'false'])) ? 'checkbox' : 'text';
if ($type == "text") {
$form->add($sanitized_key, 'gamesetting', [
'field_type' => 'text',
'data' => $sanitized_value,
]);
} elseif ($type == "checkbox") {
$form->add($sanitized_key, 'gamesetting', [
'field_type' => 'checkbox',
'data' => $sanitized_value,
]);
}
}
$form = $form->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
var_dump($form->getData());
exit;
}
return [
'game' => $game,
'form' => $form->createView()
];
}
最佳答案
当你创建 Symfony 表单元素时,它们有各种带有默认值的属性。其中之一是“必需”,默认为 true。
http://symfony.com/doc/2.7/reference/forms/types/text.html#required
如果您使用的浏览器支持 HTML5 表单验证,如果您尝试为任何具有 required=true 的 Symfony 表单元素提交空值,它将显示错误。出于这个原因,我总是在构造表单字段时设置 required=false。这让您可以控制表单验证。
关于php - Symfony 2 自己的字段类型 - 总是 "This value is not valid"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20163209/
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file