【问题标题】:Validate field in form - check if "product" exists in CakePhp 3验证表单中的字段 - 检查 CakePhp 3 中是否存在“产品”
【发布时间】:2016-03-22 12:12:36
【问题描述】:

我遇到了字段验证问题。

我想通过模型验证表单。我想检查是否存在具有某些值的字段。

我想阻止多次使用某些标题。

例如

如果数据库中存在标题为“Main”的字段“Site”,则无法验证表单。

如果不存在,可以通过。

我希望允许用户只添加一个标题为“Main”的“Site”,但他可以在任何情况下添加任何其他标题的“Site”。

你知道如何解决它吗?

【问题讨论】:

  • 如果您告诉我们您的表结构和要验证的字段,会容易得多。

标签: php validation cakephp


【解决方案1】:

我认为你有两个选择。

(1) 向服务器设置 Ajax 请求。

这样做:

  • 在名为 checkName() 的 SiteController 中创建一个响应 Ajax 请求的函数

    public function checkName($name) {
        // allow ajax requests 
        $this->request->allowMethod(['ajax']);
        // perform your check within the db
        $isExistent = [...]; 
        // prepare the response
        $response = ['name' => $name, 'isExistent' => $isExistent]; 
    
        if ($this->request->isAjax()){
            $this->autoRender = false;
            $this->response->disableCache();
            $this->response->type(['json' => 'application/json']);
            $this->response->body(json_encode($response));
        }
    }
    
  • 使用'_ext' => 'json'选项将路由添加到您的路由文件中

  • 准备调用已定义路由的 Javascript Ajax 函数并将其附加到输入字段的 onchange 属性上。 (有关简单示例,请参阅此链接:http://www.w3schools.com/jquery/ajax_ajax.asp

(2) 使 Site 表的“名称”字段唯一。

为此,您可以将以下函数添加到您的 SiteTable 类中

public function buildRules(
    RulesChecker $rules
) {
    $rules->add($rules->isUnique(['name']));
    return $rules;
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多