KnowledgeSeeker
KnowledgeSeeker

Reputation: 107

SilverStripe dependent dropdown - x is not a valid option

I have a simple dropdown field with 2 values and a dependent dropdown field:

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();
}

When ever I try to save my object by submitting the form, it gives me the same message:

Please select a value within the list provided. x is not a valid option

The values are being populated correctly. I can see them in the browser by inspecting the element. Yet if I select ID 1 for example it says "1 is not a valid option" etc for each Area object. It gets stuck at validation, doesn't even go to the action. I've done similar things in other parts of the site/other sites and they work fine.

Why is this validation incorrectly blocking the form submission and how do we fix this?

Upvotes: 3

Views: 541

Answers (1)

Fatal Error
Fatal Error

Reputation: 1024

Seems like you just need to create an Array of your Map object.

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

Normally you could just use the Map object as the source for a DropdownField. But I think the DependentDropdownField has a little trouble with the Map object.

Upvotes: 2

Related Questions