Generate create view for a model
@param array $config Configuration array
@param boolean $simple Optional True for a simple view (just the form)
@return string Create form in HTML
436106
public static function create($config, $simple = false) {
        //$config = CrudGenerator::translateConfig($config);
        if (request()->has('_itemRelSel')) {
            list($itemsRelSelCampo, $itemsRelSelId) = explode("|", request()->_itemRelSel);
            foreach ($config['campos'] as $clave => $relacion) {
                if ($clave != $itemsRelSelCampo) {
                    unset($config['campos'][$clave]);
                }
            }
        }
        if (!CrudGenerator::checkPermission($config)) {
            return View::make('sirgrimorum::crudgen.error', ['message' => trans('crudgenerator::admin.messages.permission')]);
        }
        $modelo = strtolower(class_basename($config["modelo"]));
        $config = CrudGenerator::loadTodosFromConfig($config);

        if (!$simple) {
            $js_section = config("sirgrimorum.crudgenerator.js_section");
            $css_section = config("sirgrimorum.crudgenerator.css_section");
        } else {
            $js_section = "";
            $css_section = "";
        }
        if ($config['url'] == "Sirgrimorum_CrudAdministrator") {
            $config['url'] = route("sirgrimorum_modelo::store", ["modelo" => $modelo]);
            if (\Lang::has('crudgenerator::' . $modelo . '.labels.create')) {
                $config['botones'] = trans("crudgenerator::$modelo.labels.create");
            } else {
                $config['botones'] = trans("crudgenerator::admin.layout.crear");
            }
        }
        if (request()->has('_itemRelSel')) {
            $view = View::make('sirgrimorum::crudgen.templates.relationshipssel_simple', [
                        'config' => $config,
                        'datoId' => $itemsRelSelId,
                        'columna' => $itemsRelSelCampo,
                        'tabla' => (new $config['campos'][$itemsRelSelCampo]['modelo'])->getTable(),
                        'datos' => $config['campos'][$itemsRelSelCampo],
                        'js_section' => $js_section,
                        'css_section' => $css_section,
                        'modelo' => $modelo
            ]);
        } else {
            $view = View::make('sirgrimorum::crudgen.create', [
                        'config' => $config,
                        'tieneHtml' => CrudGenerator::hasTipo($config, ['html','article']),
                        'tieneDate' => CrudGenerator::hasTipo($config, ['date', 'datetime', 'time']),
                        'tieneSlider' => CrudGenerator::hasTipo($config, 'slider'),
                        'tieneSelect' => CrudGenerator::hasTipo($config, ['select', 'relationship', 'relationships']),
                        'tieneSearch' => CrudGenerator::hasTipo($config, [ 'relationshipssel']),
                        'tieneFile' => CrudGenerator::hasTipo($config, [ 'file', 'files']),
                        'tieneJson' => CrudGenerator::hasTipo($config, [ 'json']),
                        'js_section' => $js_section,
                        'css_section' => $css_section,
                        'modelo' => $modelo
            ]);
        }
        return $view->render();
    }
1255526
public function render($config = array())
    {
        // Load the language strings for toolbar button labels
        JFactory::getLanguage()->load('joomla', JPATH_ADMINISTRATOR);

        $html = parent::render($config);

        return $html;
    }
1245645
public function autocomplete($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'element'  => null,
            'options_callback' => null, // wraps the call to select2 options in JavaScript, can be used to add JS code
            'options'  => array(
                'minimumInputLength' => 2,
                'validate'      => false, //Toggle if the forms validation helper is loaded
                'queryVarName'  => 'search',
                'width'         => 'resolve',
                'model'		    => $config->model,
                'placeholder'   => $config->prompt,
                'allowClear'    => $config->deselect,
                'value'         => $config->value,
                'text'          => $config->text,
                'selected'      => $config->selected,
                'url'           => $config->url,
                'multiple'      => false
            )
        ))->append(array(
            'options' => array(
                'label' => $config->text
            )
        ));

        $html ='';

        if (!$config->options->url instanceof KHttpUrl) {
            $config->options->url = $this->getObject('lib:http.url', array('url' => $config->options->url));
        }

        $config->options->url->setQuery(array('fields' => $config->value.','.$config->text), true);

        $config->options->url = (string)$config->options->url;

        $options   = $config->options;
        $signature = md5('autocomplete-'.$config->element.$config->options_callback.$options);

        if($config->element && !static::isLoaded($signature))
        {
            $options = (string) $options;

            if ($config->options_callback) {
                $options = $config->options_callback.'('.$options.')';
            }

            $html .= $this->select2(array('element' => false));

            if (!static::isLoaded('koowa-select2-autocomplete')) {
                $html .= '<script>
                if(!Koowa) {
                    var Koowa = {};
                }
                
                Koowa.getSelect2Options = function(options) {
                    var defaults = {
                        width: "resolve",
                        minimumInputLength: 2,
                        theme: "bootstrap",
                        ajax: {
                            url: options.url,
                            delay: 100,
                            data: function (params) {
                                var page  = params.page || 1,  // page is the one-based page number tracked by Select2
                                    query = {
                                        limit: 10, // page size
                                        offset: (page-1)*10
                                    };
                                query[options.queryVarName] = params.term;
            
                                return query;
                            },
                            processResults: function (data, page) {
                                var results = [],
                                    more = (page * 10) < data.meta.total; // whether or not there are more results available
            
                                kQuery.each(data.entities, function(i, item) {
                                    // Change format to what select2 expects
                                    item.id   = item[options.value];
                                    item.text = item[options.text];
            
                                    results.push(item);
                                });
            
                                // notice we return the value of more so Select2 knows if more results can be loaded
                                return {results: results, more: more};
                            }
                        }
                    };
                    
                    var settings = kQuery.extend( {}, defaults, options);
                    
                    return settings;
                };
                </script>';

                static::setLoaded('koowa-select2-autocomplete');
            }

            $html .= '<script>
            kQuery(function($){
                $("'.$config->element.'").select2(Koowa.getSelect2Options('.$options.'));
            });</script>';

            static::setLoaded($signature);
        }

        return $html;
    }
118300
public function paginate($listRows = null, $simple = false, $config = [])
    {
        if (is_int($simple)) {
            $total  = $simple;
            $simple = false;
        }

        $paginate = Db::getConfig('paginate');

        if (is_array($listRows)) {
            $config   = array_merge($paginate, $listRows);
            $listRows = $config['list_rows'];
        } else {
            $config   = array_merge($paginate, $config);
            $listRows = $listRows ?: $config['list_rows'];
        }

        /** @var Paginator $class */
        $class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']);
        $page  = isset($config['page']) ? (int) $config['page'] : call_user_func([
            $class,
            'getCurrentPage',
        ], $config['var_page']);

        $page = $page < 1 ? 1 : $page;

        $config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']);

        if (!isset($total) && !$simple) {
            $options = $this->getOptions();

            unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);

            $bind    = $this->bind;
            $total   = $this->count();
            $results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
        } elseif ($simple) {
            $results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
            $total   = null;
        } else {
            $results = $this->page($page, $listRows)->select();
        }

        $this->removeOption('limit');
        $this->removeOption('page');

        return $class::make($results, $listRows, $page, $total, $simple, $config);
    }
1285926
protected function renderByType($config)
    {
        if($config['script']){

            return $this->script($config['script']);

        } elseif($config['meta']){

            return $this->meta($config['meta']);

        } elseif($config['style']){

            return $this->style($config['style']);

        } elseif($config['menu']){

            return menu($config['menu']);

        } elseif(form()->exists($config['form'])){

            return form($config['form']);

        } elseif(view()->exists($config['view'])){

            return view($config['view']);

        } elseif($config['config']){

            return config($config['config']);

        }

        return false;
    }
1364141
protected function buildTagView(array $viewConfig)
    {
        $view = new TagView();
        $view->setConfigHash($viewConfig);

        if (isset($viewConfig['template'])) {
            $view->setTemplateIdentifier($viewConfig['template']);
        }

        if (isset($viewConfig['controller'])) {
            $view->setControllerReference(new ControllerReference($viewConfig['controller']));
        }

        return $view;
    }
294508
protected function _applyConfig($config)
    {
        if (is_string($config)) {
            $name = $config;
            $config = static::getConfig($name);
            if (empty($config)) {
                throw new InvalidArgumentException(sprintf('Unknown email configuration "%s".', $name));
            }
            unset($name);
        }

        $this->_profile = array_merge($this->_profile, $config);

        $simpleMethods = [
            'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath',
            'cc', 'bcc', 'messageId', 'domain', 'subject', 'attachments',
            'transport', 'emailFormat', 'emailPattern', 'charset', 'headerCharset'
        ];
        foreach ($simpleMethods as $method) {
            if (isset($config[$method])) {
                $this->{'set' . ucfirst($method)}($config[$method]);
            }
        }

        if (empty($this->headerCharset)) {
            $this->headerCharset = $this->charset;
        }
        if (isset($config['headers'])) {
            $this->setHeaders($config['headers']);
        }

        $viewBuilderMethods = [
            'template', 'layout', 'theme'
        ];
        foreach ($viewBuilderMethods as $method) {
            if (array_key_exists($method, $config)) {
                $this->viewBuilder()->{'set' . ucfirst($method)}($config[$method]);
            }
        }

        if (array_key_exists('helpers', $config)) {
            $this->viewBuilder()->setHelpers($config['helpers'], false);
        }
        if (array_key_exists('viewRender', $config)) {
            $this->viewBuilder()->setClassName($config['viewRender']);
        }
        if (array_key_exists('viewVars', $config)) {
            $this->set($config['viewVars']);
        }
    }
380024
protected function createMail(array $config)
    {
        $mail = $this->newMailInstance();

        $mail->setName(ConfigUtil::getValue($config, 'name'));
        $mail->setLabel(ConfigUtil::getValue($config, 'label'));
        $mail->setDescription(ConfigUtil::getValue($config, 'description'));
        $mail->setType(ConfigUtil::getValue($config, 'type', MailTypes::TYPE_ALL));
        $mail->setEnabled(ConfigUtil::getValue($config, 'enabled', true));
        $mail->setSubject(ConfigUtil::getValue($config, 'subject'));
        $mail->setHtmlBody(ConfigUtil::getValue($config, 'html_body'));
        $mail->setBody(ConfigUtil::getValue($config, 'body'));
        $mail->setTranslationDomain(ConfigUtil::getValue($config, 'translation_domain'));

        if (isset($config['layout'])) {
            $mail->setLayout($this->layoutLoader->load($config['layout']));
        }

        if (isset($config['translations']) && \is_array($config['translations'])) {
            foreach ($config['translations'] as $translation) {
                $mail->addTranslation($this->createMailTranslation($mail, $translation));
            }
        }

        return $mail;
    }
1126943
protected function buildForm(array $config)
    {
        return isset($config['form'])
            ? $config['form']
            : ClassUtils::getClass($this->filterFormRegistry[$this->buildType($config)]);
    }
558609
public function renderWidget( $config = [] ) {

		if( !isset( $this->title ) ) {

			switch( $this->template ) {

				case 'message': {

					$this->title = 'Message';

					break;
				}
				case 'success': {

					$this->title = 'Success';

					break;
				}
				case 'warning': {

					$this->title = 'Alert';

					break;
				}
				case 'error': {

					$this->title = 'Error';

					break;
				}
			}
		}

		if( !isset( $this->size ) ) {

			if( $this->modal && in_array( $this->template, [ 'message', 'success', 'warning', 'error' ] ) ) {

				$this->size = 'medium';
			}
		}

		$widgetHtml = $this->render( $this->template, [
			'widget' => $this
		]);

		return $widgetHtml;
	}
336220
public static function generateList( $config = [] ) {

		$modelClass	= static::$modelClass;
		$modelTable = $modelClass::tableName();

		// Query and Column
		$query	= new Query();
		$column	= $config[ 'column' ] ?? 'id';

		// Conditions, Filters and Sorting
		$conditions	= $config[ 'conditions' ] ?? null;
		$filters	= $config[ 'filters' ] ?? null;
		$order		= $config[ 'order' ] ?? null;

		// Conditions ----------

		$query->select( $column )->from( $modelTable );

		if( isset( $conditions ) ) {

			foreach ( $conditions as $ckey => $condition ) {

				if( is_numeric( $ckey ) ) {

					$query->andWhere( $condition );

					unset( $conditions[ $ckey ] );
				}
			}

			$query->andWhere( $conditions );
		}

		$interfaces = class_implements( static::class );

		if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {

			$statusFilter = $modelClass::STATUS_TERMINATED;

			$query->andWhere( "$modelTable.status<$statusFilter" );
		}

		// Filters -------------

		if( isset( $filters ) ) {

			foreach ( $filters as $filter ) {

				$query	= $query->andFilterWhere( $filter );
			}
		}

		// Sorting -------------

		if( isset( $order ) ) {

			$query->orderBy( $order );
		}

		// Quering -------------

		// Get column
		$query->column();

		// Create command
		$command	= $query->createCommand();

		// Execute the command
		$list		= $command->queryAll();
		$resultList	= [];

		// Result --------------

		foreach ( $list as $item ) {

			$resultList[] = $item[ $column ];
		}

		return $resultList;
	}
560921
public function renderWidget( $config = [] ) {

		// Form and Fields
		if( !isset( $this->model ) && isset( $this->slug ) ) {

			$this->model = $this->modelService->getBySlugType( $this->slug, $this->type );
		}

		if( isset( $this->model ) && $this->model->isActive() ) {

			// fields and html
			$fieldsHtml		= FormUtil::getApixFieldsHtml( $this->model, $this->form, [ 'label' => $this->labels, 'modelName' => $this->formName ] );
			$captchaHtml	= null;

			// Views Path
			$formPath		= "$this->template/form";
			$captchaPath	= "$this->template/captcha";

			// submit url
			if( !isset( $this->ajaxUrl ) ) {

				$formSlug		= $this->model->slug;
				$this->ajaxUrl	= "form/$formSlug";
			}

			if( $this->model->captcha ) {

				$captchaHtml = $this->render( $captchaPath );
			}

			$formHtml = $this->render( $formPath, [ 'widget' => $this, 'fieldsHtml' => $fieldsHtml, 'captchaHtml' => $captchaHtml ] );

			// Prepare Form Options
			$modelOptions = !empty( $this->model->htmlOptions ) ? json_decode( $this->model->htmlOptions, true ) : [];

			$this->options = \yii\helpers\ArrayHelper::merge( $this->options, $modelOptions );

			$this->options[ 'action' ]			= $this->ajaxUrl;
			$this->options[ 'method' ]			= 'post';
			$this->options[ 'cmt-app' ]			= 'form';
			$this->options[ 'cmt-controller' ]	= 'form';
			$this->options[ 'cmt-action' ]		= 'default';

			if( !isset( $this->options[ 'class' ] ) ) {

				$this->options[ 'class' ] = 'cmg-form';
			}

			if( !isset( $this->options[ 'id' ] ) ) {

				$this->options[ 'id' ] = "frm-$this->slug";
			}

			if( isset( $this->cmtApp ) ) {

				$this->options[ 'cmt-app' ]	= $this->cmtApp;
			}

			if( isset( $this->cmtController ) ) {

				$this->options[ 'cmt-controller' ] = $this->cmtController;
			}

			if( isset( $this->cmtAction ) ) {

				$this->options[ 'cmt-action' ] = $this->cmtAction;
			}

			if( $this->wrap ) {

				return Html::tag( $this->wrapper, $formHtml, $this->options );
			}

			return $formHtml;
		}
		else {

			echo "<div class=\"warning\">Form not found or submission is disabled.</div>";
		}
	}
388271
private function generateArray(array $config)
    {
        ++$this->indent;

        foreach ($config as $key => $value) {
            if (is_null($value)) {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => %s,", $key, 'null'));
                } else {
                    $this->writeLine(sprintf('%s,', 'null'));
                }
            } elseif (is_bool($value)) {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => %s,", $key, $value ? 'true' : 'false'));
                } else {
                    $this->writeLine(sprintf('%s,', $value ? 'true' : 'false'));
                }
            } elseif (is_string($value)) {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => '%s',", $key, $value));
                } else {
                    $this->writeLine(sprintf("'%s',", $value));
                }
            } elseif (is_array($value)) {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => [", $key));
                } else {
                    $this->writeLine('[');
                }

                $this->generateArray($value);

                $this->writeLine('],');
            } elseif ($value instanceof ClassName) {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => %s,", $key, (string) $value));
                } else {
                    $this->writeLine(sprintf('%s,', (string) $value));
                }
            } else {
                if (is_string($key)) {
                    $this->writeLine(sprintf("'%s' => %s,", $key, $value));
                } else {
                    $this->writeLine($value.',');
                }
            }
        }

        --$this->indent;
    }
817736
public function renderForm( $config = [], $html = [] ) {

		$formView = CodeGenUtil::isAbsolutePath( $this->formView, true ) ? $this->formView : "$this->template/$this->formView";

		return $this->render( $formView, [
			'widget' => $this,
			'infoHtml' => $html[ 'infoHtml' ],
			'fieldsHtml' => $html[ 'fieldsHtml' ]
		] );
	}
934687
public function vue($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append([
            'debug' => false,
            'vuex' => true,
            'entity' => null
        ]);

        $html = '';

        if (!static::isLoaded('vue'))
        {
            $html .= '<ktml:script src="assets://js/'.($config->debug ? 'build/' : 'min/').'vue.js" />';

            static::setLoaded('vue');
        }

        if ($config->vuex && !static::isLoaded('vuex'))
        {
            $html .= '<ktml:script src="assets://js/polyfill.promise.js" />';
            $html .= '<ktml:script src="assets://js/'.($config->debug ? 'build/' : 'min/').'vuex.js" />';

            static::setLoaded('vuex');
        }

        if ($config->entity instanceof KModelEntityInterface)
        {
            $entity = $config->entity->toArray();
            $entity = is_numeric(key($entity)) ? current($entity) : $entity;
            $entity['_isNew'] = $config->entity->isNew();
            $entity['_name']  = KStringInflector::singularize($config->entity->getIdentifier()->name);

            $html .= $this->koowa($config);
            $html .= "
            <ktml:script src=\"assets://js/koowa.vue.js\" />
            <script>
                kQuery(function($) {
                    var form = $('.k-js-form-controller');
                    
                    if (form.length) {
                        form.data('controller').store = Koowa.EntityStore.create({
                            form: form,
                            entity: ".json_encode($entity)."
                        });
                    }
                });
            </script>
";
        }

        return $html;
    }
218993
public function render($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'toolbar' => null
        ));

        $html = '<ul class="k-navigation">';

        foreach ($config->toolbar->getCommands() as $command)
        {
            $command->append(array(
                'attribs' => array(
                    'href' => '#',
                    'class' => array()
                )
            ));

            if(!empty($command->href)) {
                $command->attribs['href'] = $this->getTemplate()->route($command->href);
            }

            $url = KHttpUrl::fromString($command->attribs->href);

            if (isset($url->query['view'])) {
                $command->attribs->class->append('k-navigation-'.$url->query['view']);
            }

            $attribs = clone $command->attribs;
            $attribs->class = implode(" ", KObjectConfig::unbox($attribs->class));

            $html .= '<li'.($command->active ? ' class="k-is-active"' : '').'>';
            $html .= '<a '.$this->buildAttributes($attribs).'>';
            $html .= $this->getObject('translator')->translate($command->label);
            $html .= '</a>';
            $html .= '</li>';
        }

        $html .= '</ul>';

        return $html;
    }
1116438
public function renderWidget( $config = [] ) {

		$widgetHtml = $this->render( $this->template, [ 'widget' => $this ] );

		return Html::tag( 'div', $widgetHtml, $this->options );
	}