Skip to content

Instantly share code, notes, and snippets.

@fivestar
Created June 23, 2010 04:33
Show Gist options
  • Save fivestar/449498 to your computer and use it in GitHub Desktop.
Save fivestar/449498 to your computer and use it in GitHub Desktop.
<?php
use Symfony\Components\Form\Form;
use Symfony\Components\Form\FieldGroup;
use Symfony\Components\Form\ChoiceField;
use Symfony\Components\Form\TextField;
use Symfony\Components\Form\CheckboxField;
use Symfony\Components\Form\NumberField;
use Symfony\Components\Form\PasswordField;
use Symfony\Components\Form\RepeatedField;
use Symfony\Components\Validator\Validator;
use Symfony\Components\Validator\ConstraintValidatorFactory;
use Symfony\Components\Validator\Constraints\Min;
use Symfony\Components\Validator\Constraints\Max;
use Symfony\Components\Validator\Constraints\MinLength;
use Symfony\Components\Validator\Constraints\MaxLength;
use Symfony\Components\Validator\Constraints\AssertType;
use Symfony\Components\Validator\Constraints\Email;
use Symfony\Components\Validator\Constraints\Choice;
use Symfony\Components\Validator\Constraints\Valid;
use Symfony\Components\Validator\Constraints\NotBlank;
use Symfony\Components\Validator\Mapping\ClassMetadataFactory;
use Symfony\Components\Validator\Mapping\ClassMetadata;
use Symfony\Components\Validator\Mapping\Loader\LoaderChain;
use Symfony\Components\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Components\Validator\Mapping\Loader\XmlFileLoader;
use Symfony\Components\Validator\MessageInterpolator\XliffMessageInterpolator;
use Symfony\Foundation\UniversalClassLoader;
// path pointing to Symfony 2
define('SYMFONY_DIR', __DIR__.'/symfony');
require_once SYMFONY_DIR.'/src/Symfony/Foundation/UniversalClassLoader.php';
class User
{
private $firstName;
private $lastName;
private $email;
private $married = false;
private $age;
private $gender;
private $address;
public function getFirstName() { return $this->firstName; }
public function setFirstName($firstName) { $this->firstName = $firstName; }
public function getLastName() { return $this->lastName; }
public function setLastName($lastName) { $this->lastName = $lastName; }
public function getEmail() { return $this->email; }
public function setEmail($email) { $this->email = $email; }
public function isMarried() { return $this->married; }
public function setMarried($married) { $this->married = (bool)$married; }
public function getAge() { return $this->age; }
public function setAge($age) { $this->age = $age; }
public function getGender() { return $this->gender; }
public function setGender($gender) { $this->gender = $gender; }
public function getAddress() { return $this->address; }
public function setAddress($address) { $this->address = $address; }
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addGetterConstraint('firstName', new MinLength(2));
$metadata->addGetterConstraint('lastName', new MinLength(2));
$metadata->addGetterConstraint('firstName', new NotBlank());
$metadata->addGetterConstraint('lastName', new NotBlank());
$metadata->addGetterConstraint('email', new Email());
$metadata->addGetterConstraint('email', new NotBlank());
$metadata->addGetterConstraint('age', new Min(6));
$metadata->addGetterConstraint('gender', new Choice(array('choices' => self::getGenders())));
$metadata->addGetterConstraint('address', new Valid());
}
public static function getGenders()
{
return array('male', 'female');
}
}
class Address
{
private $street;
private $zipCode;
private $city;
public function getStreet() { return $this->street; }
public function setStreet($street) { $this->street = $street; }
public function getZipCode() { return $this->zipCode; }
public function setZipCode($zipCode) { $this->zipCode = $zipCode; }
public function getCity() { return $this->city; }
public function setCity($city) { $this->city = $city; }
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addGetterConstraint('street', new MinLength(6));
$metadata->addGetterConstraint('zipCode', new MinLength(4));
$metadata->addGetterConstraint('zipCode', new MaxLength(5));
$metadata->addGetterConstraint('zipCode', new AssertType('numeric'));
$metadata->addGetterConstraint('city', new MinLength(3));
}
}
\Locale::setDefault('ja_JP');
// initialize autoloader
$loader = new UniversalClassLoader();
$loader->registerNamespace('Symfony', SYMFONY_DIR.'/src');
$loader->register();
// initialize validator
$metadataFactory = new ClassMetadataFactory(new LoaderChain(array(
new StaticMethodLoader('loadValidatorMetadata'),
new XmlFileLoader(SYMFONY_DIR.'/src/Symfony/Components/Form/Resources/config/validation.xml'),
)));
$validatorFactory = new ConstraintValidatorFactory();
$messageInterpolator = new XliffMessageInterpolator(SYMFONY_DIR.'/src/Symfony/Components/Validator/Resources/i18n/messages.en.xml');
$validator = new Validator($metadataFactory, $validatorFactory, $messageInterpolator);
// create new business object
$user = new User();
$user->setAddress(new Address());
// create form to interact with the business object
$form = new Form('user', $user, $validator);
$form->add(new TextField('firstName'));
$form->add(new TextField('lastName'));
$form->add(new RepeatedField(new TextField('email')));
$form->add(new CheckboxField('married'));
$form->add(new NumberField('age'));
$form->add(new ChoiceField('gender', array('choices' => array_combine(User::getGenders(), User::getGenders()))));
$addressGroup = new FieldGroup('address');
$addressGroup->add(new TextField('street'));
$addressGroup->add(new TextField('zipCode'));
$addressGroup->add(new TextField('city'));
$form->add($addressGroup);
if (PHP_SAPI === 'cli' && !debug_backtrace()) {
$params = array(
'firstName' => 'Katsuhiro',
'lastName' => 'Ogawa',
'email' => array(
'first' => 'katsuhiro.ogawa@example.com',
'second' => 'katsuhiro.ogawa@example.com',
),
'married' => false, # ^q^
'age' => 23,
'gender' => 'male',
'address' => array(
'street' => 'Hongou 3-38-1-701',
'zipCode' => '113-0033',
'city' => 'Bunkyo-ku',
),
);
$_POST['user'] = $params;
}
// bind POST data to the form
if (isset($_POST['user'])) {
$form->bind($_POST['user']);
var_dump($user);
// object(User)#9 (7) {
// ["firstName":"User":private]=>
// string(9) "Katsuhiro"
// ["lastName":"User":private]=>
// string(5) "Ogawa"
// ["email":"User":private]=>
// string(21) "katsuhiro.ogawa@example.com"
// ["married":"User":private]=>
// bool(false)
// ["age":"User":private]=>
// float(23)
// ["gender":"User":private]=>
// string(4) "male"
// ["address":"User":private]=>
// object(Address)#34 (3) {
// ["street":"Address":private]=>
// string(17) "Hongou 3-38-1-701"
// ["zipCode":"Address":private]=>
// string(8) "113-0033"
// ["city":"Address":private]=>
// string(9) "Bunkyo-ku"
// }
// }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form Component</title>
</head>
<body>
<form action="<?php echo @$_SERVER['SCRIPT_NAME'] ?: '#' ?>" method="post">
<?php echo $form->renderErrors() ?>
<?php echo $form->render() ?>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment