I am struggling with performing a validation problem, based on a field entity called published
I must apply validation rules:
- Validate entity when it is set to
true
- Do nothing when it is set to
false
(draft feature)
I managed to add a callback validator to canonical fields which check my rule and it works fine:
Validator definition
$emptyValidatorOnPublish = array(
'name' => 'Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'This field cannot be empty',
),
'callback' => function($value, $context=array()) {
if($context['published']){//Here I know the POST value
return !empty($value); //it must not be empty
}
return true;
},
),
);
Usage:
array(
'name' => 'title',
'description' => 'Title of the interview',
'required' => true,
'filters' => array(
0 => array(
'name' => 'Zend\\Filter\\StringTrim',
'options' => array()
),
1 => array(
'name' => 'Zend\\Filter\\StripTags',
'options' => array()
)
),
'validators' => array($emptyValidatorOnPublish),
'error_message' => 'title is required',
'allow_empty' => true,
'continue_if_empty' => true
)
Now I have on some fields which are validated with a ObjectExists
validator:
array(
'name' => 'person',
'description' => 'Person link',
'required' => true,
'filters' => array(),
'validators' => array(
0 => array(
'name' => 'MyApp\\Validators\\ObjectExists',
'options' => array(
'fields' => 'ref',
'message' => 'This person does not exist',
'object_manager' => 'doctrine.entitymanager.orm_default',
'object_repository' => 'MyApp\\Person'
)
)
),
'allow_empty' => true,
'continue_if_empty' => true
),
The ObjectExists
validator extends DoctrineModule\Validator\ObjectExists
.
class ObjectExists extends BaseObjectExists
{
/**
* {@inheritDoc}
*/
public function isValid($value)
{
if (! is_array($value)) {
return parent::isValid($value);
}
$isValid = null;
foreach ($value as $oneValue) {
$isValid = false === $isValid ? $isValid : parent::isValid($oneValue);
}
return $isValid;
}
}
Problem:
The parent class validator doesn't know the value of
published
Even if I change the implementation to check the
published
value I will get the value from the DB not from the actualPOST
request
Is there a way to check the existence of an entity depending on the published
value from the request?
Is there a way to pass a sibling value when validating another field (in my case pass 'published
when validating a person
)?