我正在使用CakePHP3,我使用此表创建了de Config模型:
+----------------------+---------------------------+
| param | value |
+----------------------+---------------------------+
| dhcp_dns1 | 192.168.1.100 |
| dhcp_dns2 | 192.168.1.100 |
| dhcp_enabled | 1 |
| dhcp_end_ip | 192.168.1.200 |
| dhcp_netmask | 255.255.255.0 |
| dhcp_router | 192.168.1.100 |
| dhcp_start_ip | 192.168.1.100 |
| host_name | box |
我正在使用一对param / value。 param不会改变,但只有价值可以改变。 我有不同类型的值(IP地址,文本,数字),我需要在更改之前验证。 因此控制器使用多步保存数据来验证不同类型的值。
我创建了一个Form(用于测试)来更新host_name(alphaNumeric Validation)和dhcp_start_ip(ipv4 Validation)。
对于验证我使用了这个: http://book.cakephp.org/3.0/en/orm/validation.html#using-a-different-validation-set
验证工作正常但如果验证不匹配则不显示消息。如何在patchEntity时显示消息说主机名或IP地址格式错误? 也许我做错了...
这是观点:
<div class="config form large-10 medium-9 columns">
<fieldset>
<legend><?= __('DHCP Config')?></legend>
<?= $this->Form->create('config') ?>
<?php
//$params = array('host_name', 'host_ip', 'host_netmask', 'host_gateway', 'host_dns1', 'host_dns2');
echo $this->Form->input('host_name',[
'label' => __('Hostname : '),
'default' => $host_name->value
]);
echo $this->Form->input('dhcp_start_ip',[
'label' => __('DHCP Pool start : '),
'default' => $dhcp_start_ip->value
]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
控制器:
public function test()
{
$host_name = $this->Config->get('host_name', ['contain' => []]);
$dhcp_start_ip = $this->Config->get('dhcp_start_ip', ['contain' => []]);
if ($this->request->is(['patch', 'post', 'put'])) {
$confdata = array(
'param' => 'dhcp_start_ip',
'value' => $this->request->data['dhcp_start_ip']
);
$host_name_data = array(
'param' => 'host_name',
'value' => $this->request->data['host_name']
);
// 1ere methode de validation
$dataconfig = $this->Config->patchEntity($dhcp_start_ip, $confdata, [
'validate' => 'ipaddr',
]);
$this->Config->save($dataconfig);
$dataconfig = $this->Config->patchEntity($host_name, $host_name_data, [
'validate' => 'name',
]);
$this->Config->save($dataconfig);
}
$this->set('dhcp_start_ip', $dhcp_start_ip);
$this->set('host_name', $host_name);
}
型号:
public function validationIpaddr(Validator $validator)
{
$validator->notEmpty('value')
->add('value', 'notEmpty', [
'rule' => ['ip', 'ipv4'],
'message' => __('Invalid IP Address')
]);
return $validator;
}
public function validationName(Validator $validator)
{
$validator
->add('value', 'notEmpty', [
'rule' => ['alphaNumeric'],
'message' => __('Invalid Name')
]);
return $validator;
}
答案 0 :(得分:0)
试试这个,在你的控制器中
$dataconfig = $this->Config->patchEntity($dhcp_start_ip, $confdata, [
'validate' => 'ipaddr',
]);
if (!$dataconfig->errors()) {
$this->Config->save($dataconfig);
}else{
debug($dataconfig->errors());
$this->Flash->error('Invalid IP Address!');
}