Create an entry

@apiMethod POST
@apiUri    /{component}/{controller}
@return    void
552068
public function createTask()
	{
		$this->requiresAuthentication();

		$name = $this->resolveModel();

		$properties = $model->getStructure()->getTableColumns($model->getTableName());
		$properties = $this->normalizeProperties($properties);

		foreach ($properties as $property => $type)
		{
			if ($property == $model->getPrimaryKey())
			{
				continue;
			}

			if ($type == 'integer')
			{
				$fields[$property] = Request::getInt($property, 0, 'post');
			}
			/*else if ($type == 'date')
			{
				$fields[$property] = Request::getString($property, with(new Date('now'))->toSql(), 'post');
			}*/
			else
			{
				$fields[$property] = Request::getVar($property, null, 'post');
			}
		}

		if (!$model->set($fields))
		{
			App::abort(500, Lang::txt('JLIB_APPLICATION_ERROR_BIND_FAILED', $model->getError()));
		}

		// Trigger before save event
		$result = Event::trigger('on' . $model->getModelName() . 'BeforeSave', array(&$model, true));

		// Save the data
		if (!$model->save())
		{
			App::abort(500, Lang::txt('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
		}

		// Trigger after save event
		Event::trigger('on' . $model->getModelName() . 'AfterSave', array(&$model, true));

		// Log activity
		if (method_exists($model, 'link'))
		{
			$base = rtrim(Request::base(), '/');
			$url  = str_replace('/api', '', $base . '/' . ltrim(Route::url($model->link()), '/'));
		}

		$recipients = array();

		if ($model->hasAttribute('created_by'))
		{
			$recipients[] = $model->get('created_by');
		}

		Event::trigger('system.logActivity', [
			'activity' => [
				'action'      => 'created',
				'scope'       => $this->_name . '.' . $model->getModelName(),
				'scope_id'    => $model->get($model->getPrimaryKey()),
				'description' => Lang::txt(
					'JLIB_ACTIVITY_ITEM_CREATED',
					$model->getModelName() . ' #' . $model->get($model->getPrimaryKey())
				),
				'details'     => $model->toArray()
			],
			'recipients' => $recipients
		]);

		/*if ($model->hasAttribute('created_by')
		 && $model->hasAttribute('anonymous'))
		{
			$model->set('created_by', 0);
		}*/

		// Format timestamps before sending output
		foreach ($properties as $property => $type)
		{
			if ($type == 'date' && $model->get($property) && $model->get($property) != '0000-00-00 00:00:00')
			{
				$model->set($property, with(new Date($model->get($property)))->format('Y-m-d\TH:i:s\Z'));
			}
		}

		// Send results
		$this->send($model->toObject());
	}
993668
protected function PostInsertHook()
    {
        parent::PostInsertHook();

        // we need to add an customer number to the order... since generation of this number may differ
        // from shop to shop, we have added the method to fetch a new customer number to the shop class
        if (empty($this->sqlData['customer_number']) || empty($this->sqlData['shop_id'])) {
            $aUpdateData = array();
            if (empty($this->sqlData['customer_number'])) {
                $aUpdateData['customer_number'] = $this->GetCustomerNumber();
            }
            if (empty($this->sqlData['shop_id'])) {
                $oShop = TdbShop::GetInstance();
                $aUpdateData['shop_id'] = $oShop->id;
            }
            if (count($aUpdateData) > 0) {
                $this->SaveFieldsFast($aUpdateData);
            }
        }
        TdbDataExtranetGroup::UpdateAutoAssignToUser($this);
    }
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();
    }
397161
public function createAction()
    {
        if ($this->enableScreens) {
            $edit = false;
            $org  = $this->getRespondent()->getOrganization();
            if (! $org) {
                $org = $this->currentOrganization;
            }

            if ($org) {
                $edit = $org->getRespondentEditScreen();
            }

            if (! $edit) {
                $group = $this->currentUser->getGroup();
                if ($group) {
                    $edit = $group->getRespondentEditScreen();
                }
            }

            if ($edit ) {
                if ($edit instanceof ProcessModelInterface) {
                    $edit->processModel($this->getModel());
                }

                // All are arrays, so easy to set
                $this->createParameters = $edit->getCreateParameters() + $this->createParameters;
                $editSnippets = $edit->getSnippets();
                if (false !== $editSnippets) {
                    $this->createEditSnippets = $editSnippets;
                }
            }
        }

        parent::createAction();
    }
277510
public function create()
    {
        $autoIncrementField = $this->getAutoIncrementField();
        if ($autoIncrementField && $this->$autoIncrementField === null) {
            $this->$autoIncrementField = $this->getNextAutoIncrementId();
        }

        $fields = $this->getFields();
        foreach ($this->getAutoFilledData(self::OP_CREATE) as $field => $value) {
            /** @noinspection NotOptimalIfConditionsInspection */
            if (!in_array($field, $fields, true) || $this->$field !== null) {
                continue;
            }
            $this->$field = $value;
        }

        $this->validate($fields);

        $this->eventsManager->fireEvent('model:beforeSave', $this);
        $this->eventsManager->fireEvent('model:beforeCreate', $this);

        $fieldValues = [];
        $defaultValueFields = [];
        foreach ($fields as $field) {
            if ($this->$field !== null) {
                $fieldValues[$field] = $this->$field;
            } elseif ($field !== $autoIncrementField) {
                $defaultValueFields[] = $field;
            }
        }

        foreach ($this->getJsonFields() as $field) {
            if (is_array($this->$field)) {
                $fieldValues[$field] = json_encode($this->$field, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            }
        }

        /**
         * @var \ManaPHP\DbInterface $connection
         */
        $connection = $this->_di->getShared($this->getDb($this));

        if ($autoIncrementField && $this->$autoIncrementField === null) {
            $this->$autoIncrementField = (int)$connection->insert($this->getSource($this), $fieldValues, true);
        } else {
            $connection->insert($this->getSource($this), $fieldValues);
        }

        if ($defaultValueFields) {
            if ($r = static::query(null, $this)->select($defaultValueFields)->where($this->_getPrimaryKeyValuePairs())->fetch(true)) {
                foreach ($r[0] as $field => $value) {
                    $this->$field = $value;
                }
            }
        }

        $this->_snapshot = $this->toArray();

        $this->eventsManager->fireEvent('model:afterCreate', $this);
        $this->eventsManager->fireEvent('model:afterSave', $this);

        return $this;
    }
1035749
def _create_entry(self, title, data, tags):
        
        status = False
        if data.get('link') and len(data.get('link')) > 0:
            wall = self.wall()
            if wall is not False:
                try:
                    wall.post_entries(url=data.get('link').encode(), title=title, tags=(tags.lower()))
                    logger.debug('wallabag {} created'.format(data.get('link')))
                    status = True
                except Exception as e:
                    logger.critical('issue with something else that a token link ? : {}'.format(data.get('link')))
                    logger.critical(e)
                    update_result(self.trigger_id, msg=e, status=False)
                    status = False
        else:
            status = True  # we ignore empty link
        return status
1091041
public function createAction()
    {
        $this->checkAuth(AdminResources::PRODUCT, [], AccessManager::CREATE);

        $baseForm = $this->createForm(ApiForm::PRODUCT_SALE_ELEMENTS, "form", [], [
            "validation_groups" => ["create", "Default"],
            'csrf_protection' => false,
            "cascade_validation" => true,
        ]);

        $con = Propel::getConnection(ProductSaleElementsTableMap::DATABASE_NAME);
        $con->beginTransaction();

        $createdIds = array();

        try {
            $form = $this->validateForm($baseForm);

            $entries = $form->getData();

            foreach ($entries["pse"] as $entry) {
                $createEvent = new ProductSaleElementCreateEvent(
                    ProductQuery::create()->findPk($entry["product_id"]),
                    $entry["attribute_av"],
                    $entry["currency_id"]
                );

                $createEvent->bindForm($form);

                $this->dispatch(TheliaEvents::PRODUCT_ADD_PRODUCT_SALE_ELEMENT, $createEvent);

                $this->processUpdateAction(
                    $entry,
                    $pse = $createEvent->getProductSaleElement(),
                    $createEvent->getProduct()
                );

                $createdIds[] = $pse->getId();
            }

            $con->commit();
        } catch (\Exception $e) {
            $con->rollBack();

            return new JsonResponse(["error" => $e->getMessage()], 500);
        }

        return new JsonResponse(
            $this->getProductSaleElements(
                array_merge(
                    $this->getRequest()->query->all(),
                    ["id" => implode(",", $createdIds)]
                )
            ),
            201
        );
    }
13176
public function create()
	{
		// Element fields, so don´t use parent construct method
		$GLOBALS['TL_DCA']['tl_content']['palettes'][$this->element] .= ',protected';
		$GLOBALS['TL_DCA']['tl_content']['fields']['protected']['eval']['tl_class'] = 'clr'; // push to new row (clear)

		// The groups field
		if (!$this->canChangeGroups)
		{
			if(($key = array_search('protected', $GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__'])) !== false) {
				unset($GLOBALS['TL_DCA']['tl_content']['palettes']['__selector__'][$key]);
			}
			
			unset($GLOBALS['TL_DCA']['tl_content']['subpalettes']['protected']);
			
			$GLOBALS['TL_DCA']['tl_content']['fields']['protected']['eval']['submitOnChange'] = false;
			
			// Overwrite the elements groups with groups from the pattern
			$db = Database::getInstance();
			$db->prepare("UPDATE tl_content SET groups=? WHERE id=?")
			   ->execute($this->groups, $this->cid);
		}
		
		// The guests field
		if ($this->canChangeGuests)
		{
			$GLOBALS['TL_DCA']['tl_content']['palettes'][$this->element] .= ',guests';
		}
	}
986552
public function create()
    {
        if (!userHasPermission('admin:blog:blog:create')) {

            unauthorised();
        }

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

        $this->data['page']->title = 'Manage Blogs &rsaquo; Create';

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

        //  Handle POST
        if ($this->input->post()) {

            $oFormValidation = Factory::service('FormValidation');
            $oFormValidation->set_rules('label', '', 'required');
            $oFormValidation->set_rules('description', '', '');
            $oFormValidation->set_message('required', lang('fv_required'));

            if ($oFormValidation->run()) {

                $aInsertData                = array();
                $aInsertData['label']       = $this->input->post('label');
                $aInsertData['description'] = $this->input->post('description');

                $iId = $this->blog_model->create($aInsertData);

                if ($iId) {

                    $sStatus   = 'success';
                    $sMessage  = 'Blog was created successfully, ';
                    $sMessage .= 'now please confirm blog settings.';
                    $this->session->set_flashdata($sStatus, $sMessage);
                    redirect('admin/blog/settings?blog_id=' . $iId);

                } else {

                    $this->data['error']  = 'Failed to create blog. ';
                    $this->data['error'] .= $this->blog_model->lastError();
                }

            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

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

        //  Load views
        Helper::loadView('edit');
    }
452010
def create
      @record = Post.new(post_params)
      @record.additional_data(params[:additional_data]) if defined?(params[:additional_data]) && !params[:additional_data].blank?

      respond_to do |format|

        if @record.save

          # assigns and unassigns categories and tags to an individual posts
          Post.deal_with_categories @record, params[:category_ids], params[:tag_ids]

          format.html { redirect_to admin_articles_path, notice: I18n.t("controllers.admin.articles.create.flash.success") }

        else
          format.html {
            # add breadcrumb and set title
            add_breadcrumb I18n.t("controllers.admin.articles.new.breadcrumb")
            @action = 'create'
            flash[:error] = I18n.t('generic.validation.no_passed')
            render action: "new"
          }
        end

      end
    end
878457
private function createNewPost()
	{
		if (!$this->user->role->hasPermission('create'))
			throw new CHttpException(403, Yii::t('Api.content', 'You do not have permission to create new entries.'));

		$model = new Content;

		$model->populate($_POST);

		// Return a model instance to work with
		if ($model->savePrototype($this->user->id))
		{
			return $model->getAPIAttributes(array(
					'category_id',
					'parent_id',
					'author_id'
				),
				array(
					'author' => array(
						'password',
						'activation_key',
						'email',
						'about',
						'user_role',
						'status',
						'created',
						'updated'
					),
					'category' => array(
						'parent_id'
					),
					'metadata' => array(
						'content_id'
					)
				));
		}

		return $this->returnError(400, NULL, $model->getErrors());
	}
559683
def create_entry(post_uri, entry, slug=nil)
      unless entry.kind_of?(Atom::Entry)
        entry = Atom::Entry.new :stream => entry
      end
      service = @service_info.get(post_uri)
      unless entry.categories.all?{ |c| service.allows_category?(c) }
        raise RequestError, "Forbidden Category"
      end
      create_resource(post_uri, entry.to_s, Atom::MediaType::ENTRY.to_s, slug)
      @res['Location']
    end
459330
public function create()
	{
		$arrNodes = false;

		if ($this->insideRoot)
		{
			$objContent = \ContentModel::findById($this->data->pid);

			$rootId = Controller::getRootPageId($objContent->ptable, $objContent->pid);

			if (null !== $rootId)
			{
				$objPage = \PageModel::findWithDetails($rootId);

				if ($this->insideLang || empty($objPage->domain))
				{
					$arrNodes = array($rootId);
				}
				else
				{
					$arrNodes = (array) \PageModel::findByDns($objPage->domain)->fetchEach('id');
				}
			}
		}
		
		if ($this->multiArticle)
		{
			$this->generateDCA('multiArticle', array
			(
				'inputType' => 'articleTree',
				'label'		=> array($this->label, $this->description),
				'eval'		=> array
				(
					'multiple'		=>	true,				
					'fieldType'		=>	'checkbox', 
					'orderField'	=>	$this->virtualFieldName('orderArticle'),
					'mandatory'		=> ($this->mandatory) ? true : false, 
					'rootNodes'		=>	$arrNodes,
					'tl_class'		=> 'clr'
				),
				'load_callback'		=> array
				(
					array('tl_content_contentblocks', 'prepareOrderPageValue'),
				),
				'save_callback'		=> array
				(
					array('tl_content_contentblocks', 'saveOrderPageValue'),
				),
			));
		}
		else
		{
			$this->generateDCA('singleArticle', array
			(
				'inputType' => 'articleTree',
				'label'		=> array($this->label, $this->description),
				'eval'		=> array
				(
					'fieldType'		=>	'radio', 
					'mandatory'		=> ($this->mandatory) ? true : false, 
					'rootNodes'		=>	$arrNodes,
					'tl_class'		=> 'clr'
				),
			));
		}
	}
1074741
public function createAction() {
        $this->setStatusCode(201);
        $createObjects = $this->createActionProcess();

        if(sizeOf($createObjects) == 1) { //Default handling of passing in one
            $createObject = $createObjects[0];
            $this->setErrors($createObject->getErrors());
            $this->setStatusCode($createObject->getStatusCode());
            if(!is_null($createObject->getEntity())) {
                try {
                    $this->showActionInternal($createObject->getEntity());
                } catch(Exception $e) {
                    $this->handleError($e);
                } catch(ValidationException $e) {
                    $this->handleValidationError($e);
                } catch(AclException $e) {
                    $this->handleAclError($e);
                } catch(CatchableException $e) {
                    $this->handleCatchableError($e);
                }
            }
        } else {
            $this->setStatusCode(400);
            $hasOneSuccessful = false;
            $objects = [];
            foreach($createObjects as $createObject) {
                $object = new \stdClass();
                try {
                    if(!is_null($createObject->getEntity())) {
                        $hasOneSuccessful = true;
                        $object->{$createObject->getEntity()->getEntityName()} = $this->generateEntityAction($createObject->getEntity());
                    }
                    $object = $this->addErrorsAndStatus($createObject->getErrors(), $createObject->getStatusCode(), $object);
                } catch(Exception $e) {
                    $this->handleError($e);
                } catch(ValidationException $e) {
                    $this->handleValidationError($e);
                } catch(AclException $e) {
                    $this->handleAclError($e);
                } catch(CatchableException $e) {
                    $this->handleCatchableError($e);
                }
                $objects[] = $object;
            }
            $blankEntity = $this->generateEntity();
            $outputObject = $this->getOutputObject();
            $outputObject->{$blankEntity->getEntityName() . 's'} = $objects;
            $this->setOutputObject($outputObject);
            if($hasOneSuccessful) {
                $this->setStatusCode(201);
            }
        }


    }
552079
private function createMigration(): void
    {
        try {

            $oNow    = Factory::factory('DateTime');
            $aFields = [
                'INDEX'      => $this->oInput->getArgument('index'),
                'DATE_START' => $oNow->format('Y-m-d'),
            ];

            if (is_null($aFields['INDEX'])) {

                //  Get the most recent migration and increment it by 1
                $sPattern    = \Nails\Common\Console\Command\Database\Migrate::VALID_MIGRATION_PATTERN;
                $aMigrations = [];
                foreach (new \DirectoryIterator(static::MIGRATION_PATH) as $oFileInfo) {

                    if ($oFileInfo->isDot()) {
                        continue;
                    }

                    //  In the correct format?
                    if (preg_match($sPattern, $oFileInfo->getFilename(), $aMatches)) {
                        $aMigrations[] = (int) $aMatches[1];
                    }
                }

                sort($aMigrations);

                if (!empty($aMigrations)) {
                    $aFields['INDEX'] = end($aMigrations) + 1;
                } else {
                    $aFields['INDEX'] = 0;
                }

            } elseif (!is_numeric($aFields['INDEX'])) {
                throw new NailsException('Specified migration index is not a numeric value.');
            } else {
                $aFields['INDEX'] = (int) $aFields['INDEX'];
            }

            $this->oOutput->write('Creating migration <comment>' . $aFields['INDEX'] . '</comment>... ');

            //  Check for existing controller
            $sPath = static::MIGRATION_PATH . $aFields['INDEX'] . '.php';
            if (file_exists($sPath)) {
                throw new MigrationExistsException(
                    'Migration "' . $aFields['INDEX'] . '" exists already at path "' . $sPath . '"'
                );
            }

            //  If we're making the first migration, get a dump of all the non-Nails tables
            $aFields['QUERIES'] = '';
            if ($aFields['INDEX'] === 0 && stringToBoolean($this->oInput->getOption('sql-on-zero'))) {

                $oDb      = Factory::service('Database');
                $aResult  = $oDb->query('SHOW TABLES')->result();
                $aCreates = [];

                foreach ($aResult as $oResult) {
                    $aResult = (array) $oResult;
                    $sTable  = reset($aResult);
                    if (!preg_match('/^' . NAILS_DB_PREFIX . '/', $sTable) || $sTable == NAILS_DB_PREFIX . 'user_meta_app') {
                        $aResult    = (array) $oDb->query('SHOW CREATE TABLE ' . $sTable)->row();
                        $aCreates[] = 'DROP TABLE IF EXISTS ' . $aResult['Table'] . ';' . "\n" . $aResult['Create Table'];
                    }
                }

                foreach ($aCreates as $sCreate) {

                    $aCreate = explode("\n", $sCreate);
                    $iCount  = count($aCreate);
                    array_walk(
                        $aCreate,
                        function (&$sLine, $iIndex) use ($iCount) {
                            $sLine = trim($sLine);
                            if ($iIndex > 1 && $iIndex < ($iCount - 1)) {
                                $sLine = $this->tabs(4) . $sLine;
                            } else {
                                $sLine = $this->tabs(3) . $sLine;
                            }
                        }
                    );

                    $aFields['QUERIES'] .= $this->tabs(2) . '$this->query(\'' . "\n";
                    $aFields['QUERIES'] .= str_replace("'", "\'", implode("\n", $aCreate)) . "\n";
                    $aFields['QUERIES'] .= $this->tabs(2) . '\');' . "\n";
                }

                $aFields['QUERIES'] = trim($aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(NAILS_DB_PREFIX, '{{NAILS_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = str_replace(APP_DB_PREFIX, '{{APP_DB_PREFIX}}', $aFields['QUERIES']);
                $aFields['QUERIES'] = preg_replace('/AUTO_INCREMENT=\d+ /', '', $aFields['QUERIES']);

            } else {
                $aFields['QUERIES'] = '$this->query(\'\');';
            }

            $this->createFile($sPath, $this->getResource('template/migration.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 migration</error>');
                foreach ($aCreated as $sPath) {
                    @unlink($sPath);
                }
            }
            throw new NailsException($e->getMessage());
        }
    }
634108
def create(self, **kwargs):
        

        return super(PostController, self).create(**self._with_markdown(kwargs))
829878
public function actionCreate()
    {
        $data = [
            'f1' => $this->getContext()->getInput()->post('p1'),
            'f2' => $this->getContext()->getInput()->post('p2'),
        ];

        $this->outputJson($data);
        //$this->outputJson(null, 'shibaile', 403);
    }