Skip to content

Instantly share code, notes, and snippets.

@winzou
Created July 21, 2011 02:36
Show Gist options
  • Save winzou/1096397 to your computer and use it in GitHub Desktop.
Save winzou/1096397 to your computer and use it in GitHub Desktop.
Subform Validation
<?php
namespace Asso\BookBundle\Form;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
/**
* @Annotation
*/
class AmountModel
{
/**
* @Assert\Min(99)
*/
private $debit;
/**
* @Assert\Min(99)
*/
private $credit;
public function setDebit($debit)
{
$this->debit = $debit;
}
public function getDebit()
{
return $this->debit;
}
public function setCredit($credit)
{
$this->credit = $credit;
}
public function getCredit()
{
return $this->credit;
}
/**
* @Assert\True(message = "The amount is invalid")
*/
public function isCreditValid()
{
exit('I am triggered !'); // just to see if the validator goes through this method
return false;
}
}
<?php
namespace Asso\BookBundle\Form;
class AmountTransformer implements DataTransformerInterface
{
public function transform($value)
{
$amount = new AmountModel;
if( $value < 0 )
{
$amount->setDebit(-$value);
$amount->setCredit(0);
}
else
{
$amount->setCredit($value);
$amount->setDebit(0);
}
return $amount;
}
public function reverseTransform($value)
{
if( $value->getCredit() != 0 AND $value->getDebit() != 0 )
{
throw new TransformationFailedException('Transformation failed cause amount is not valid');
}
return ( $value->getCredit() - $value->getDebit() );
}
}
<?php
namespace Asso\BookBundle\Form;
class AmountType extends AbstractType
{
/**
* @see Symfony\Component\Form.AbstractType::buildForm()
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('debit', 'integer', array('required' => false))
->add('credit', 'integer', array('required' => false));
$builder->appendClientTransformer(new AmountTransformer);
return parent::buildForm($builder, $options);
}
/**
* @see Symfony\Component\Form.AbstractType::getDefaultOptions()
*/
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Asso\BookBundle\Form\AmountModel',
);
}
/**
* @see Symfony\Component\Form.AbstractType::getName()
*/
public function getName()
{
return 'asso_book.amount';
}
}
<?php
namespace Asso\BookBundle\Form;
class EntryType extends AbstractType
{
/**
* @see Symfony\Component\Form.AbstractType::buildForm()
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('label')
->add('amount', new AmountType)
->add('date')
;
}
/**
* @see Symfony\Component\Form.AbstractType::getDefaultOptions()
*/
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Asso\BookBundle\Entity\Entry',
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment