[Form] Fixed: required setting in FieldFactory is now properly overridable

This commit is contained in:
Bernhard Schussek 2011-01-27 15:12:55 +01:00 committed by Fabien Potencier
parent 0c3ca26e6e
commit 9e6e95d7e4

View File

@ -49,39 +49,41 @@ class FieldFactory implements FieldFactoryInterface
*/ */
public function getInstance($object, $property, array $options = array()) public function getInstance($object, $property, array $options = array())
{ {
$guess = $this->guess(function ($guesser) use ($object, $property) { // guess field class and options
return $guesser->guessMaxLength($object, $property); $classGuess = $this->guess(function ($guesser) use ($object, $property) {
});
$maxLength = $guess ? $guess->getValue() : null;
$guess = $this->guess(function ($guesser) use ($object, $property) {
return $guesser->guessClass($object, $property); return $guesser->guessClass($object, $property);
}); });
if (!$guess) { if (!$classGuess) {
throw new \RuntimeException(sprintf('No field could be guessed for property "%s" of class %s', $property, get_class($object))); throw new \RuntimeException(sprintf('No field could be guessed for property "%s" of class %s', $property, get_class($object)));
} }
$class = $guess->getClass(); // guess maximum length
$textField = 'Symfony\Component\Form\TextField'; $maxLengthGuess = $this->guess(function ($guesser) use ($object, $property) {
return $guesser->guessMaxLength($object, $property);
});
if (null !== $maxLength && ($class == $textField || is_subclass_of($class, $textField))) { // guess whether field is required
$options = array_merge(array('max_length' => $maxLength), $options); $requiredGuess = $this->guess(function ($guesser) use ($object, $property) {
}
$options = array_merge($guess->getOptions(), $options);
$field = new $class($property, $options);
$guess = $this->guess(function ($guesser) use ($object, $property) {
return $guesser->guessRequired($object, $property); return $guesser->guessRequired($object, $property);
}); });
if ($guess) { // construct field
$field->setRequired($guess->getValue()); $class = $classGuess->getClass();
$textField = 'Symfony\Component\Form\TextField';
if ($maxLengthGuess && ($class == $textField || is_subclass_of($class, $textField))) {
$options = array_merge(array('max_length' => $maxLengthGuess->getValue()), $options);
} }
return $field; if ($requiredGuess) {
$options = array_merge(array('required' => $requiredGuess->getValue()), $options);
}
// user options may override guessed options
$options = array_merge($classGuess->getOptions(), $options);
return new $class($property, $options);
} }
/** /**