Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Form Questions

MultiSelect with Custom / Filtered Source


Reply

2 Posts   741 Views

Avatar
x75

11 January 2012 at 7:15am Community Member, 42 Posts

Hi,
I have build a ProductPage which can have many ReferencePages (many_many and belongs_many_many). So far it works.

Now I want to be able to only select ReferencePages that are within the same "section" of the website. (ProductPage and ReferencePages have the same Root)

I tried using TreeMultiselectField with a DropDownMap as DataSource:

// get the IDs of all Pages with this root:
$root = $this->Level(1);
$ids = $root->getDescendantIDList();

// get all ReferencePages that are in that idlist and convert to dropdown map:
$query = '("SiteTree"."ID" = ' . implode(' OR "SiteTree"."ID" = ', $ids) .')';
$items = DataObject::get("ReferencePage", $query)->map('ID', 'Title', '--empty--');

// create field:
$treeField = new TreeMultiselectField("References", "References", $items);


   
Works: The TreeMultiselectField only shows References that i want it to show. You can select References and it actually saves the selection to the DB.
Problem: The selected References are not selected /checked in the TreeMultiselectField when the control loads.

Can I select them manually somehow? By setting $treeField->value or something?
Or is there an other way to do all this?

Thanks
Johannes

Avatar
x75

21 January 2012 at 2:35am (Last edited: 24 January 2012 4:12am), Community Member, 42 Posts

Ok, in case someone else is looking for a solution:

I could not figure out how to solve this with a TreeMultiselectField so I ended up using the CheckboxSetField, because it's constructor takes the selected values as an argument:

// get the IDs of all Pages with this root:
$root = $this->Level(1);
$ids = $root->getDescendantIDList();

// get all ReferencePages that are in that idlist and convert to dropdown map:
$query = '("SiteTree"."ID" = ' . implode(' OR "SiteTree"."ID" = ', $ids) .')';
$items = DataObject::get("ReferencePage", $query)->map('ID', 'Title');

// create field:
$fields->addFieldToTab( 'Root.Content.References', new CheckboxSetField( $name = "References", $title = "References", $source = $items , $value = $this->References())) ;

just a little update:
replaced:

$items = DataObject::get("ReferencePage", $query)->map('ID', 'Title');


with:

$items = DataObject::get("ReferencePage", $query);

because otherwise it would fail, if there are no ReferencePages in that section yet. You could check for that, but since the map function was not necessary anyways and CheckboxSetField can handle an empty source the best thing to do is just remove it.