【问题标题】:OctoberCMS: How to prefill a child form field based on a parent form fieldOctoberCMS:如何根据父表单字段预填充子表单字段
【发布时间】:2021-08-05 23:17:40
【问题描述】:

我只是想在 OctoberCMS 后端建立一个关系,子表单应该从父表单获取一个值作为建议(默认)。

详细来说,有两个模型通过 belongsTo 关系链接(参加者属于锦标赛) 第一个涵盖体育赛事的父模型 (field.yaml):

tournament:
    # ... some other fields
    start_date:
        label: Start date
        type: date
    attendees:
        label: Attendees
        type: partial

参加者的第二个子模型:

attendee:
    name:
        label: Name
        type: text
    start_date:
        label: Start date
        type: date
        # how to get the value from tournament->start_date as preset?

父表格(在体育比赛中)具有开始日期以及相关的部分涵盖参加比赛的运动员。每个运动员还有一个单独的开始日期字段,我想在父锦标赛表格调用此表格时预先填写比赛的开始日期。但它必须是可编辑的,因为并非所有与会者都会在同一天开始。

有一个内置函数可以使用来自同一表单的另一个字段的值预设一个字段,但不幸的是我找不到如何从父表单获取值的解决方案。

提前致谢!

【问题讨论】:

    标签: octobercms octobercms-backend october-form-controller


    【解决方案1】:

    您可以将relationExtendManageWidget 方法添加到您的Tournament controller 中并扩展其行为。您现在可以在创建新记录时inject initial values for your new modal

    // ..code
    class Tournament extends Controller
    {
        // ..code
    
        public function __construct()
        {
            // ..code
        }
    
        public function relationExtendManageWidget($widget, $field, $model)
        {
          // make sure we are doing on correct relation
          // also make sure our context is create so we only copy name on create
          if($field === 'attendees' 
              && property_exists($widget->config, 'context') 
              && $widget->config->context === 'create'
          ) {         
            $widget->config->model->start_date = $model->start_date;
            // this is attendee ^ model            ^ this is main tournament model
          }
        }
    }
    
    

    现在,当您尝试从您的Tournament record 创建一个新的attendee record 时,您的参加者的start_date 将根据您的锦标赛的start_date 预先填充,并且只会在创建新记录时发生。

    如有任何疑问,请发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多