[英]ZF2 + Doctrine2 - Fieldset in Fieldset of a Collection in Fieldset does not validate properly
[英]ZF2: Validate collection field based on parent fieldset element
我正在嘗試驗證集合中的字段。
該集合指的是公司領域,並與公司字段集相關
驗證需要檢查數據庫中該公司的區域名稱是否尚不存在。
我正在嘗試使用集合元素“ area_name”中的回調驗證器來執行此操作,我的問題是集合僅了解其自身的上下文,這意味着與該Area相關聯的所有字段均不了解公司上下文,因此我無法按公司的母公司篩選我的驗證人。
有沒有辦法訪問集合的父上下文? 還是在驗證之前需要初始化將Company對象傳遞給Collection的表單?
編輯 :我忘了提到我正在使用Doctrine2,所以我不確定是否可以使用與ZF2捆綁在一起的Db_NoRecordExists驗證程序
這是一個古老的問題,您可能已經解決了,但是最近我也遇到了類似的問題。
您可以在區域模型/服務中創建一個函數:validateAreaCompanyRelation(區域,公司),並在您的字段集中使用回調函數來使用它:
AreaService類:添加一種方法,該方法基於受1行限制的查詢返回true或false。 就我而言,是這樣的:
public function validateAreaCompanyRelation($company, $area)
{
$result = false;
$count = $this->getRepository()
->createQueryBuilder('q')
->select('q')
->innerJoin('q.company', 'c')
->innerJoin('q.area','b')
->where('b.id = :area and c.company = :company')
->setParameter('area',$area)
->setParameter('company',$area)
->setMaxResults( 1 )
->getQuery()
->getArrayResult();
if(count($count) <>1){
$result=true;
}
return $result;
}
Area字段集:將AreaService注入字段集(將其傳遞給工廠構造)
class AreaFieldset extends Fieldset implements InputFilterProviderInterface
{
private $areaService;
public function __construct(areaServiceEntityService $areaService)
{
$this->areaService = $areaService;
}
public function init()
{
$this->add(
array(
'name' => 'area',
'filters' => array(),
'validators' => array (
array(
'name' => 'Zend\Validator\Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Your custom error message',
),
'callback' => array($this,'vlidateUniqueRelation'),
),
),
)
)
);
array(
'name' => 'company',
'filters' => array(),
'validators' => array (
array(
'name' => 'Zend\Validator\Callback',
'options' => array(
'messages' => array(
\Zend\Validator\Callback::INVALID_VALUE => 'Your custom error message',,
),
'callback' => array($this,'vlidateUniqueRelation'),
),
),
)
)
);
}
public function vlidateUniqueRelation($value, $context)
{
// $value = value
// $context['xxxx'] = xxxxx value
// Logic to validate goes here
$context["company"]
$context["area"]
return $this->AreaService->validateAreaCompanyRelation($context["company"], $context["Area"]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.