CMB2 nestable list field type 01
February 17, 2015
The non trivial matter of saving a nested list.
The problem
I've embarked on the quest to create some custom field types for the Custom Meta Boxes 2 WordPress plugin and I've had a measure of success in implementing a nested sortable list control based on the Nestable.js library.
The problem is, though, with dynamic content.
Right now the field will take an option input like this (see CMB2 documentation for usage guide)
array(
'name' => 'Nested list field',
'desc' => 'A nested list field',
'id' => $prefix . 'nested_list',
'type' => 'tad_nested_list',
'options' => array(
array('id' => 1, 'text' => 'One'),
array('id' => 2, 'text' => 'Two'),
array('id' => 3, 'text' => 'Three',),
array('id' => '3.1', 'text' => 'Three.one'),
array('id' => '3.2', 'text' => 'Three.two'),
array('id' => 4, 'text' => 'Four'),
array('id' => 5, 'text' => 'Five'),
array('id' => 6, 'some' => 'some')
)
)
to output a nested list like this one [](http://theaveragedev.local/wordpress/wp-content/uploads/2015/02/2015-02-17-at-20.31.png) that, Nestable.js providing the magic, could be sorted like this [
](http://theaveragedev.local/wordpress/wp-content/uploads/2015/02/2015-02-17-at-20.34.png) And that's tagged
0.1.1
on GitHub.
Dynamic options?
The static list of options above might be replaced by the output of a method updating and serving them from a variable list
array(
'name' => 'Nested list field',
'desc' => 'A nested list field',
'id' => $prefix . 'nested_list',
'type' => 'tad_nested_list',
'options' => CustomPostType::get_list()
)
and that method might have a sudo code like this one
public static function get_list(){
$posts = get_posts(array(
'post_type' => self::$type,
'posts_per_page' => -1
));
$list = array();
foreach($posts as $post){
$list[] = array(
'id' => $post->ID,
'text' => $post->post_title
);
}
return $list;
}
where the number and data present in the list might vary between each admin render.
Next
I will deal with option plucking and updating.