如何替换数组中的变量?

时间:2019-03-08 13:01:59

标签: php arrays symfony oop formbuilder

我正在尝试减少一些代码,以使其看起来更干净:

  if($target == "edit"){
                $formBuilder->add('getTimestamp', DateType::class, array(
                  'widget' => 'single_text',
                  'format' => 'dd.MM.yyyy',
                  'html5' => false,
                  'attr' => array('class' => 'js-date form-control', 'style' => 'line-height: 20px;'), 'label' => $field['fieldName'],
                ));
              } else {
                $formBuilder->add('getTimestamp', DateType::class, array(
                  'widget' => 'single_text',
                  'data' => new \DateTime(),
                  'format' => 'dd.MM.yyyy',
                  'html5' => false,
                  'attr' => array('class' => 'js-date form-control', 'style' => 'line-height: 20px;'), 'label' => $field['fieldName'],
                ));

              }

这是我的方法:

if($target == "edit"){
      $newdate = ['data' => new \DateTime()];
 } 


 $formBuilder->add('getTimestamp', DateType::class, array(
                'widget' => 'single_text',
                $newdate,
                'format' => 'dd.MM.yyyy',
                'html5' => false,
                'attr' => array('class' => 'js-date form-control', 'style' => 'line-height: 20px;'), 'label' => $field['fieldName'],
              ));

问题是,当我尝试减少代码时,日期未在我的字段中创建。

3 个答案:

答案 0 :(得分:6)

尝试其他方法。修改并以数组形式传递选项。

$options =  [
    'widget' => 'single_text',
    'format' => 'dd.MM.yyyy',
    'html5'  => false,
    'attr'   => ['class' => 'js-date form-control', 'style' => 'line-height: 20px;'], 'label' => $field['fieldName'],
];

if ($target == 'edit') {
    $options['data'] = new \DateTime();
}

$formBuilder->add('getTimestamp', DateType::class, $options);

答案 1 :(得分:3)

对于add,变量$newdate未初始化。

初始化它。

$newdate = '';
if($target == "edit"){
      $newdate = new \DateTime();
 } 

答案 2 :(得分:1)

您可以初始化$ newdate,如果有值,则可以推入选项数组。

if ($target == "edit") {
    $newdate = ['data' => new \DateTime()];
}
$options = [
    'widget' => 'single_text',
    'format' => 'dd.MM.yyyy',
    'html5'  => false,
    'attr'   => ['class' => 'js-date form-control', 'style' => 'line-height: 20px;'], 'label' => $field['fieldName'],
];
if(!empty($newdate)){
    $options = array_merge($options, $newdate);
}
$formBuilder->add('getTimestamp', DateType::class, $options);