我试图创建一个简单的s2表单作为包含数据的表的过滤器。
由于我没有适当的实体,我已经制作了一个简单的模型类 - YearModel
namespace MyBundle\Model\Filter;
class YearModel
{
/**
* @var array
*/
private $years = array();
/**
* @return array
*/
public function getYears()
{
return $this->years;
}
/**
* @param $year
* @return YearModel
*/
public function addYear( $year )
{
/** .... logic to add new year... */
}
/**
* @param $year
* @return YearModel
*/
public function removeYear( $year )
{
/** .... logic to remove one ... */
}
}
然后为该特定过滤器创建了一个FormType:
namespace MyBundle\Form\Filter;
use /** sue statements */
class YearFilterType extends AbstractType
{
const FILTER_TYPE_NAME = 'years_formfilter';
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder->add('years', 'choice', array(
'required' => true,
'placeholder' => false,
));
}
public function setDefaultOptions( OptionsResolverInterface $resolver )
{
$resolver->setDefaults(array(
'csrf_protection' => false,
'data_class' => "MyBundle\\Model\\Filter\\YearModel"
));
}
public function getName()
{
return self::FILTER_TYPE_NAME;
}
}
我的控制器看起来像这样:
class MyController extends Controller
{
public function indexAction(Request $o_request)
{
// jsut for demo purpose
$o_now = new \DateTime();
// create a new instance of YearModel
$o_filter_model = new MyBundle\Model\Filter\YearModel();
// prepopulate with some mandatory data
$o_filter_model->addYear( (int) $o_now->format('Y') );
// create s2-form
$o_filter_form = $this->_createFilterForm( $o_filter_model );
if( $o_request->getMethod == 'post' )
{
$o_filter_form->handleRequest( $o_request );
}
/** .... vodoo-magic ... */
$a_twig_vars = array(
'a_data_for_the_table' => $a_found_entries,
'o_filter_form' => $o_filter_form->createView(),
);
return $this->render("MyBundle:MyController:index.html.twig", $a_twig_vars)
}
private function _createFilterForm( MyBundle\Model\Filter\YearModel $o_filter_model)
{
$a_form_option = array(
'method' => 'POST',
'attr' => array(
'novalidate' => 'novalidate',
'accept-charset' => 'UTF-8',
),
);
$o_filter_model = $this->createForm( new MyBundle\Form\Filter\YearFilterType(), $o_filter_model, $a_form_option );
$o_filter_model->add('submit', 'submit', array(
'label' => 'refresh',
));
return $o_filter_model;
}
}
正如你所知 - 它是一个非常基本的东西,但由于某些原因,下拉列表总是空的,即使$o_filter_model->getYears()
返回一个多年的关联数组
我失踪了什么?!
更新 另一个想法,我忘了提到:
这样,我总是"添加"当年控制器内!所有其他年份都将从DB中读取(为了实现这一点,我尝试使用FormEvent::PRE_SET_DATA
事件)
/** in the formBuild-method ... */
cb_pre_set_data = function( FormEvent $o_event ) use ($em) {
// get model-object
// find all other years...
};
$builder->addEventListener(FormEvents::PRE_SET_DATA, $cb_pre_set_data);