2016-08-01 18 views
2

我有2個值和相關下拉字段一個簡​​單的下拉字段:SilverStripe依賴下拉 - x不是一個有效的選項

public function areaForm() { 
    $datasource = function($val) { 
     if ($val =='yes') { 
      $areas = DataObject::get('Area', 'ParentID = 0'); 
      return $areas->map('ID', 'Name'); 
     } 
     if ($val == 'no') { 
      return false; 
     } 
    }; 

    $fields = new FieldList(
     TextField::create('Name', 'Area Name:'), 
     $dropField = DropdownField::create('isChild', 'Is this a sub Area?', array('yes' => 'Yes', 'no'=>'No')) 
      ->setEmptyString('Select one'), 
     DependentDropdownField::create('ParentSelect', 'Select Parent Area:', $datasource) 
      ->setDepends($dropField) 
      ->setEmptyString('Select one') 
    ); 

    return new Form($this, __FUNCTION__, $fields, FieldList::create(new FormAction('doSaveArea', 'Save area'))); 
} 

public function doSaveArea($data, $form) { 
    var_dump($data); 
    exit; 
    $name = $data['Name']; 
    $isChild = $data['isChild']; 

    if ($isChild === 'no') { 
     $area = new Area(); 
     $area->Name = $name; 
     $area->ParentID = 0; 
     $area->write(); 
    } 
    elseif ($isChild === 'yes') { 
     $area = new Area(); 
     $area->Name = $name; 
     $area->ParentID = $data['ParentSelect']; 
     $area->write(); 
    } 
    $this->redirectBack(); 
} 

當過我嘗試通過提交表單保存我的對象,它給我相同的消息:

請在列表中選擇一個值。 x不是有效選項

這些值正在填充正確。通過檢查元素,我可以在瀏覽器中看到它們。但是,如果我選擇ID 1例如它說「1不是有效的選項」等每個區域對象。它被卡在驗證中,甚至沒有進入操作。我在網站/其他網站的其他部分做了類似的事情,並且他們工作得很好。

爲什麼此驗證不正確地阻止表單提交,我們該如何解決這個問題?

回答

1

好像你只需要創建一個Map對象Array

if ($val =='yes') { 
    $areas = Area::get()->filter('ParentID', '0'); 
    return $areas->map('ID', 'Name')->toArray(); 
} 

通常情況下,你可以只使用Map對象爲源的DropdownField。但我認爲DependentDropdownFieldMap對象有一些問題。