Skip to content

Example: Parent Child

e-frank edited this page Dec 13, 2014 · 13 revisions

One \app\models\Test1 has many \app\models\Test2

$model->test2s is the relation containing all child items.

use the "attributes" option to

  1. define custom extenders for the attribute
  2. define which mapping should be used to create the object

In our example, we set the creation mapping for the "test2s" relation attribute to "mapping.my1", which reuses the generated "mapping.test2".

In PHP View Code:

<?
// creates: mapping.test1
Mapping::widget(array(
    'model'      => $model, // instance of \app\models\Test1
    'attributes' => [
        'test2s'    => ['mapping' => 'mapping.my1'], // use mapping "my1" to create child items
    ],
    ));

// creates: mapping.test2
Mapping::widget(array(
    'model'      => new \app\models\Test2, // child model
    ));
?>

In JavaScript View Code:

<script>
mapping.my1= {
    create: function(options) {
        var self = ko.mapping.fromJS(options.data, mapping.test2);

        self.tax  = 1.2;
        self.calc = ko.computed({
            read: function() {
                return self.value() * self.tax;
            },
            write: function(v) {
                self.value(v / self.tax);
            },
            owner: self
        }).extend({decimal: {decimals: 2}});

        return self;
    }
}
</script>

Clone this wiki locally