1. Webfox Developments
  2. Websites
  3. silverstripe-dependentdropdownfield

Overview

HTTPS SSH

silverstripe-dependentdropdownfield

A silverstripe dropdown or listbox field that has it's options populated via ajax, based on the value of the field it depends on

Based on the module by sheadawson

Requirements

SilverStripe 3

Usage example

DropdownField

$postsSource  = function ($val) {
    /** @var Category $category */
    $category = Category::get_by_id('Category', $val);
    return $category->Posts()->map()->toArray();
};

$currentPost = $this->PostID;

/** @var DependentDropdownField $postField */
$postField = DependentDropdownField::create('AssignedPost', 'Select Featured Post', $postsSource);
$postField->setMultiple(true);
$postField->setDefaultItems($currentPost);
$postField->setDepends($fields->fieldByName('Root.Main.CategoryID'));

$fields->addFieldToTab('Root.Main', $postsField);

ListboxField

$postsSource  = function ($val) {
    /** @var Category $category */
    $category = Category::get_by_id('Category', $val);
    return $category->Posts()->map()->toArray();
};

$currentPosts = $this->Posts()->column('ID');

/** @var DependentListboxField $postsField */
$postsField = DependentListboxField::create('AssignedPosts', 'Select Posts', $postsSource);
$postsField->setMultiple(true);
$postsField->setDefaultItems($currentPosts);
$postsField->setDepends($fields->fieldByName('Root.Main.CategoryID'));

$fields->addFieldToTab('Root.Main', $postsField);