2017-01-01 2 views
1
use App\Model\Rule\CustomIsUnique; 

$rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [ 
    'errorField' => 'item_id', 
    'message' => 'Item Unit must be unique.' 
]); 

На CustomIsUnique Я копировать вставить коды IsUniqueНаписание пользовательских правил для CakePHP модели

Cake\ORM\Rule\IsUnique; 

Но, как расширить или добавить больше операций внутри метода __invoke?

Update ::

public function __invoke(EntityInterface $entity, array $options) 
{ 
    $result = parent::__invoke($entity, $options); 
    if ($result) { 
     return true; 
    } else { 
     if ($options['type'] == 'item_units') { 
      $data = TableRegistry::get('item_units')->find() 
       ->where(['item_id' => $entity['item_id'], 
        'manufacture_unit_id' => $entity['manufacture_unit_id'], 
        'status !=' => 99])->hydrate(false)->first(); 
      if (empty($data)) { 
       return true; 
      } 
     } elseif ($options['type'] == 'production_rules') { 
      $data = TableRegistry::get('production_rules')->find() 
       ->where(['input_item_id' => $entity['input_item_id'], 
        'output_item_id' => $entity['output_item_id'], 
        'status !=' => 99])->hydrate(false)->first(); 
      if (empty($data)) { 
       return true; 
      } 
     } elseif ($options['type'] == 'prices') { 
      $data = TableRegistry::get('prices')->find() 
       ->where(['item_id' => $entity['item_id'], 
        'manufacture_unit_id' => $entity['manufacture_unit_id'], 
        'status !=' => 99])->hydrate(false)->first(); 
      if (empty($data)) { 
       return true; 
      } 
     } 
    } 
} 

это, как я реализовал для другой модели и передается дополнительный параметр вместе с вариантов массива. Я думаю, что это не лучший способ сделать это.

ответ

2

Если вы хотите продлить правило ядро ​​приложения, вы можете сделать что-то вроде:

<?php 
use App\Model\Rule; 

class CustomIsUnique extends Cake\ORM\Rule\IsUnique 
{ 
    public function __invoke(EntityInterface $entity, array $options) 
    { 
     $result = parent::__invoke($entity, $options); 
     if ($result) { 
      // the record is indeed unique 
      return true; 
     } 
     // do any other checking here 
     // for instance, checking if the existing record 
     // has a different deletion status than the one 
     // you are inserting 
    } 
} 

Это позволит вам добавить любую дополнительную логику для вашего приложения.

+0

Я не понимаю, о чем вы просите сейчас. –

Смежные вопросы