Create the Model

@throws \Exception
551239
private function createController(): void
    {
        $aFields  = $this->getArguments();
        $aCreated = [];

        try {

            $aClasses = array_filter(explode(',', $aFields['CLASS_NAME']));

            foreach ($aClasses as $sClass) {

                $aFields['CLASS_NAME'] = $sClass;
                $this->oOutput->write('Creating controller <comment>' . $sClass . '</comment>... ');

                //  Check for existing controller
                $sPath = static::CONTROLLER_PATH . $sClass . '.php';
                if (file_exists($sPath)) {
                    throw new ControllerExistsException(
                        'Controller "' . $sClass . '" exists already at path "' . $sPath . '"'
                    );
                }

                $this->createFile($sPath, $this->getResource('template/controller.php', $aFields));
                $aCreated[] = $sPath;
                $this->oOutput->writeln('<info>done!</info>');
            }

        } catch (\Exception $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            //  Clean up created models
            if (!empty($aCreated)) {
                $this->oOutput->writeln('<error>Cleaning up - removing newly created controllers</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw $e;
        }
    }
726637
public function newAction()
    {
        $model = $this->loadModel();
        if (!$model->isObjectNew()) {
            $this->_forward('noroute');
            return;
        }

        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            try {
                $model->isObjectNew(true);
                foreach ($this->preprocessPostData($postData) as $key => $value) {
                    $model->setDataUsingMethod($key, $value);
                }
                $model->save();
                $this->_redirectUrl($this->getHelper()->getGridUrl());
                $this->_getSession()->addSuccess('Saved Successfully');
                return;
            } catch (Exception $e) {
                $message = $e->getMessage();
                if ($e instanceof Zend_Db_Statement_Exception && $e->getChainedException() instanceof PDOException) {
                    /** @var PDOException $e */
                    $e = $e->getChainedException();
                    if (isset($e->errorInfo[0]) && $e->errorInfo[0] == 23000 && isset($e->errorInfo[1]) && $e->errorInfo[1] == 1062) {
                        $message = $this->getHelper()->__(
                            "Record already exists for %s '%s'",
                            $model->getIdFieldName(),
                            $model->getId()
                        );
                    }
                }
                Mage::logException($e);
                $this->_getSession()->addError($message);
            }
        }

        $this->loadLayout();
        $this->renderLayout();
    }
1372902
public function create()
    {
        $record = $this->getNewModelInstance();

        $fields = array_only(
            $this->modelInformation->form->fields,
            $this->getRelevantFormFieldKeys(true)
        );

        $this->checkListParents(false);

        $values = $this->getFormFieldValuesFromModel($record, array_keys($fields));
        $errors = $this->getNormalizedFormFieldErrors();

        $renderedFields = $this->renderedFormFieldStrategies($record, $fields, $values, $errors);

        return view($this->getCreateView(), [
            'moduleKey'           => $this->moduleKey,
            'routePrefix'         => $this->routePrefix,
            'permissionPrefix'    => $this->permissionPrefix,
            'model'               => $this->modelInformation,
            'record'              => $record,
            'recordReference'     => null,
            'creating'            => true,
            'fields'              => $fields,
            'fieldStrategies'     => $renderedFields,
            'values'              => $values,
            'fieldErrors'         => $errors,
            'activeTab'           => $this->getActiveTab(),
            'errorsPerTab'        => $this->getErrorCountsPerTabPane(),
            'hasActiveListParent' => (bool) $this->listParentRelation,
            'topListParentOnly'   => $this->showsTopParentsOnly(),
            'listParents'         => $this->listParents,
        ]);
    }
123729
public function create(): bool
    {
        if ($this->isCreate()) {
            throw new Exception\RuntimeException('Memory table have been created, cannot recreated');
        }

        // Init memory table instace
        $table = new SwooleTable($this->getSize());
        $this->setTable($table);

        // Set columns
        foreach ($this->columns as $field => $fieldValue) {
            $args = array_merge([$field], $fieldValue);
            $this->table->column(...$args);
        }

        // Create memory table
        $result = $table->create();

        // Change memory table create status
        $this->setCreate(true);
        return $result;
    }
113786
protected function createModel()
    {
        if (! $this->model instanceof \Gems_Model_StaffModel) {
            $this->model = $this->loader->getModels()->getStaffModel(false);
            $this->model->applyOwnAccountEdit();
        }

        return $this->model;
    }
771890
protected function createModel()
    {
        if ($this->model instanceof \Gems_Model_RespondentModel) {
            $model = $this->model;

        } else {
            if ($this->respondent instanceof \Gems_Tracker_Respondent) {
                $model = $this->respondent->getRespondentModel();

            } else {
                $model = $this->loader->getModels()->getRespondentModel(true);;
            }
            $model->applyDetailSettings();
        }

        return $model;
    }
821243
public function create()
	{
		$class = ($this->classClr) ? 'w50 clr m12' : 'w50 m12';
	
		$this->generateDCA('checkBox', array
		(
			'inputType' 	=>	'checkbox',
			'label'			=>	array($this->label, $this->description),
			'eval'			=>	array
			(
				'mandatory'		=>	($this->mandatory) ? true : false, 
				'tl_class'		=>	$class,
			)
		));
	}
1151790
public function create()
    {
        // Look for overriden views
        $this->overrideViews();

        // Pass validation through
        Former::withRules($this->getRules());

        // Initialize localization
        with($localize = new Localize)
            ->model($this->model)
            ->title(Str::singular($this->title));

        // Make the sidebar
        $sidebar = new Sidebar;
        if (!$localize->hidden()) {
            $sidebar->addToEnd($localize);
        }

        // Render view
        return $this->populateView($this->show_view, [
            'item' => null,
            'localize' => $localize,
            'sidebar' => $sidebar,
            'parent_id' => $this->parent ? $this->parent->getKey() : null,
        ]);
    }
237668
protected function createFactory()
    {
        $factory = Str::studly(class_basename($this->argument('name')));

        $this->call('make:factory', [
            'name' => "{$factory}Factory",
            '--model' => $this->argument('name'),
        ]);
    }
940111
static public function create()
    {

        if (self::$displayErrors) {
            $flags = E_ALL;
            ini_set('display_errors', 1);
        } else {
            $flags = 0;
            ini_set('display_errors', 0);
        }

        set_error_handler(array('\psDebug\Debug', "errorHandler"), $flags);
        set_exception_handler(array('\psDebug\Debug', "exceptionHandler"));

    }
1125257
final public function create() {
        global $DB, $USER;

        if ($this->raw_get('id')) {
            // The validation methods rely on the ID to know if we're updating or not, the ID should be
            // falsy whenever we are creating an object.
            throw new coding_exception('Cannot create an object that has an ID defined.');
        }

        if (!$this->is_valid()) {
            throw new invalid_persistent_exception($this->get_errors());
        }

        // Before create hook.
        $this->before_create();

        // We can safely set those values bypassing the validation because we know what we're doing.
        $now = time();
        $this->raw_set('timecreated', $now);
        $this->raw_set('timemodified', $now);
        $this->raw_set('usermodified', $USER->id);

        $record = $this->to_record();
        unset($record->id);

        $id = $DB->insert_record(static::TABLE, $record);
        $this->raw_set('id', $id);

        // We ensure that this is flagged as validated.
        $this->validated = true;

        // After create hook.
        $this->after_create();

        return $this;
    }
756478
private function createModel(): self
    {
        $oInput      = $this->oInput;
        $oOutput     = $this->oOutput;
        $bSkipDb     = $oInput->getOption('skip-db');
        $bSkipSeeder = $oInput->getOption('skip-seeder');
        $bAutoDetect = $oInput->getOption('auto-detect');
        $bLocalised  = $oInput->getOption('localised');
        $bAdmin      = Components::exists('nails/module-admin') && $oInput->getOption('admin');

        //  If auto-detecting models using the database then skip cresting database tables
        if ($bAutoDetect) {
            $bSkipDb = true;
        }

        try {

            if (!$bAutoDetect) {

                $aFields    = $this->getArguments();
                $aModels    = explode(',', $aFields['MODEL_NAME']);
                $aModelData = [];
                sort($aModels);
                foreach ($aModels as $sModelName) {
                    $oModel = $this->prepareModelName($sModelName);

                    /**
                     * Test whether the model exists already
                     *
                     * Alter our behaviour slightly depending if we're localising or not. An existing model, which
                     * is not-localised is OK as we'll convert it to be localised (assuming the --localised flag
                     * is passed).
                     */

                    if ($this->modelExists($oModel)) {
                        if ($bLocalised && classUses($oModel->class_path, Localised::class)) {
                            throw new NailsException(
                                'A localised model by that path already exists "' . $oModel->path . $oModel->filename . '"'
                            );
                        } elseif (!$bLocalised) {
                            throw new NailsException(
                                'A model by that path already exists "' . $oModel->path . $oModel->filename . '"'
                            );
                        }
                    }

                    if (!$bSkipDb && $this->tableExists($oModel)) {
                        if ($bLocalised && classUses($oModel->class_path, Localised::class)) {
                            throw new NailsException(
                                'Localised table "' . $oModel->table_with_prefix . '" already exists. Use option --skip-db to skip database check.'
                            );
                        } elseif (!$bLocalised) {
                            throw new NailsException(
                                'Table "' . $oModel->table_with_prefix . '" already exists. Use option --skip-db to skip database check.'
                            );
                        }
                    }

                    $aModelData[] = $oModel;
                }

            } else {

                $oDb        = Factory::service('PDODatabase');
                $sAppPrefix = defined('APP_DB_PREFIX') ? APP_DB_PREFIX : '';
                $oTables    = $oDb->query('SHOW TABLES LIKE "' . $sAppPrefix . '%";');
                $aTables    = $oTables->fetchAll(\PDO::FETCH_NUM);

                //  If APP_DB_PREFIX is empty then the query above will have all the Nails table's too,
                //  filter them out.
                if (empty($sAppPrefix)) {
                    $aTables = array_filter(
                        $aTables,
                        function ($aTable) {
                            return !preg_match('/^' . NAILS_DB_PREFIX . '/', $aTable[0]);
                        }
                    );
                    $aTables = array_values($aTables);
                }

                $aModelData = array_map(
                    function ($aTable) use ($sAppPrefix) {
                        $sTable = $aTable[0];
                        $sTable = preg_replace('/^' . $sAppPrefix . '/', '', $sTable);
                        $sTable = str_replace('_', ' ', $sTable);
                        $sTable = ucwords($sTable);
                        $sTable = str_replace(' ', '/', $sTable);

                        $oModel = $this->prepareModelName($sTable);

                        return $this->modelExists($oModel) ? null : $oModel;
                    },
                    $aTables
                );
                $aModelData = array_filter($aModelData);
            }

            arraySortMulti($aModelData, 'class_path');

            //  Report to the user and get confirmation
            $oOutput->writeln('The following model(s) will be created:');
            $oOutput->writeln('');
            foreach ($aModelData as $oModel) {
                $oOutput->writeln('Model Class:    <info>\\' . $oModel->class_path . '</info>');
                $oOutput->writeln('Model Path:     <info>' . $oModel->path . $oModel->filename . '</info>');
                if ($bLocalised && $this->modelExists($oModel)) {
                    $oOutput->writeln('Localised:      <info>Model will be converted</info>');
                } else {
                    $oOutput->writeln('Resource Class: <info>\\' . $oModel->resource_class_path . '</info>');
                    $oOutput->writeln('Resource Path:  <info>' . $oModel->resource_path . $oModel->resource_filename . '</info>');
                    if (!$bSkipDb) {
                        $oOutput->writeln('Table:          <info>' . $oModel->table_with_prefix . '</info>');
                    }
                    if ($bAdmin) {
                        $oOutput->writeln('Admin:          <info>Controller will be created</info>');
                    }
                    if (!$bSkipSeeder) {
                        $oOutput->writeln('Seeder:         <info>Seeder will be created</info>');
                    }
                }
                $oOutput->writeln('');
            }

            if ($this->confirm('Continue?', true)) {

                $aServiceModelDefinitions    = [];
                $aServiceResourceDefinitions = [];

                foreach ($aModelData as $oModel) {
                    $oOutput->writeln('');
                    if ($bLocalised && $this->modelExists($oModel)) {
                        $this->convertExistingModelToLocalised(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    } elseif ($bLocalised && !$this->modelExists($oModel)) {
                        list($sServiceDefinition, $sResourceDefinition) = $this->createLocalisedModel(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    } else {
                        list($sServiceDefinition, $sResourceDefinition) = $this->createNormalModel(
                            $oModel,
                            $bSkipDb,
                            $bAdmin,
                            $bSkipSeeder
                        );
                    }

                    if (!empty($sServiceDefinition)) {
                        $aServiceModelDefinitions[] = $sServiceDefinition;
                    }

                    if (!empty($sResourceDefinition)) {
                        $aServiceResourceDefinitions[] = $sResourceDefinition;
                    }
                }

                // --------------------------------------------------------------------------

                //  Add models to the app's services array
                if (!empty($aServiceModelDefinitions)) {
                    $this->oOutput->writeln('');
                    $this->oOutput->write('Adding model(s) to app services...');
                    $this->writeServiceFile($aServiceModelDefinitions);
                    $this->oOutput->writeln('<info>done!</info>');
                }

                //  Add resources to app's service array
                if (!empty($aServiceResourceDefinitions)) {
                    $this->oOutput->write('Adding resource(s) to app services...');
                    //  Reset the token detials so we write to the correct part of the file
                    $this->validateServiceFile(static::SERVICE_RESOURCE_TOKEN);
                    $this->writeServiceFile($aServiceResourceDefinitions);
                    $this->oOutput->writeln('<info>done!</info>');
                }
            }

        } catch (\Exception $e) {
            if (!empty($aModelData)) {
                foreach ($aModelData as $oModel) {
                    @unlink($oModel->path . '/' . $oModel->filename);
                }
            }
            throw new NailsException(
                $e->getMessage(),
                is_numeric($e->getCode()) ? $e->getCode() : null
            );
        }

        return $this;
    }
932273
public function actionCreate()
    {

        $model = new $this->userClassName;
        $model->setScenario('create');
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                return $this->redirect(['index']);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);

    }
1072839
protected function createModel()
    {
        if (! $this->model instanceof RoundModel) {
            $this->model = $this->trackEngine->getRoundModel(false, 'index');
        }

        // Now add the joins so we can sort on the real name
        // $this->model->addTable('gems__surveys', array('gro_id_survey' => 'gsu_id_survey'));

        // $this->model->set('gsu_survey_name', $this->model->get('gro_id_survey'));

        return $this->model;
    }
1034677
protected function createBaseModel()
	{
		$name_parts = explode('_', $this->tableName());
		
		$path = $this->laravel['path'].'/models';
		
		for ($i = 0; $i < (count($name_parts) - 1); $i++) {
			$path .= '/' . Str::studly(Str::singular($name_parts[$i]));
		}
		
		if (count($name_parts) > 1 && !File::exists($path)) {
			File::makeDirectory($path, 0755, true);
		}
		
		$path .= '/' . Str::studly(Str::singular(end($name_parts))) . '.php';
		
		return $path;
	}
1155739
protected function createModel()
    {
        if (! $this->model instanceof \Gems_Model_RespondentModel) {
            $this->model = $this->loader->getModels()->createRespondentModel();
            $this->model->applyBrowseSettings();
        }
        return $this->model;
    }
618913
public function create() {
        switch($this->info[2]) {
            case IMAGETYPE_JPEG:
                $this->resource = imagecreatefromjpeg($this->file);
                break;
            case IMAGETYPE_GIF:
                $this->resource = imagecreatefromgif($this->file);
                break;
            case IMAGETYPE_PNG:
                $this->resource = imagecreatefrompng($this->file);
                break;
            default:
                throw new Exception('Image type is not supported');
                break;
        }
    }