Stores submitted form field data on a model.

@param Model $model
@param array $data
@return bool
@throws Exception
425244
public function store(Model $model, array $data)
    {
        if ( ! config('cms-models.transactions')) {
            return $this->storeFormFieldValuesForModel($model, $data);
        }

        // Perform the whole store process in a transaction
        DB::beginTransaction();

        try {

            $success = $this->storeFormFieldValuesForModel($model, $data);

            if ($success) {
                DB::commit();
            } else {
                DB::rollBack();
            }

        } catch (Exception $e) {

            DB::rollBack();

            throw $e;
        }

        return $success;
    }
1107932
public function beforeInsert($model, &$data)
    {
        if ($this->weak) {
            return;
        }

        // The value for the master_field is set, so we are going to use existing record anyway
        if ($model->hasField($this->master_field) && $model[$this->master_field]) {
            return;
        }

        $insert = $this->dsql();
        $insert->mode('insert');
        $insert->set($model->persistence->typecastSaveRow($model, $this->save_buffer));
        $this->save_buffer = [];
        $insert->set($this->foreign_field, null);
        $insert->insert();
        $this->id = $this->owner->lastInsertID();

        if ($this->join) {
            $this->join->set($this->master_field, $this->id);
        } else {
            $data[$this->master_field] = $this->id;
        }
    }
415803
public function store(array $data)
    {
        $exception = new ExceptionModel();

        $exception->type = $data['exception'];
        $exception->code = $data['code'];
        $exception->message = $data['message'];
        $exception->file = $data['file'];
        $exception->line = $data['line'];
        $exception->trace = $data['trace'];
        $exception->method = $data['method'];
        $exception->path = $data['path'];
        $exception->query = $data['query'];
        $exception->body = $data['body'];
        $exception->cookies = $data['cookies'];
        $exception->headers = $data['headers'];
        $exception->ip = $data['ip'];

        try {
            $exception->save();
        } catch (\Exception $e) {
            //dd($e);
        }

        return $exception->save();
    }
1111534
public function update($model, array $data)
    {
        if ($this->hasNotProvided($this->condition))
            return "To prevent updating all records you must provide at least one condition. Using where method would solve this.";

        $method = 'write';

        $ids = $this->search($model);

        //If string it can't continue for retrieving models
        //Throw exception with the error.
        if (is_string($ids))
            throw new OdooException($ids);

        $result = $this->call($model, $method, [$ids->toArray(), $data]);

        return $this->makeResponse($result, 0);
    }
1142237
protected function _beforeSave($model, &$data, $where = null) {
        $localizedData = array();
        foreach ($this->_translatableFields as $field) {
            if (array_key_exists($field, $data)) {
                $localizedData[$field] = $data[$field];
                unset($data[$field]);
            }
        }
        // Can't use values that are not arrays
        $localizedData = array_filter($localizedData, 'is_array');

        // We now have an array containing all values that are provided in one or more languages
        $languages = Garp_I18n::getLocales();
        $existingRows = array_fill_keys($languages, array());
        if (!is_null($where)) {
            $pKeys = $this->_getPrimaryKeysOfAffectedRows($model, $where);
            if (!count($pKeys)) {
                // No primary keys found in update?
                // That means there aren't any affected rows and there's nothing for us to do.
                return;
            }
            $existingRows = $this->_fetchLocalizedRows($languages, $model, $pKeys);
        }

        $defaultLanguage = Garp_I18n::getDefaultLocale();
        $languages = array_diff($languages, array($defaultLanguage));
        foreach ($localizedData as $column => $val) {
            foreach ($languages as $language) {
                if (!empty($val[$language])) {
                    // If value provided in language: good!
                    continue;
                }
                if (empty($val[$defaultLanguage])) {
                    // No default? Nothing to fall back to
                    continue;
                }
                if (!$where) {
                    // If insert, just use default value
                    $localizedData[$column][$language] = $val[$defaultLanguage];
                    continue;
                }
                // Else if update, make sure existing row isn't different from default language row
                if (!$this->_translatedVersionHasBeenChanged(
                    $existingRows[$defaultLanguage],
                    $existingRows[$language], $column
                )
                ) {
                    $localizedData[$column][$language] = $val[$defaultLanguage];
                }
            }
        }
        $this->_queue = $localizedData;
    }
46747
public function beforeSave(Model $model, $options = array()) {
        $alias = $model->alias;

        if (empty($model->data[$alias])) {
            return true;
        }

        // Loop through the data and upload the file
        foreach ($model->data[$alias] as $field => $file) {
            if (empty($this->settings[$alias][$field])) {
                continue;
            }

            // Gather attachment settings
            $attachment = $this->_settingsCallback($model, $this->settings[$alias][$field]);
            $data = array();

            // Initialize Transit
            $transit = new Transit($file);
            $transit->setDirectory($attachment['tempDir']);

            $this->_uploads[$alias] = $transit;

            // Set transformers and transporter
            $this->_addTransformers($model, $transit, $attachment);
            $this->_setTransporter($model, $transit, $attachment);

            // Attempt upload or import
            try {
                $overwrite = $attachment['overwrite'];
                $response = null;

                // File upload
                if (is_array($file)) {
                    $response = $transit->upload($overwrite);

                // Remote import
                } else if (preg_match('/^http/i', $file)) {
                    $response = $transit->importFromRemote($overwrite, $attachment['curl']);

                // Local import
                } else if (file_exists($file)) {
                    $response = $transit->importFromLocal($overwrite);

                // Stream import
                } else if (!empty($file)) {
                    $response = $transit->importFromStream($overwrite);
                }

                // Successful upload or import
                if ($response) {
                    $dbColumnMap = array($attachment['dbColumn']);
                    $transportConfig = array($this->_prepareTransport($attachment));

                    // Rename and move file
                    $data[$attachment['dbColumn']] = $this->_renameAndMove($model, $transit->getOriginalFile(), $attachment);

                    // Fetch exif data before transforming
                    $metaData = array();

                    foreach ($transit->getOriginalFile()->toArray() as $key => $value) {
                        if (substr($key, 0, 4) === 'exif' && $value) {
                            $metaData[$key] = $value;
                        }
                    }

                    // Transform the files and save their path
                    if ($attachment['transforms']) {
                        $transit->transform();

                        $transformedFiles = $transit->getTransformedFiles();
                        $count = 0;

                        foreach ($attachment['transforms'] as $transform) {
                            if ($transform['self']) {
                                $tempFile = $transit->getOriginalFile();
                                $dbColumnMap[0] = $transform['dbColumn'];

                            } else {
                                $tempFile = $transformedFiles[$count];
                                $dbColumnMap[] = $transform['dbColumn'];
                                $count++;

                                $transportConfig[] = $this->_prepareTransport($transform);
                            }

                            $data[$transform['dbColumn']] = $this->_renameAndMove($model, $tempFile, $transform);
                        }
                    }

                    $metaData = array_merge($transit->getOriginalFile()->toArray(), $metaData);

                    // Transport the files and save their remote path
                    if ($attachment['transport']) {
                        if ($transportedFiles = $transit->transport($transportConfig)) {
                            foreach ($transportedFiles as $i => $transportedFile) {
                                $data[$dbColumnMap[$i]] = $transportedFile;
                            }
                        }
                    }
                }

            // Trigger form errors if validation fails
            } catch (ValidationException $e) {
                $dbColumns = array_merge(array($attachment['dbColumn']), array_keys($attachment['transforms']));

                foreach ($dbColumns as $dbCol) {
                    unset($model->data[$alias][$dbCol]);
                }

                // Allow empty uploads
                if ($attachment['allowEmpty']) {
                    continue;
                }

                // Invalidate and stop
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                if ($attachment['stopSave']) {
                    return false;
                }

            // Log exceptions that shouldn't be shown to the client
            } catch (Exception $e) {
                $model->invalidate($field, __d('uploader', $e->getMessage()));

                $this->log($e->getMessage(), LOG_DEBUG);

                // Rollback the files since it threw errors
                $transit->rollback();

                if ($attachment['stopSave']) {
                    return false;
                }
            }

            // Save file meta data
            $cleanup = $data;

            if ($attachment['metaColumns'] && $data && !empty($metaData)) {
                foreach ($attachment['metaColumns'] as $method => $column) {
                    if (isset($metaData[$method]) && $column) {
                        $data[$column] = $metaData[$method];
                    }
                }
            }

            // Merge upload data with model data
            if ($data) {
                $model->data[$alias] = $data + $model->data[$alias];
            }

            // Keep it in a loop, so it will delete all files
            // If we are doing an update, delete the previous files that are being replaced
            if ($model->id && $cleanup) {
                $this->_cleanupOldFiles($model, $cleanup);
            }
        }

        return true;
    }
35137
public function beforeUpdate($model, &$data)
    {
        if ($this->weak) {
            return;
        }

        if (!$this->save_buffer) {
            return;
        }

        $update = $this->dsql();
        $update->set($model->persistence->typecastSaveRow($model, $this->save_buffer));
        $this->save_buffer = [];

        if ($this->reverse) {
            $update->where($this->foreign_field, $model->id);
        } else {
            $update->where($this->foreign_field, $model[$this->master_field]);
        }

        $update->update();
    }
855219
private function cacheModelByKeys(\Tx_Oelib_Model $model, array $data)
    {
        foreach ($this->additionalKeys as $key) {
            if (isset($data[$key])) {
                $value = $data[$key];
                if ($value !== '') {
                    $this->cacheByKey[$key][$value] = $model;
                }
            }
        }

        $this->cacheModelByCombinedKeys($model, $data);
        if (!empty($this->compoundKeyParts)) {
            $this->cacheModelByCompoundKey($model, $data);
        }
    }
1242773
public function beforeInsert($model, &$data)
    {
        if ($this->weak) {
            return;
        }

        if ($model->hasField($this->master_field)
            && $model[$this->master_field]
        ) {
            // The value for the master_field is set,
            // we are going to use existing record.
            return;
        }

        // Figure out where are we going to save data
        $persistence = $this->persistence ?:
            $this->owner->persistence;

        $this->id = $persistence->insert(
            $model,
            $this->save_buffer,
            $this->foreign_table
        );

        $data[$this->master_field] = $this->id;

        //$this->owner->set($this->master_field, $this->id);
    }
1035416
protected function getExcelData($data, \MUtil_Model_ModelAbstract $model)
    {
        $headings = array();
        $emptyMsg = $this->_('No data found.');
        foreach ($model->getItemsOrdered() as $name) {
            if ($label = $model->get($name, 'label')) {
                $headings[$name] = (string) $label;
            }
        }
        $results = array();
        $results[] = $headings;
        if ($headings) {
            if ($data) {
                foreach ($data as $row) {
                    foreach ($headings as $key => $value) {
                        $result[$key] = isset($row[$key]) ? $row[$key] : null;
                    }
                    $results[] = $result;
                }
                return $results;
            } else {
                foreach ($headings as $key => $value) {
                    $result[$key] = $emptyMsg;
                }
                $results[] = $result;
                return $results;
            }
        } else {
            return array($emptyMsg);
        }
    }
664757
protected function prepareModel(Model $model)
    {
        if (is_callable($this->prepareModel)) {
            call_user_func($this->prepareModel, $model);
        } else {
            foreach ($model->attributes() as $attribute) {
                $value = Yii::$app->settings->get($this->getSection($model), $attribute);

                if (!is_null($value)) {
                    $model->{$attribute} = $value;
                }
            }
        }
    }
1005696
public function prepareForm(ModelInterface $model = null, array $data = null, $useInputFilter = false, $useHydrator = false)
    {
        $argv = compact('model', 'data');
        $argv = $this->prepareEventArguments($argv);
        $this->getEventManager()->trigger(self::EVENT_PRE_PREPARE_FORM, $this, $argv);
        $data = $argv['data'];

        /* @var $form Form */
        $form = $this->getForm(null, $this->formOptions);

        if ($useInputFilter) {
            $form->setInputFilter($this->getInputFilter());
        }

        if ($useHydrator) {
            $form->setHydrator($this->getHydrator());
        }

        if ($model) {
            $form->bind($model);
        }

        if ($data) {
            $form->setData($data);
        }

        $argv = compact('form', 'model', 'data');
        $argv = $this->prepareEventArguments($argv);

        $this->getEventManager()->trigger(self::EVENT_POST_PREPARE_FORM, $this, $argv);

        return $form;
    }
547823
public function store(Model $model, $source, $value)
    {
        if ( ! $this->isTranslated()) {
            $this->performStore($model, $source, $value);
            return;
        }

        /** @var Model|Translatable $model */

        if ( ! is_array($value)) {
            throw new UnexpectedValueException("Value should be in per-locale array format for translatable data");
        }

        foreach ($value as $locale => $singleValue) {

            // Safeguard: use empty string if non-nullable translated field is null
            if (null === $singleValue && ! $this->isNullable()) {
                $singleValue = '';
            }

            $this->performStore($model->translateOrNew($locale), $source, $singleValue);
        }
    }
667027
protected function getFormFieldValuesFromModel(Model $model, array $keys)
    {
        $values = [];

        foreach ($keys as $key) {

            $field    = $this->getModelFormFieldDataForKey($key);
            $instance = $this->getFormFieldStoreStrategyInstanceForField($field);

            $instance->setFormFieldData($field);
            $instance->setParameters(
                $this->getFormFieldStoreStrategyParametersForField($field)
            );

            // If we're creating a new model, pre-select the form field for the active list parent
            if ( ! $model->exists && $this->isFieldValueBeDerivableFromListParent($field->key)) {

                try {
                    $values[ $key ] = $instance->valueForListParentKey($this->getListParentRecordKey());

                    // @codeCoverageIgnoreStart
                } catch (Exception $e) {
                    $message = "Failed retrieving value for form field '{$key}' (using " . get_class($instance)
                             . " (valueForListParentKey)): \n{$e->getMessage()}";

                    throw new StrategyRetrievalException($message, $e->getCode(), $e);
                    // @codeCoverageIgnoreEnd
                }

                continue;
            }

            try {
                $values[ $key ] = $instance->retrieve($model, $field->source ?: $field->key);

                // @codeCoverageIgnoreStart
            } catch (Exception $e) {
                $message = "Failed retrieving value for form field '{$key}' (using " . get_class($instance)
                         . "): \n{$e->getMessage()}";

                throw new StrategyRetrievalException($message, $e->getCode(), $e);
                // @codeCoverageIgnoreEnd
            }
        }

        return $values;
    }
44591
public function backup(array $data, $model)
    {
        $directory = gplcart_file_private_module('backup');

        if (!file_exists($directory) && !mkdir($directory, 0775, true)) {
            return false;
        }

        $data['type'] = 'module';
        $data['name'] = $this->translation->text('Module @name', array('@name' => $data['name']));

        $time = date('d-m-Y--G-i');
        $destination = gplcart_file_unique("$directory/module-{$data['id']}-$time.zip");
        $data['path'] = gplcart_file_relative($destination);

        $success = $this->zip->directory($data['directory'], $destination, $data['id']);

        if ($success) {
            return (bool) $model->add($data);
        }

        return false;
    }
272752
public function saveToModel(Model $model, Request $request)
    {
        $this->setModel($model);

        $model->setAttribute($this->getFieldName(), $this->getSaveValue($request));

        return $this;
    }
568530
public function onSave(Model $model)
    {
        $data            = $this->queryAttributes($model);
        $fieldData       = FieldData::query()->firstOrCreate($data);
        $fieldData->data = input($this->getName());
        return $fieldData->save();
    }