public function validateSubForm() { $class = get_class($this); $fb = FormBuilder::load($class); $listView = $fb->findAllField(['type' => 'ListView']); foreach ($listView as $k => $lv) { ## if listview is valid if ((@$lv['fieldTemplate'] == "datasource" || @$lv["fieldTemplate"] == "form") && @$lv['templateForm'] != '') { if (isset($this->attributes[$lv['name']])) { $items = $this->attributes[$lv['name']]; foreach ($items as $k => $item) { Yii::import($lv['templateForm']); $newClass = Helper::explodeLast(".", $lv['templateForm']); $new = new $newClass(); $new->attributes = $item; $new->validate(); if ($new->hasErrors()) { foreach ($new->errors as $name => $errors) { $this->addError($name, implode("<br> • ", $errors)); } } } } } } }
/** * render * Fungsi ini untuk me-render layout * @param array $layout * @param array $sections * @param array $model * @param boolean $return * @return mixed me-return sebuah layout */ public static function render($layout, $sections = null, $model = null, $return = false) { $formpath = @$sections['editor'] ? '//layouts/forms_editor/' : "//layouts/forms/"; if (count($sections) > 0) { foreach ($sections as $k => $section) { switch (@$section['type']) { case "menu": if (@$section['file'] == "") { continue; } $options = ['title' => @$section['title'], 'icon' => @$section['icon'], 'sections' => $sections, 'options' => @$section['menuOptions'], 'inlineJS' => @$section['inlineJS']]; $mt = MenuTree::load($section['file'], $options); if ($mt != null) { $sections[$k]['content'] = $mt->render(false); } break; case "form": if (@$section['class'] == "") { continue; } $fb = FormBuilder::load(@$section['class']); if ($fb != null) { $sections[$k]['content'] = $fb->render($model, ['renderInAjax' => true]); } break; } } } return Yii::app()->controller->renderPartial($formpath . $layout, $sections, $return); }
public function actionRenderProperties() { $properties = FormBuilder::load('RepoProperties'); if ($this->beginCache('RepoProperties', array('dependency' => new CFileCacheDependency(Yii::getPathOfAlias('application.forms.RepoProperties') . ".php")))) { echo $properties->render(); $this->endCache(); } }
public function actionCellTemplate() { $postdata = file_get_contents("php://input"); $post = CJSON::decode($postdata); $fb = FormBuilder::load($post['class']); $field = $fb->findField(['name' => $post['name']]); $this->attributes = $field; $post['item'] = $this->processSingleColumn($post['item']); echo $this->getRowTemplate($post['item'], $post['idx']); }
public function actionSubform($c, $f) { Yii::import($c); $class = Helper::explodeLast(".", $c); $fb = FormBuilder::load($class); $field = $fb->findField(['name' => $f]); if (!!$field) { $this->attributes = $field; $this->renderSubForm(); } }
public function renderSubForm() { if ($this->subFormClass == get_class($this)) { return '<center><i class="fa fa-warning"></i> Error Rendering SubForm: Subform can not be the same as its parent</center>'; } else { ## render Yii::import($this->subForm); $fb = FormBuilder::load($this->subFormClass); $render = $fb->render($fb->model, ['wrapForm' => false]); return $render; } }
public function actionResizeCol($col, $name, $size, $alias) { $fb = FormBuilder::load($alias); $field = $fb->findField(['name' => $name]); if (isset($field) && isset($field['columns'][$col])) { if (!isset($field['columns'][$col]['options'])) { $field['columns'][$col]['options'] = []; } $field['columns'][$col]['options']['width'] = $size; } $fields = $fb->updateField(['name' => $name], $field); $fb->setFields($fields); }
public function renderHtml() { Yii::import($this->subForm); $class = $this->subFormClass; if (!class_exists($class)) { return ''; } $model = new $class(); $fb = FormBuilder::load($class); $html = '<div ng-controller="' . $this->ctrlName . 'Controller">'; if ($this->mode == 'single') { $fb->fieldNameTemplate = '' . get_class($this->model) . '[' . $this->name . '][:name]'; } $this->templateAttributes = $model->attributes; $html .= $fb->render(null, ['wrapForm' => false]); $html .= '</div>'; return $html; }
function formbuilder_maintain($name) { // We need the object whether or not there are any questions in it $formbuilder = new FormBuilder(); $formbuilder->load($name); $data = $_POST['data']; switch ($_POST['edit']['step']) { // Generate confirmation page case 'confirm': // TODO generate the confirmation; for now, just save changes //$rc = $formbuilder->perform_maintenance( $data ); //$rc .= $formbuilder->render_confirmation(); //break; // TODO generate the confirmation; for now, just save changes //$rc = $formbuilder->perform_maintenance( $data ); //$rc .= $formbuilder->render_confirmation(); //break; case 'perform': $rc = $formbuilder->perform_maintenance($data); $rc .= $formbuilder->save(true); $rc .= $formbuilder->render_maintenance(); break; default: $rc = $formbuilder->render_maintenance(); } return $rc; }
public function actionPreviewSQL() { $postdata = file_get_contents("php://input"); $post = json_decode($postdata, true); $criteria = @$post['criteria'] ? $post['criteria'] : []; $params = @$post['params'] ? $post['params'] : []; $baseClass = $post['baseclass']; switch ($baseClass) { case "DataGrid": case "DataFilter": case "RelationField": case "TextField": $rel = 'currentModel'; $name = $post['rfname']; $classPath = $post['rfclass']; $modelClassPath = $post['rfmodel']; $modelClass = Helper::explodeLast(".", $modelClassPath); Yii::import($modelClassPath); $class = Helper::explodeLast(".", $classPath); Yii::import($classPath); $model = new $modelClass(); $builder = $model->commandBuilder; $fb = FormBuilder::load($classPath); $field = $fb->findField(['name' => $name]); $rf = new RelationField(); $rf->builder = $fb; $rf->attributes = $field; $rf->relationCriteria = $criteria; $rf->params = $post['params']; $criteria = $rf->generateCriteria('', []); $criteria = new CDbCriteria($criteria); break; case "DataSource": $rel = $post['rel']; $name = $post['dsname']; $classPath = $post['dsclass']; $class = Helper::explodeLast(".", $classPath); Yii::import($classPath); $model = new $class(); $builder = $model->commandBuilder; $fb = FormBuilder::load($classPath); $fb->model = new $model(); $field = $fb->findField(['name' => $name]); $ds = new DataSource(); $ds->attributes = $field; $criteria = DataSource::generateCriteria($params, $criteria, $ds); $criteria = SqlCriteria::convertPagingCriteria($criteria); $criteria = new CDbCriteria($criteria); break; } if (!isset($rel)) { echo json_encode(["sql" => '', "error" => '']); return false; } $isRelated = false; if ($rel == 'currentModel') { $tableSchema = $model->tableSchema; } else { $parent = $model::model()->find(); $relMeta = $model->getMetadata()->relations[$rel]; $relClass = $relMeta->className; if (!is_subclass_of($relClass, 'ActiveRecord')) { throw new CException("Class {$relClass} harus merupakan subclass dari ActiveRecord"); } $tableSchema = $relClass::model()->tableSchema; if (!is_null($parent)) { $parentPrimaryKey = $parent->metadata->tableSchema->primaryKey; switch (get_class($relMeta)) { case 'CHasOneRelation': case 'CBelongsToRelation': if (is_string($relMeta->foreignKey)) { $criteria->addColumnCondition([$relMeta->foreignKey => $parent->{$parentPrimaryKey}]); $isRelated = true; } break; case 'CManyManyRelation': $parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative()); $stmts = $parser->parse('<?php ' . $relMeta->foreignKey . ';'); $bridgeTable = $stmts[0]->name->parts[0]; $arg0 = $stmts[0]->args[0]->value->name->parts[0]; $arg1 = $stmts[0]->args[1]->value->name->parts[0]; $criteria->join .= " " . $relMeta->joinType . " {$bridgeTable} ON t.{$tableSchema->primaryKey} = {$bridgeTable}.{$arg1} "; break; case 'CHasManyRelation': //without through if (is_string($relMeta->foreignKey)) { $criteria->addColumnCondition([$relMeta->foreignKey => $parent->{$parentPrimaryKey}]); $isRelated = true; } //with through //todo.. break; } } } $command = $builder->createFindCommand($tableSchema, $criteria); $commandText = $command->text; if ($isRelated) { $commandText = str_replace(":ycp0", "\n" . '"{$model->' . $relMeta->foreignKey . '}"', $commandText); } $commandText = SqlFormatter::highlight($commandText); $errMsg = ''; try { $command->queryScalar(); } catch (Exception $e) { $errMsg = $e->getMessage(); $errMsg = str_replace("CDbCommand gagal menjalankan statement", "", $errMsg); } echo json_encode(["sql" => $commandText, "error" => $errMsg]); }
public function doAfterSave($withRelation = true) { $pk = $this->tableSchema->primaryKey; if ($this->isNewRecord) { $this->{$pk} = $this->dbConnection->getLastInsertID(); ## this is hack ## UPDATE AUDIT TRAIL 'CREATE' ID if (!!Yii::app()->user && !Yii::app()->user->isGuest) { $a = $this->dbConnection->createCommand("\n update p_audit_trail set model_id = :model_id\n WHERE user_id = :user_id and\n model_class = :model_class and\n type = 'create' and\n model_id is null")->execute(['model_class' => ActiveRecord::baseClass($this), 'model_id' => $this->{$pk}, 'user_id' => Yii::app()->user->id]); } } else { $this->deleteResetedRelations(); } if ($withRelation) { $this->saveRelation(); } ## handling untuk file upload if (method_exists($this, 'getFields')) { $fb = FormBuilder::load(get_class($this)); $uploadFields = $fb->findAllField(['type' => 'UploadFile']); $attrs = []; $model = $this; foreach ($uploadFields as $k => $f) { if (@$f['name'] == '' || @$f['uploadPath'] == '') { continue; } ## create directory ## Jika disini gagal, berarti ada yang salah dengan format uploadPath di FormBuilder-nya $evalDir = ''; eval('$evalDir = "' . $f['uploadPath'] . '";'); $evalDir = str_replace(["\n", "\r"], "", $evalDir); $repopath = realpath(Yii::getPathOfAlias("repo")); $evalDirArr = explode("/", $evalDir); foreach ($evalDirArr as $i => $j) { $evalDirArr[$i] = preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $j); } $evalDir = implode("/", $evalDirArr); $dir = $repopath . "/" . $evalDir . "/"; $dir = str_replace(["\n", "\r"], "", $dir); if (!is_dir($dir)) { mkdir($dir, 0777, true); } ## get oldname $old = $this->{$f['name']}; $ext = pathinfo($old, PATHINFO_EXTENSION); $filename = pathinfo($old, PATHINFO_FILENAME); if (@$f['filePattern']) { ## get newname ## Jika disini gagal, berarti ada yang salah dengan format filePattern di FormBuilder-nya eval('$newname = "' . $f['filePattern'] . '";'); } else { $newname = $filename . "." . $ext; } $new = $dir . preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $newname); $new = str_replace(["\n", "\r"], "", $new); ## delete file if already exist and allowed to overwrite if (is_file($new) && $f['allowOverwrite'] == 'Yes' && is_file($old)) { unlink($new); } if (!is_file($new) && is_file($old)) { rename($old, $new); $this->{$f['name']} = trim($evalDir, "/") . "/" . $newname; if ($this->hasAttribute($f['name'])) { $attrs[] = $f['name']; } } } if (count($attrs) > 0) { if ($this->isNewRecord) { $this->isNewRecord = false; $this->updateByPk($this->id, $this->getAttributes($attrs)); $this->isNewRecord = true; } else { $this->update($attrs); } } } return true; }
<?php FormField::$inEditor = false; ?> <div class="properties-header"> <div ng-if="propMsg != 'Loading Field'"> <i class="fa fa-file-text"></i> Form Properties </div> <div ng-if="propMsg == 'Loading Field'"> <i class="fa fa-spin fa-refresh"></i> Loading Field... </div> </div> <div ui-content style="padding:6px 5px 0px 10px;"> <?php $fp = FormBuilder::load('DevFormProperties'); echo $fp->render($fb->form); ?> </div> <?php FormField::$inEditor = true;
public function actionUpdate($class) { FormField::$inEditor = true; $isPHP = Helper::explodeLast(".", $class); $class = $isPHP == "php" ? substr($class, 0, -4) : $class; $class = FormBuilder::classPath($class); $this->layout = "//layouts/blank"; ## reset form builder session FormBuilder::resetSession($class); ## load form builder class and session $fb = FormBuilder::load($class); $fb->resetTimestamp(); $fb->updateExtendsFrom('Blog'); $classPath = $class; $class = Helper::explodeLast(".", $class); if (is_subclass_of($fb->model, 'ActiveRecord')) { $formType = "ActiveRecord"; FormsController::setModelFieldList($class::model()->getAttributesList(), "AR", $class); } else { if (is_subclass_of($fb->model, 'FormField')) { $formType = "FormField"; $mf = new $class(); FormsController::setModelFieldList($mf->attributes, "FF"); } else { if (is_subclass_of($fb->model, 'Form')) { $formType = "Form"; $mf = new $class(); FormsController::setModelFieldList($mf->attributes, "FF"); } } } $fieldData = $fb->fields; FormsController::$modelField = $fieldData; $toolbar = $this->renderAllToolbar($formType); Yii::import('application.modules.' . $fb->module . '.controllers.*'); echo $this->render('form', array('fb' => $fb, 'class' => $class, 'classPath' => $classPath, 'formType' => $formType, 'moduleName' => Helper::explodeFirst(".", $classPath), 'toolbarData' => @$toolbar['data'], 'fieldData' => $fieldData), true); }
public function doAfterSave($withRelation = true) { $pk = $this->tableSchema->primaryKey; if ($this->isNewRecord) { $this->{$pk} = $this->dbConnection->getLastInsertID(); ## this is hack ## UPDATE AUDIT TRAIL 'CREATE' ID if (!!Yii::app()->user && !Yii::app()->user->isGuest) { $a = $this->dbConnection->createCommand("\n update p_audit_trail set model_id = :model_id\n WHERE user_id = :user_id and\n model_class = :model_class and\n type = 'create' and\n model_id is null")->execute(['model_class' => ActiveRecord::baseClass($this), 'model_id' => $this->{$pk}, 'user_id' => Yii::app()->user->id]); } } else { $this->deleteResetedRelations(); } if ($withRelation) { foreach ($this->__relations as $k => $new) { if ($k == 'currentModel') { $rel = new CHasManyRelation('currentModel', get_class($this), 'id'); } else { $rel = $this->getMetaData()->relations[$k]; } $relClass = $rel->className; if (!class_exists($relClass)) { continue; } $relType = get_class($rel); $relForeignKey = $rel->foreignKey; $relTableModel = $relClass::model(); $relTable = $relTableModel->tableName(); $relPK = $relTableModel->metadata->tableSchema->primaryKey; switch ($relType) { case 'CHasOneRelation': case 'CBelongsToRelation': if (!empty($new)) { $relForeignKey = $rel->foreignKey; if ($this->{$relForeignKey} == $new[$relPK]) { $model = $relClass::model()->findByPk($this->{$relForeignKey}); if (is_null($model)) { $model = new $relClass(); } if (array_diff($model->attributes, $new)) { $model->attributes = $new; if ($relType == 'CHasOneRelation') { $model->{$relForeignKey} = $this->{$pk}; } $model->save(); } } else { $this->loadRelation($rel->name); } } break; case 'CManyManyRelation': case 'CHasManyRelation': ## if relation type is Many to Many, prepare required variable $relMM = []; if ($relType == 'CManyManyRelation') { $parser = new PhpParser\Parser(new PhpParser\Lexer\Emulative()); $stmts = $parser->parse('<?php ' . $relForeignKey . ';'); if (count($stmts) > 0) { $relMM = ['tableName' => $stmts[0]->name->parts[0], 'from' => $stmts[0]->args[0]->value->name->parts[0], 'to' => $stmts[0]->args[1]->value->name->parts[0]]; } } ## Handle Insert if (isset($this->__relInsert[$k])) { if ($k != 'currentModel') { if (is_string($relForeignKey)) { ## without through if ($relType != 'CManyManyRelation') { foreach ($this->__relInsert[$k] as $n => $m) { $this->__relInsert[$k][$n][$relForeignKey] = $this->{$pk}; } } } else { if (is_array($relForeignKey)) { ## with through foreach ($this->__relInsert[$k] as $n => $m) { foreach ($relForeignKey as $rk => $fk) { $this->__relInsert[$k][$n][$fk] = $this->__relations[$rel->through][$rk]; } } } } } if (count($this->__relInsert[$k]) > 0) { if ($relType == "CHasManyRelation") { ActiveRecord::batchInsert($relClass, $this->__relInsert[$k]); } ## if current relation is many to many if ($relType == 'CManyManyRelation' && !empty($relMM)) { $manyRel = []; foreach ($this->__relInsert[$k] as $item) { $manyRel[] = [$relMM['from'] => $this->{$pk}, $relMM['to'] => $item[$relPK]]; } ## if relinsert is already exist, then do not insert it again foreach ($this->__relInsert[$k] as $insIdx => &$ins) { if (!!@$ins[$relPK]) { unset($this->__relInsert[$k]); } } ActiveRecord::batchInsert($relClass, $this->__relInsert[$k]); ## create transaction entry to link between ## related model and current model ActiveRecord::batchInsert($relMM['tableName'], $manyRel, false); } } $this->__relInsert[$k] = []; } ## Handle Update if (isset($this->__relUpdate[$k])) { if ($k != 'currentModel') { if (is_string($relForeignKey)) { ## without through if ($relType == 'CManyManyRelation') { } else { foreach ($this->__relUpdate[$k] as $n => $m) { $this->__relUpdate[$k][$n][$relForeignKey] = $this->{$pk}; } } } else { if (is_array($relForeignKey)) { ## with through foreach ($this->__relUpdate[$k] as $n => $m) { foreach ($relForeignKey as $rk => $fk) { $this->__relUpdate[$k][$n][$fk] = $this->__relations[$rel->through][$rk]; } } } } } if (count($this->__relUpdate[$k]) > 0) { ActiveRecord::batchUpdate($relClass, $this->__relUpdate[$k]); } $this->__relUpdate[$k] = []; } ## Handle Delete if (isset($this->__relDelete[$k])) { if (count($this->__relDelete[$k]) > 0) { if ($relType == 'CManyManyRelation') { if (!empty($relMM)) { //first remove entry in transaction table first ActiveRecord::batchDelete($relMM['tableName'], $this->__relDelete[$k], ['table' => $relMM['tableName'], 'pk' => $relPK, 'condition' => "{$relMM['from']} = {$this->{$pk}} AND {$relMM['to']} IN (:ids)", 'integrityError' => false]); //and then remove entry in actual table //ActiveRecord::batchDelete($relClass, $this->__relDelete[$k]); } } else { ActiveRecord::batchDelete($relClass, $this->__relDelete[$k]); } } $this->__relDelete[$k] = []; } break; } } } ## handling untuk file upload if (method_exists($this, 'getFields')) { $fb = FormBuilder::load(get_class($this)); $uploadFields = $fb->findAllField(['type' => 'UploadFile']); $attrs = []; $model = $this; foreach ($uploadFields as $k => $f) { if (@$f['name'] == '' || @$f['uploadPath'] == '') { continue; } ## create directory ## Jika disini gagal, berarti ada yang salah dengan format uploadPath di FormBuilder-nya $evalDir = ''; eval('$evalDir = "' . $f['uploadPath'] . '";'); $evalDir = str_replace(["\n", "\r"], "", $evalDir); $repopath = realpath(Yii::getPathOfAlias("repo")); $evalDirArr = explode("/", $evalDir); foreach ($evalDirArr as $i => $j) { $evalDirArr[$i] = preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $j); } $evalDir = implode("/", $evalDirArr); $dir = $repopath . "/" . $evalDir . "/"; $dir = str_replace(["\n", "\r"], "", $dir); if (!is_dir($dir)) { mkdir($dir, 0777, true); } ## get oldname $old = $this->{$f['name']}; $ext = pathinfo($old, PATHINFO_EXTENSION); $filename = pathinfo($old, PATHINFO_FILENAME); if (@$f['filePattern']) { ## get newname ## Jika disini gagal, berarti ada yang salah dengan format filePattern di FormBuilder-nya eval('$newname = "' . $f['filePattern'] . '";'); } else { $newname = $filename . "." . $ext; } $new = $dir . preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $newname); $new = str_replace(["\n", "\r"], "", $new); ## delete file if already exist and allowed to overwrite if (is_file($new) && $f['allowOverwrite'] == 'Yes' && is_file($old)) { unlink($new); } if (!is_file($new) && is_file($old)) { rename($old, $new); $this->{$f['name']} = trim($evalDir, "/") . "/" . $newname; $attrs[] = $f['name']; } } if (count($attrs) > 0) { if ($this->isNewRecord) { $this->isNewRecord = false; $this->updateByPk($this->id, $this->getAttributes($attrs)); $this->isNewRecord = true; } else { $this->update($attrs); } } } return true; }
<?php FormField::$inEditor = false; ?> <div class="properties-header"> <div class='btn btn-default btn-xs pull-right ' ng-click='unselectLayout();'> <i class='fa fa-times'></i> Close </div> <i class = "fa fa-file-text"></i> Form Layout <span class="label label-default">{{layout.name | uppercase }}</span> </div> <div ui-content style="padding:6px 0px 0px 0px;"> <?php $fpl = FormBuilder::load('DevFormLayoutProperties', array('module' => $fb->module)); echo $fpl->render(); ?> </div> <?php FormField::$inEditor = true;
public function save() { $path = $this->uploadPath; $path = trim(RepoManager::createDir($path)); $valid = $this->validate(); if ($valid) { ## remove delimeter character from attributes $attr = $this->attributes; foreach ($attr as $k => $i) { $attr[$k] = str_replace($this->repoDef['delimeter'], "-", $i); } ## modify attributes, so it can be safely stored as filename foreach ($attr as $k => $a) { $attr[$k] = preg_replace("([^\\w\\s\\d\\-_~,;:\\[\\]\\(\\).]|[\\.]{2,})", '', $a); } extract($attr); ## get dir $pattern = $this->repoDef['pattern']; preg_match_all("/\\{(.*?)\\}/", $pattern, $blocks); foreach ($blocks[1] as $b) { $varname = '$' . explode(":", $b)[0]; $pattern = str_replace('{' . $b . '}', '{' . $varname . '}', $pattern); } eval('$dir = "' . $pattern . '";'); ## create dir $newdir = $path . "/" . $dir; $dirRenamed = false; if (!is_dir($newdir)) { if ($this->dirPath == "") { mkdir($newdir, 0777, true); } else { rename($path . "/" . $this->dirPath, $newdir); $dirRenamed = true; } } $oldDirPath = $path . "/" . $this->dirPath; $this->_dirpath = $dir; ## move uploaded file $fb = FormBuilder::load(get_class($this)); $fb->model = $this; $model = $this; foreach ($this->repoDef['fileFields'] as $fieldName) { if ($this->{$fieldName} != '') { ## find the FormField to get its file pattern $field = $fb->findField(['name' => $fieldName]); ## make sure file path is in the right path $this->{$fieldName} = RepoManager::resolve($this->{$fieldName}); ## get file extension $ext = pathinfo($this->{$fieldName}, PATHINFO_EXTENSION); ## file is uploaded if (is_file($this->{$fieldName})) { ## move the file to correct location eval('@rename($this->{$fieldName}, $newdir . "/' . $field['filePattern'] . '");'); ## assign new location to its var eval('$this->{$fieldName} = $newdir . "/' . $field['filePattern'] . '";'); if (isset($this->oldAttr[$fieldName])) { $old = RepoManager::resolve($this->oldAttr[$fieldName]); if ($old != $this->{$fieldName}) { @unlink($old); } } } else { if ($dirRenamed) { $this->{$fieldName} = $newdir . substr($this->{$fieldName}, strlen($oldDirPath)); } } ## change the path to relative path $this->{$fieldName} = RepoManager::getRelativePath($this->{$fieldName}); } } } return $valid; }
function load_survey($extra = false, $user = null) { $formbuilder = new FormBuilder(); $formbuilder->load($this->formkey()); if ($extra) { $this->add_auto_questions($formbuilder, $user); } return $formbuilder; }
private function handleFileUpload($className, &$obj) { $fb = FormBuilder::load($className); $uploadFields = $fb->findAllField(['type' => 'UploadFile']); $attrs = []; $model = $this; foreach ($uploadFields as $k => $f) { if (@$f['name'] == '' || @$f['uploadPath'] == '') { continue; } ## create directory ## Jika disini gagal, berarti ada yang salah dengan format uploadPath di FormBuilder-nya $evalDir = ''; eval('$evalDir = "' . $f['uploadPath'] . '";'); $evalDir = str_replace(["\n", "\r"], "", $evalDir); $repopath = realpath(Yii::getPathOfAlias("repo")); $evalDirArr = explode("/", $evalDir); foreach ($evalDirArr as $i => $j) { $evalDirArr[$i] = preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $j); } $evalDir = implode("/", $evalDirArr); $dir = $repopath . "/" . $evalDir . "/"; $dir = str_replace(["\n", "\r"], "", $dir); if (!is_dir($dir)) { mkdir($dir, 0777, true); } ## get oldname if (is_object($obj)) { $old = $obj->{$f['name']}; } else { if (is_array($obj)) { $old = $obj[$f['name']]; } } $ext = pathinfo($old, PATHINFO_EXTENSION); $filename = pathinfo($old, PATHINFO_FILENAME); if (@$f['filePattern']) { ## get newname ## Jika disini gagal, berarti ada yang salah dengan format filePattern di FormBuilder-nya eval('$newname = "' . $f['filePattern'] . '";'); } else { $newname = $filename . "." . $ext; } $new = $dir . preg_replace('/[\\/\\?\\:\\*\\"\\<\\>\\|\\\\]*/', "", $newname); $new = str_replace(["\n", "\r"], "", $new); $new = str_replace(["//", "\\\\"], ["/", "\\"], $new); if ($old == $new) { continue; } ## delete file if already exist and allowed to overwrite if (is_file($new) && $f['allowOverwrite'] == 'Yes' && is_file($old)) { unlink($new); } if (!is_file($new) && is_file($old)) { rename($old, $new); if (is_object($obj) && is_subclass_of($obj, 'ActiveRecord')) { $obj->{$f['name']} = $new; if ($obj->hasAttribute($f['name'])) { $attrs[$f['name']] = $new; } } if (is_array($obj)) { if (isset($obj[$f['name']])) { $obj[$f['name']] = $new; $attrs[$f['name']] = $new; } } } } return $attrs; }
/** * render * Fungsi ini untuk me-render field dan atributnya * @return mixed me-return sebuah field dan atribut checkboxlist dari hasil render */ public function render() { $this->addClass('form-group form-group-sm flat', 'options'); $this->addClass($this->layoutClass, 'options'); $this->addClass($this->errorClass, 'options'); $this->fieldOptions['ui-tree-node'] = ''; $this->fieldOptions['ng-repeat'] = 'item in value'; $this->fieldOptions['ng-init'] = 'initItem(value, $index)'; $this->addClass('list-view-item', 'fieldOptions'); Yii::import(FormBuilder::classPath($this->templateForm)); $class = Helper::explodeLast(".", $this->templateForm); if (($this->fieldTemplate == 'form' || $this->fieldTemplate == 'datasource') && class_exists($class)) { $fb = FormBuilder::load($class); $model = new $class(); if ($this->value == "") { $this->value = []; } $this->templateAttributes = $model->attributes; $fb->model = $model; $this->renderTemplateForm = $fb->render($model, ['wrapForm' => false]); } else { if ($this->fieldTemplate == 'default') { $field = new $this->singleView(); $field->attributes = $this->singleViewOption; $field->renderID = $this->name . rand(0, 10000); $field->builder = $this->builder; $field->formProperties = $this->formProperties; $this->templateAttributes = ['val' => '']; $this->renderTemplateForm = $field->render(); } } $this->setDefaultOption('ng-model', "model.{$this->originalName}", $this->options); $jspath = explode(".", FormBuilder::classPath($this->templateForm)); array_pop($jspath); $jspath = implode(".", $jspath); $inlineJS = str_replace("/", DIRECTORY_SEPARATOR, trim($this->inlineJS, "/")); $inlineJS = Yii::getPathOfAlias($jspath) . DIRECTORY_SEPARATOR . $inlineJS; if (is_file($inlineJS)) { $inlineJS = file_get_contents($inlineJS); } else { $inlineJS = ''; } return $this->renderInternal('template_render.php', ['inlineJS' => $inlineJS]); }
public function actionQuery() { $postdata = file_get_contents("php://input"); $post = CJSON::decode($postdata); $class = Helper::explodeLast(".", $post['class']); Yii::import($post['class']); $this->lastCount = @$post['lc'] > 0 ? @$post['lc'] : 0; if (class_exists($class)) { $fb = FormBuilder::load($class); $field = $fb->findField(['name' => $post['name']]); if ($field['fieldType'] != "php" && method_exists($class, 'model')) { if (!is_null(@$post['model_id'])) { $fb->model = $class::model()->findByPk(@$post['model_id']); } if (is_null($fb->model)) { $fb->model = new $class(); } } $this->attributes = $field; $this->builder = $fb; $this->queryParams = is_array(@$post['params']) ? @$post['params'] : []; if (is_object($this->model) && isset($post['modelParams'])) { $this->model->attributes = $post['modelParams']; } $isGenerate = isset($post['generate']); if (is_string($this->params)) { $this->params = []; } if ($this->postData == 'No' || $this->relationTo == '' || $this->relationTo == '-- NONE --') { ## without relatedTo switch ($this->fieldType) { case "sql": $data = $this->query($this->params); break; case "phpsql": $this->sql = $this->execute($this->params); $data = $this->query($this->params); break; case "php": $data = $this->execute($this->params); break; } } else { ## with relatedTo $data = $this->getRelated($this->params, $isGenerate); } if (empty($data)) { echo "{}"; die; } echo json_encode(['data' => $data['data'], 'count' => $data['debug']['count'], 'params' => $data['debug']['params'], 'debug' => $this->debugSql == 'Yes' ? $data['debug'] : []]); } }
public function actionRelnext() { $postdata = file_get_contents("php://input"); $post = CJSON::decode($postdata); if (count($post) == 0) { die; } $start = @$post['i']; $fb = FormBuilder::load($post['m']); $ff = $fb->findField(['name' => $post['f']]); foreach ($ff['filters'] as $filter) { if ($filter['name'] != $post['n']) { continue; } $rf = new RelationField(); $rf->params = $filter['relParams']; $rf->modelClass = $filter['relModelClass']; $rf->relationCriteria = $filter['relCriteria']; $rf->relationCriteria['limit'] = ActiveRecord::DEFAULT_PAGE_SIZE; $rf->relationCriteria['offset'] = $start; $rf->idField = $filter['relIdField']; $rf->labelField = $filter['relLabelField']; $rf->builder = $this->builder; $rf->params = is_null($filter['relParams']) ? [] : $filter['relParams']; if (is_array($rf->params)) { foreach ($rf->params as $k => $ff) { if (substr($ff, 0, 3) == "js:" && isset($post['p'][$k])) { $rf->params[$k] = "'" . @$post['p'][$k] . "'"; } } } $list = []; $rawList = $rf->query(@$post['s'], $rf->params); $rawList = is_null($rawList) ? [] : $rawList; foreach ($rawList as $key => $val) { $list[] = ['key' => $val['value'], 'value' => $val['label']]; } $count = $rf->count(@$post['s'], $rf->params); echo json_encode(['list' => $list, 'count' => $count, 's' => $post['s']]); } }
public function actionUpdate($class) { $this->layout = "//layouts/blank"; $path = $class; $class_path = explode(".", $class); $class = $class_path[count($class_path) - 1]; $properties = FormBuilder::load('DevMenuEditor'); $properties->registerScript(); Asset::registerJS('application.static.js.lib.ace'); $this->render('form', array('class' => $class, 'path' => $path)); }
public function actionSearch() { $postdata = file_get_contents("php://input"); $post = CJSON::decode($postdata); if (!is_array($post)) { return; } $m = ''; $f = ''; $v = ''; $s = ''; $p = ''; extract($post); $fb = FormBuilder::load($m); if (isset($i)) { $field = $fb->findField(['name' => $f, 'identifier' => @$i]); } else { $field = $fb->findField(['name' => $f]); } $this->attributes = $field; $this->builder = $fb; if (@$field['criteria']) { $this->relationCriteria = @$field['criteria']; } $this->relationCriteria['limit'] = ActiveRecord::DEFAULT_PAGE_SIZE; $this->relationCriteria['offset'] = 0; if (isset($start)) { $this->includeEmpty = 'No'; $this->relationCriteria['offset'] = $start; } if ($this->modelClass == '') { $this->modelClass = $m; } if (is_array(@$field['params'])) { foreach ($field['params'] as $k => $ff) { if (substr($ff, 0, 3) == "js:" && isset($p[$k])) { if (is_string($p[$k])) { $p[$k] = "'" . $p[$k] . "'"; } } } } echo json_encode(['list' => $this->query($s, $p), 'count' => $this->count($s, $p)]); }
public function renderForm($class, $model = null, $params = [], $options = []) { if (is_array($model)) { $options = $params; $params = $model; $model = null; } $fb = FormBuilder::load($class); ## check if layout property is declared by rendering controller $reflection = new ReflectionObject($this); $layoutClass = $reflection->getProperty('layout')->getDeclaringClass()->getName(); ## if layout property is not declared, then set it to default form layout '//layouts/form' if ($layoutClass != get_class($this)) { $this->layout = '//layouts/form'; } ## set page title & layout to options $this->pageTitle = isset($options['pageTitle']) ? $options['pageTitle'] : @$fb->form['title']; $this->layout = isset($options['layout']) ? $options['layout'] : $this->layout; $renderOptions = ['wrapForm' => true, 'action' => $this->action->id]; if (is_object($model)) { if (get_class($model) != Helper::explodeLast(".", $class)) { throw new Exception("Invalid model name, please instantiate model from {$class} class"); } $fb->model = $model; } $options['params'] = $params; $renderOptions = array_merge($renderOptions, $options); $mainform = $fb->render($model, $renderOptions); $data = $fb->form['layout']['data']; $renderSection = @$_GET['render_section']; foreach ($data as $k => $d) { if ($d['type'] == "mainform") { $data[$k]['content'] = $mainform; } if (isset($data[$renderSection]) && $k != $renderSection) { unset($data[$k]); } } $layout = Layout::render($fb->form['layout']['name'], $data, $model, true); $this->renderText($layout, false); }