Jackson D Jackson D - 3 months ago 31
PHP Question

Dynamically set values of objects added via Silverstripe GridField (CMS)

I have a basic relation editor

GridField
, and I need to dynamically define/set the value of any objects added via that
GridField
, with data related to the
GridField
's context.

class Draw extends DataObject {

private static $has_many = array(
'Items' => 'Item'
);
}


When an Item is added via
Draw
's
Items
GridField
, I need to define a value for use in
Item::getCMSFields()

Answer

Some good suggestions in here: https://www.silverstripe.org/community/forums/data-model-questions/show/21517?start=7

You can work directly with the GridField's GridFieldDetailForm component, and set fields accordingly.

The code that worked for me is:

    $config = GridFieldConfig_RecordEditor::create();
    if($this->exists()) {
        // Ensure that fields are generated with knowledge of the parent
        $editComponent = $config->getComponentByType('GridFieldDetailForm');
        $item = new Item();
        $item->DrawID = $this->ID;
        $editComponent->setFields($item->getCMSFields());
    }
    $items = new GridField('Items', 'Items', $this->Items(), $config);
    $fields->addFieldToTab('Root.Main', $items);

You can then call Draw::get()->byID($this->DrawID) from Item::getCMSFields()

Comments