forked from synatree/yii2-dynamic-relations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamicRelations.php
79 lines (68 loc) · 1.78 KB
/
DynamicRelations.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
namespace synatree\dynamicrelations;
use Yii;
use yii\base\Widget;
use yii\helpers\Url;
class DynamicRelations extends Widget
{
public $title;
public $collection;
public $collectionType;
public $viewPath;
public function init(){
parent::init();
}
public function run(){
if( count($this->collection) && is_object($this->collection[0]) )
{
$type = get_class( $this->collection[0] );
}
elseif( is_object($this->collectionType)) {
$type = get_class($this->collectionType);
}
else{
throw new \yii\web\HttpException(500, "No Collection Type Specified, and Collection Empty.");
}
$key = "dynamic-relations-$type";
$hash = crc32($key);
Yii::$app->session->set('dynamic-relations-'.$hash, [ 'path'=>$this->viewPath, 'cls'=>$type ]);
return $this->render('template', [
'title' => $this->title,
'collection' => $this->collection,
'viewPath' => $this->viewPath,
'ajaxAddRoute' => Url::toRoute(['dynamicrelations/load/template', 'hash'=>$hash]),
]);
}
public function uniqueOptions($field, $uniq)
{
return [
'id' => "$field-$uniq-id",
'name' => "$field-$uniq-id",
'pluginOptions' => [
'uniq' => $uniq
],
];
}
public static function relate($model, $attr, $request, $name, $clsname)
{
if($request[$name])
{
if($new = $request[$name]['new'])
{
foreach( $new as $useless=>$newattrs)
{
$newmodel = new $clsname;
$newmodel->load( $new,$useless );
$model->link($attr, $newmodel);
}
unset( $request[$name]['new'] );
}
foreach($request[$name] as $id=>$relatedattr)
{
$existingmodel = $clsname::findOne( $id );
$existingmodel->load([$name=>$relatedattr]);
$existingmodel->save();
}
}
}
}