Skip to content

Instantly share code, notes, and snippets.

@funyx funyx/Branch.php
Last active Oct 18, 2018

Embed
What would you like to do?
<?php
namespace forest\Model;
class Branch extends \forest\Model
{
public $table = 'branch';
public $title_field = 'branch_name';
public $caption = 'Branch';
function init() {
parent::init();
$this->addField('name');
$this->hasMany('TreeBranch', new TreeBranch());
}
}
<?php
namespace forest\Model;
class Tree extends \forest\Model
{
public $table = 'tree';
public $title_field = 'tree_name';
public $caption = 'Tree';
function init() {
parent::init();
$this->addField('name');
$this->addField('branches_ref');
$this->hasMany('TreeBranch', new TreeBranch());
$this->addHook(
'afterSave',
function ($new_tree)
{
$this->setRef('branches',$new_tree);
}
);
}
public function setRef($key,$new_tree){
if($key === 'branches'){
// new branch ids
$last = json_decode($new_tree->get('branches_ref'));
$saved = $new_tree->ref('TreeBranch')->export();
$add = $delete = $same = [];
foreach($saved as $key => $set) {
if(in_array($set['branch_id'],$last)) {
$same[] = $set['branch_id'];
}else{
$delete[] = $set['branch_id'];
}
}
$add = array_diff($last,$same);
// update with add and delete
if(count($delete)){
$tree->ref('TreeBranch')->addCondition('branch_id','in',$delete)->action('delete')->execute();
}
if(count($add)){
$add_ref = [];
foreach($add as $branch_id){
$add_ref[] = ['tree_id'=>$tree->get('id'),'branch_id'=>$branch_id];
}
$tree->refModel('TreeBranch')->import($add_ref);
}
}
}
}
<?php
$app = new forest\App();
$form = $app->add(
[
'\forest\Form',
'onCancelButtonClick' => $app->jsRedirect(['/trees']),
'onSuccess' => function ($f) {
return [
$f->success('Tree created successfully'),
$f->app->jsRedirect(['/trees'])
];
}
]
);
$has_branches = isset($_REQUEST['branches']) && is_array($_REQUEST['branches']);
$form->setModel($tree_model, []);
if ($has_branches) {
$branch_model = new \forest\Model\Branch($app->db);
$branch_model->set('branches_ref',json_encode($_REQUEST['branches']));
$form->addField('branches_ref',['Hidden']);
}
$form->addField('name')
<?php
namespace forest\Model;
class TreeBranch extends \forest\Model
{
public $table = 'tree_branch';
public $caption = 'Tree Branch Relation';
function init()
{
parent::init();
$this->hasOne('tree_id', [new Tree(), 'ui'=>['visible'=>false]])->addTitle();
$this->hasOne('branch_id', [new Branch(), 'ui'=>['visible'=>false]])->addTitle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.