1

我对如何修改以下生成表单以允许$Show->DateTimes()自动生成一组新字段并根据可用日期的数量填充价格的代码有点困惑。

我不确定这是否可能。虽然我在注释中添加了 foreach 来解释我认为它应该如何工作,但我认为我只是把我的 PHP 搞混了。

我现在有这个代码:

编辑:最终固定代码:

public function RegistrationForm() {
    $date_id = (int) $this->getRequest()->requestVar('DateID');

    if(!$date = DataObject::get_by_id("ShowDateTime", $date_id)) {
        return $this->httpError(404);
    }

    $date_map = array();
    if($Show = $date->Show()) {
        if($all_dates = $Show->DateTimes()) {
            $date_map = $all_dates->toDropdownMap('Price','DateLabel');
        }   
    }

    $fields = new Fieldset (
        new TextField('Event', _t('Show.Event','Name of Event'),$Show->Title),
        new EmailField('Name', _t('Show.Name','Name')),
        new EmailField('Email', _t('Show.Email','Email')),
        new TextField('Address', _t('Show.Address','Address')),
        new TextField('Telephone', _t('Show.Telephone','Telephone')),
        new DropdownField('DateID', _t('Show.CHOOSEDATE','Choose a show'), $date_map, $date_id)         
    );

    // Loop through the time/events creating a fieldset for: class,horse,number,price
    $i =0;
    foreach($all_dates as $show_price){
        $fields->push(new TextField('Class_'.$i, 'Class'));
        $fields->push(new TextField('Horse_'.$i, 'Horse'));
        $fields->push(new TextField('Number_'.$i, 'Number'));
        $fields->push(new CurrencyField('Price_'.$i, 'Price',$show_price->Price));
        $i++;
    }


    $form = new Form (
        $this,
        "RegistrationForm",
        $fields,        
        new FieldSet (
            new FormAction('doRegister', _t('Show.REGISTER','Register'))
        ),
        new RequiredFields('Event','Name','DateID')
    );

    return $form;
}
4

1 回答 1

2

在里面$form = new Form (你不能放置一个循环表达式。您只能在其中放置简单的表达式,例如 a $variableor new。但是没有什么需要更高级别的执行。

因此,首先将对象列表生成到它自己(或一个数组)的变量中,然后将其添加到$form.

The Form constructor expects to get a FieldSet object containing the fields. You can create a new one and add the fields to it and then pass this object into the constructor. Consider the following, alternative approach:

   $controller = $this;
   $name = 'RegistrationForm';
   $fields = new FieldSet();
   // add fields to $fields, setup $actions ...
   $form = new Form($controller, $name, $fields, $actions);
于 2011-06-14T16:04:19.963 回答