@@ -2,8 +2,31 @@ Yii2 behaviors implement handling of mongodb embedded documents
22===============================================================
33
44* Add attribute with name starting with underscore to model.
5+ ~~~
6+ /**
7+ * @inheritdoc
8+ */
9+ public function attributes()
10+ {
11+ return [
12+ '_address',
13+ '_phones',
14+ ]
15+ }
16+ ~~~
517* Add "safe" validation rule for attribute without underscore in name.
6- * Use attribute without underscore in name in forms or views
18+ ~~~
19+ /**
20+ * @inheritdoc
21+ */
22+ public function rules()
23+ {
24+ return [
25+ [['address', 'phones'], 'safe'],
26+ ]
27+ }
28+ ~~~
29+ * Add behavior with attribute name with underscore in name
730~~~
831'address' => [
932 'class' => EmbedsOneBehavior::className(),
@@ -13,33 +36,41 @@ Yii2 behaviors implement handling of mongodb embedded documents
1336'phones' => [
1437 'class' => EmbedsManyBehavior::className(),
1538 'attribute' => '_phones',
16- 'initEmptyScenarios' => ['create', 'update'],
1739 'embedded' => Phone::className()
1840],
1941~~~
20- * Embedded documents must be inherited from EmbeddedDocument class.
42+ * Your embedded documents must be inherited from [ EmbeddedDocument] ( EmbeddedDocument.php ) class.
2143~~~
22- class SlaveEmbeddedClass extends EmbeddedDocument
44+ class Phone extends EmbeddedDocument
2345{
24- public $name ;
25- public $value ;
46+ public $number ;
47+ public $type ;
2648
2749 public function rules()
2850 {
2951 return [
30- [['value'], 'boolean', 'on' => 'valueV'],
31- [['name'], 'integer', 'on' => 'nameV'],
32- [['name', 'value'], 'safe', 'on'=>'default']
52+ [['number', 'type'], 'string'],
53+ [['type'], 'in', 'range' => ['home', 'work']],
3354 ];
3455 }
3556}
3657~~~
3758* To create empty embedded document set base document's scenario to the value listed in initEmptyScenarios parameter of EmbedsManyBehavior
59+ ~~~
60+ 'address' => [
61+ 'class' => EmbedsOneBehavior::className(),
62+ 'attribute' => '_address',
63+ 'initEmptyScenarios' => ['create', 'update'],
64+ 'embedded' => Address::className()
65+ ],
66+ ~~~
3867* Use attribute without underscore in form or view
3968~~~
69+ // Address
4070echo $form->field($company->address, 'detail');
4171echo $form->field($company->address, 'id')->hiddenInput();
4272
73+ // Phones
4374foreach($company->phones as $key => $phone) {
4475 echo $form->field($phone, 'number');
4576 echo $form->field($phone, 'type');
0 commit comments