_request = $request; $context += [ 'entity' => null, ]; $this->_form = $context['entity']; } /** * {@inheritDoc} */ public function primaryKey() { return []; } /** * {@inheritDoc} */ public function isPrimaryKey($field) { return false; } /** * {@inheritDoc} */ public function isCreate() { return true; } /** * {@inheritDoc} */ public function val($field, $options = []) { $options += [ 'default' => null, 'schemaDefault' => true ]; $val = $this->_request->getData($field); if ($val !== null) { return $val; } $val = $this->_form->getData($field); if ($val !== null) { return $val; } if ($options['default'] !== null || !$options['schemaDefault']) { return $options['default']; } return $this->_schemaDefault($field); } /** * Get default value from form schema for given field. * * @param string $field Field name. * @return mixed */ protected function _schemaDefault($field) { $field = $this->_form->schema()->field($field); if ($field) { return $field['default']; } return null; } /** * {@inheritDoc} */ public function isRequired($field) { $validator = $this->_form->getValidator(); if (!$validator->hasField($field)) { return false; } if ($this->type($field) !== 'boolean') { return $validator->isEmptyAllowed($field, $this->isCreate()) === false; } return false; } /** * {@inheritDoc} */ public function getRequiredMessage($field) { $parts = explode('.', $field); $validator = $this->_form->getValidator(); $fieldName = array_pop($parts); if (!$validator->hasField($fieldName)) { return null; } $ruleset = $validator->field($fieldName); $requiredMessage = $validator->getRequiredMessage($fieldName); $emptyMessage = $validator->getNotEmptyMessage($fieldName); if ($ruleset->isPresenceRequired() && $requiredMessage) { return $requiredMessage; } if (!$ruleset->isEmptyAllowed() && $emptyMessage) { return $emptyMessage; } return null; } /** * {@inheritDoc} */ public function getMaxLength($field) { $validator = $this->_form->getValidator(); if (!$validator->hasField($field)) { return null; } foreach ($validator->field($field)->rules() as $rule) { if ($rule->get('rule') === 'maxLength') { return $rule->get('pass')[0]; } } return null; } /** * {@inheritDoc} */ public function fieldNames() { return $this->_form->schema()->fields(); } /** * {@inheritDoc} */ public function type($field) { return $this->_form->schema()->fieldType($field); } /** * {@inheritDoc} */ public function attributes($field) { $column = (array)$this->_form->schema()->field($field); $whiteList = ['length' => null, 'precision' => null]; return array_intersect_key($column, $whiteList); } /** * {@inheritDoc} */ public function hasError($field) { $errors = $this->error($field); return count($errors) > 0; } /** * {@inheritDoc} */ public function error($field) { return array_values((array)Hash::get($this->_form->getErrors(), $field, [])); } }