$rules = new Assert\Collection([
"items" => new Assert\Required([
new Assert\NotBlank(),
new Assert\Callback(function ($value, ExecutionContextInterface $context) {
$validator = $context->getValidator();
$violations = $validator->validate($value, new Assert\Type('array'));
if ($violations->count() > 0) {
/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
$context
->buildViolation($violation->getMessage(), $violation->getParameters())
->atPath('items')
->addViolation()
;
}
return;
}
$violations = $validator->validate($value, new Assert\All([
new Assert\Type('array'),
new Assert\Collection([
"id" => new Assert\NotBlank(),
"quantity" => new Assert\NotBlank(),
])
]));
/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
$context
->buildViolation($violation->getMessage(), $violation->getParameters())
->atPath('items'. $violation->getPropertyPath())
->addViolation()
;
}
}),
]),
]);
$validator = Validation::createValidator();
$data = [
'items' => [
[
'id' => 'id',
'quantity' => 'quantity',
],
],
];
dump($validator->validate($data, $rules)); // Ok
$data = [
'items' => 1,
];
dump($validator->validate($data, $rules)); // Ko
$data = [
'items' => [
[
'id' => 'id',
'quantity' => 'quantity',
],
[
'id2' => 'id',
'quantity2' => 'quantity',
]
],
];
dump($validator->validate($data, $rules)); // Ko
// src/Acme/SecurityBundle/Controller/Main;
namespace Acme\SecurityBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
class SecurityController extends Controller
{
public function loginAction()
{
$request = $this->getRequest();
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
if ($error && !filter_var(SecurityContext::LAST_USERNAME, FILTER_VALIDATE_EMAIL)) {
$error = new \Exception('Invalid e-mail');
}
return $this->render('AcmeSecurityBundle:Security:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
}