Lukas M.
Lukas M.

Reputation: 1

Validate field in form - check if "product" exists in CakePhp 3

I've got problem with field validation.

I would like to validate form through model. I want to check if field with some value exists.

I would like to block using some titles more than once.

For example

if field "Site" with title "Main" exists in database, you can't validate form.

If it doesn't exist, you can pass it.

I would like to allow user to add just one "Site" with title "Main", but he can add "Site" with any other title in any case.

Have you got some idea how to solve it?

Upvotes: 0

Views: 654

Answers (1)

valentinarho
valentinarho

Reputation: 121

I think you have two options.

(1) Setup an Ajax request to the server.

To do so:

  • Create a function, that responds to an Ajax request, in your SiteController named checkName()

    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));
        }
    }
    
  • Add the route to your routes file with the option '_ext' => 'json'

  • Prepare your Javascript Ajax function that call the route you have defined and attach it on the onchange attribute of your input field. (see this link for a simple example: http://www.w3schools.com/jquery/ajax_ajax.asp)

(2) Make the 'name' field of the Site table unique.

To do so you could add the following function to your SiteTable class

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

Upvotes: 1

Related Questions