Renders a form field.

@param mixed       $value
@param mixed       $originalValue
@param array       $errors
@param null|string $locale
@return string
426232
public function renderField($value, $originalValue, array $errors = [], $locale = null)
    {
        $value         = $this->normalizeValue($value);
        $originalValue = $this->normalizeValue($originalValue, true);

        $type = $this->field->type ?: array_get($this->field->options(), 'type', $this->getDefaultFieldType());

        $data = [
            'record'     => $this->model,
            'key'        => $this->field->key() . ($locale ? '-locale:' . $locale : null),
            'baseKey'    => $this->field->key(),
            'name'       => $this->getFormFieldName($locale),
            'value'      => $value,
            'original'   => $originalValue,
            'type'       => $type,
            'errors'     => $errors,
            'required'   => $this->field->required(),
            'options'    => $this->field->options(),
            'translated' => $this->field->translated(),
        ];

        return view($this->getView(), $this->decorateFieldData($data));
    }
1270294
protected function validateValue($value, EiFieldValidationResult $validationResult) {
		if ($value != null) {
			CastUtils::assertTrue($value instanceof EiuFieldMap);
			
			$eiEntryValidationResult = new EiEntryValidationResult();
			$validationResult->addSubEiEntryValidationResult($eiEntryValidationResult);
			$value->validate($eiEntryValidationResult);
			return;
		}
		
		if ($this->eiProp->isMandatory()) {
			$validationResult->addError(Message::createCodeArg('common_field_required_err', 
					['field' => $this->eiProp->getLabelLstr()->t($this->eiu->getN2nLocale())], null, 'rocket'));
		}
	}
1241724
public function npgettext($context, $original, $plural, $value)
    {
        $message = $context."\x04".$original;
        $translation = ngettext($message, $plural, $value);

        return ($translation === $message) ? $original : $translation;
    }
1276189
public function validateValueType($value)
    {
        if ($this->hasOption(Entity\Reflection\Property\Option\Primary::KEY)
            && (Entity\Reflection\Property\Option\Primary::isEmpty($value))
        ) {
            throw new Exception\InvalidArgumentException(
                "Primary value can not be empty string or null!",
                $value
            );
        }

        if ($value === null) {
            return;
        }

        // Enumeration
        if ($this->hasOption(Entity\Reflection\Property\Option\Enum::KEY)
            && !$this->getOption(Entity\Reflection\Property\Option\Enum::KEY)->isValid($value)
        ) {
            throw new Exception\InvalidArgumentException(
                "Value " . $value . " is not from defined entity enumeration "
                . "range on property " . $this->name . "!",
                $value
            );
        }

        // Scalar or array type
        if (self::isScalarType($this->type) || $this->type === self::TYPE_ARRAY) {

            if (gettype($value) === $this->type) {
                return;
            }
            throw new Exception\InvalidArgumentException(
                "Expected " . $this->type . " but " . gettype($value)
                . " given on property " . $this->name . "!",
                $value
            );
        }

        // Object validation
        $givenType = gettype($value);
        if ($givenType === "object") {
            $givenType = get_class($value);
        }

        if ($this->type === self::TYPE_ENTITY) {
            // Entity

            $expectedEntityClass = Convention::nameToClass($this->typeOption, Convention::ENTITY_MASK);
            if ($value instanceof $expectedEntityClass) {
                return;
            } else {
                throw new Exception\InvalidArgumentException(
                    "Expected entity " . $this->typeOption . " but " . $givenType
                    . " given on property " . $this->name . "!",
                    $value
                );
            }
        } elseif ($this->type === self::TYPE_COLLECTION) {
            // Collection

            $entityClass = Convention::nameToClass($this->typeOption, Convention::ENTITY_MASK);
            if (!$value instanceof Entity\Collection) {

                throw new Exception\InvalidArgumentException(
                    "Expected entity collection but " . $givenType . " given on"
                    . " property " . $this->name . "!",
                    $value
                );
            } elseif ($value->getEntityClass() !== $entityClass) {
                throw new Exception\InvalidArgumentException(
                    "Expected collection of entity " . $entityClass
                    . " but collection of entity " . $value->getEntityClass()
                    . " given on property " . $this->name . "!",
                    $value
                );
            } else {
                return;
            }
        } elseif ($this->type === self::TYPE_DATETIME) {
            // DateTime

            if ($value instanceof \DateTime) {
                return;
            } else {
                throw new Exception\InvalidArgumentException(
                    "Expected DateTime but " . $givenType . " given on"
                    . " property " . $this->name . "!",
                    $value
                );
            }
        } elseif ($this->type === self::TYPE_DATE) {
            // Date

            if ($value instanceof \DateTime) {
                return;
            } else {
                throw new Exception\InvalidArgumentException(
                    "Expected date as DateTime object but " . $givenType
                    . " given on property " . $this->name . "!",
                    $value
                );
            }
        } else {
            // Unexpected

            throw new \Exception("Unsupported type " . $this->type . "!");
        }
    }
361387
public function setValue($value)
	{
		// any preparation goes here, for example casting to int
		$errors = $this->getValidationErrors($value);
		// if specific validation existed would go here & if
		// anything goes wrong will put error message into errors
		if(!empty($errors))
			throw $this->getContext()->getModel('ValidationException', 'Form', array(($errors)));
		return $value;
	}
670818
public function present($value, $depth = null, $options = 0)
    {
        $data = $this->cloner->cloneVar($value, !($options & self::VERBOSE) ? Caster::EXCLUDE_VERBOSE : 0);

        if (null !== $depth) {
            $data = $data->withMaxDepth($depth);
        }

        // Work around https://github.com/symfony/symfony/issues/23572
        $oldLocale = \setlocale(LC_NUMERIC, 0);
        \setlocale(LC_NUMERIC, 'C');

        $output = '';
        $this->dumper->dump($data, function ($line, $depth) use (&$output) {
            if ($depth >= 0) {
                if ('' !== $output) {
                    $output .= PHP_EOL;
                }
                $output .= \str_repeat('  ', $depth) . $line;
            }
        });

        // Now put the locale back
        \setlocale(LC_NUMERIC, $oldLocale);

        return OutputFormatter::escape($output);
    }
765605
public function formatLocale($locale = null, Closure $callback = null)
    {
        if (!class_exists('\NumberFormatter')) {
            throw new BadFunctionCallException('Class NumberFormatter not exists. Require ext-intl extension.');
        }

        $formatter = new \NumberFormatter($locale ?: static::getLocale(), \NumberFormatter::CURRENCY);

        if (is_callable($callback)) {
            $callback($formatter);
        }

        return $formatter->formatCurrency($this->getValue(), $this->currency->getCurrency());
    }
419797
function renderElement(&$element, $required, $error){
        global $OUTPUT;

        // Make sure the element has an id.
        $element->_generateId();
        $advanced = isset($this->_advancedElements[$element->getName()]);

        $html = $OUTPUT->mform_element($element, $required, $advanced, $error, false);
        $fromtemplate = !empty($html);
        if (!$fromtemplate) {
            // Adding stuff to place holders in template
            // check if this is a group element first.
            if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
                // So it gets substitutions for *each* element.
                $html = $this->_groupElementTemplate;
            } else if (method_exists($element, 'getElementTemplateType')) {
                $html = $this->_elementTemplates[$element->getElementTemplateType()];
            } else {
                $html = $this->_elementTemplates['default'];
            }
            if (isset($this->_advancedElements[$element->getName()])) {
                $html = str_replace(' {advanced}', ' advanced', $html);
                $html = str_replace(' {aria-live}', ' aria-live="polite"', $html);
            } else {
                $html = str_replace(' {advanced}', '', $html);
                $html = str_replace(' {aria-live}', '', $html);
            }
            if (isset($this->_advancedElements[$element->getName()]) || $element->getName() == 'mform_showadvanced') {
                $html = str_replace('{advancedimg}', $this->_advancedHTML, $html);
            } else {
                $html = str_replace('{advancedimg}', '', $html);
            }
            $html = str_replace('{id}', 'fitem_' . $element->getAttribute('id'), $html);
            $html = str_replace('{typeclass}', 'f' . $element->getType(), $html);
            $html = str_replace('{type}', $element->getType(), $html);
            $html = str_replace('{name}', $element->getName(), $html);
            $html = str_replace('{groupname}', '', $html);
            $html = str_replace('{class}', $element->getAttribute('class'), $html);
            $emptylabel = '';
            if ($element->getLabel() == '') {
                $emptylabel = 'femptylabel';
            }
            $html = str_replace('{emptylabel}', $emptylabel, $html);
            if (method_exists($element, 'getHelpButton')) {
                $html = str_replace('{help}', $element->getHelpButton(), $html);
            } else {
                $html = str_replace('{help}', '', $html);
            }
        } else {
            if ($this->_inGroup) {
                $this->_groupElementTemplate = $html;
            }
        }
        if (($this->_inGroup) and !empty($this->_groupElementTemplate)) {
            $this->_groupElementTemplate = $html;
        } else if (!isset($this->_templates[$element->getName()])) {
            $this->_templates[$element->getName()] = $html;
        }

        if (!$fromtemplate) {
            parent::renderElement($element, $required, $error);
        } else {
            if (in_array($element->getName(), $this->_stopFieldsetElements) && $this->_fieldsetsOpen > 0) {
                $this->_html .= $this->_closeFieldsetTemplate;
                $this->_fieldsetsOpen--;
            }
            $this->_html .= $html;
        }
    }
1760
public function renderValue(array $context, $value, array $parameters = [], ?string $viewContext = null): string
    {
        try {
            return $this->renderer->renderValue(
                $value,
                $this->getViewContext($context, $viewContext),
                $parameters
            );
        } catch (Throwable $t) {
            $message = sprintf(
                'Error rendering a value of type "%s"',
                is_object($value) ? get_class($value) : gettype($value)
            );

            $this->errorHandler->handleError($t, $message, ['object' => $value]);
        }

        return '';
    }
552648
public function detect_errors($value, $type, $restrictions = array()){
		$errors = array();

		$is_required = @$restrictions['required'];
		if( $is_required && !strlen($value) ){
			// NOT NULL 制約
			// 空白文字も NULL と同様に扱う
			array_push($errors, 'Required.');
			return $errors;
		}
		if( !$is_required && !strlen($value) ){
			// NOT NULL 制約 がなくて値が空白の場合
			// 空白文字も NULL と同様に扱う
			return $errors;
		}

		$type_info = $this->exdb->form_elements()->get_type_info($type);
		if( is_callable($type_info['validate']) ){
			$errors = $type_info['validate']($value, $restrictions);
		}
		return $errors;
	}
28417
public function format($value, $params = null, $locale = null) {
		if (! isset($params['primary'])) {
			return $this->getFormatter($locale)->format($value);
		}
		
		if ($params['primary'] === 'day') {
			return $this->getFormatterDay($locale)->format($value);
		}
		
		if ($params['primary'] === 'time') {
			return $this->getFormatterTime($locale)->format($value);
		}
		
		return $this->getFormatter($locale)->format($value);
	}
1292712
protected function validate_parentid($value) {

        // Check that the parent exists. But only if we don't have it already, and we actually have a parent.
        if (!empty($value) && !$this->newparent && !self::record_exists($value)) {
            return new lang_string('invaliddata', 'error');
        }

        // During update.
        if ($this->get('id')) {

            // If there is a new parent.
            if ($this->beforeupdate->get('parentid') != $value && $this->newparent) {

                // Check that the new parent belongs to the same framework.
                if ($this->newparent->get('competencyframeworkid') != $this->get('competencyframeworkid')) {
                    return new lang_string('invaliddata', 'error');
                }
            }
        }

        return true;
    }
293378
public function renderFormJavascriptPrototypes(array $context, FormView $rootView)
    {
        if (!isset($rootView->vars['prototype'])) {
            throw new \InvalidArgumentException('The given root form view has no prototype');
        }

        $stack = [
            // FormView $prototype, string $prototypeName, string[] $parentPrototypeNames
            [$rootView->vars['prototype'], $rootView->vars['prototype']->vars['name'], []],
        ];

        $output = '[';
        $counter = 0;

        while (list($prototype, $prototypeName, $parentPrototypeNames) = \array_pop($stack)) {
            try {
                // the "unique_block_prefix" must be changed to prevent messing
                // up FormRenderer's internal cache and causing errors later on
                $prototype->vars['unique_block_prefix'] .= \sprintf('_%d', ++$this->prototypeRenderUidSeq);

                if (isset($prototype->vars['prototype'])) {
                    // directly nested collection prototypes lead to recursion in searchAndRenderBlock()
                    throw new \RuntimeException('Directly nested collections with prototypes are not supported. Add an intermediate type or disable prototypes.');
                }
                $code = $this->renderer->searchAndRenderBlock($prototype, 'javascript_prototype', $context);

                if (++$counter > 1) {
                    $output .= ",\n";
                }

                $output .= \sprintf(
                    '{id: %s, prototypeName: %s, parentPrototypeNames: %s, initializer: function ($field) { %s }}',
                    \json_encode($prototype->vars['id']),
                    \json_encode($prototypeName),
                    \json_encode($parentPrototypeNames),
                    $code
                );
            } catch (\LogicException $e) {
                foreach ($prototype->children as $child) {
                    $stack[] = isset($child->vars['prototype'])
                        ? [
                            $child->vars['prototype'],
                            $child->vars['prototype']->vars['name'],
                            \array_merge($parentPrototypeNames, [$prototypeName]),
                        ]
                        : [
                            $child,
                            $prototypeName,
                            $parentPrototypeNames,
                        ];
                }
            }
        }

        $output .= ']';

        return $output;
    }
547058
protected function normalizeValue($value, $original = false)
    {
        if (is_array($value)) {
            return $value;
        }

        if ($value instanceof Arrayable) {
            return $value->toArray();
        }

        return [ $value => [] ];
    }
1113004
public function render($value)
    {
        if ($this->shouldMinify($value)) {
            $replace = [
                '/<!--[^\[](.*?)[^\]]-->/s' => '',
                "/<\?php/"                  => '<?php ',
                "/\n([\S])/"                => ' $1',
                "/\r/"                      => '',
                "/\n/"                      => '',
                "/\t/"                      => ' ',
                '/ +/'                      => ' ',
            ];

            $value = preg_replace(array_keys($replace), array_values($replace), $value);
        } else {
            // Where skip minification tags are used let's remove them from markdown or blade.
            $value = preg_replace("/<!--[\s]+skip\.minification[\s]+-->/", '', $value);
        }

        return $value;
    }
375436
private function _viewForm($value) {
        $required = null;
        if ($value['Null'] === 'NO') {
            $required = ", 'required' => true";
        }
        switch (explode('(', $value['Type'])[0]) {
            case 'enum':
                $str = rtrim(substr($value['Type'], strpos($value['Type'], '(')), ')');
                return "select('{$value['Field']}', [{$str}])";
            case 'text':
                return "textArea('{$value['Field']}', ['label' => '{$value['Field']}'{$required}])";
            case 'int':
            case 'varchar':
            case 'char':
            default:
                return "text('{$value['Field']}', ['label' => '{$value['Field']}'{$required}])";
        }
    }
960557
protected function createError(string $expectation, $value = null): Error
    {
        if ($value !== null) {
            $error = new Error('expected: %s found: %s', 1328557141, [$expectation, $this->renderValue($value)],
                'Validation Error');
        } else {
            $error = new Error($expectation, 1328557141, [], 'Validation Error');
        }
        return $error;
    }