meotimdihia
meotimdihia

Reputation: 4299

cakePHP: how set error validation to input field manually in controller

I want set error validation to input field manually in controller example:

  if ($remainTime < 30) {
      ..... set error validation in here (error: limitTime ), ( error is not in model )
  }

other question: i want to ask : bindModel ( in this case , I use bindModel in Behaviors ) 'll cause loss of relationship with other model but is bindModel cause loss of $var validate,too ?

Upvotes: 9

Views: 21484

Answers (6)

Yaroslav
Yaroslav

Reputation: 2438

2019 update for CakePHP3 in YourController.php

// creane new
$entity = $this->YouTable->newEntity();

// or get existing from database
// $entity = $this->YouTable->get($id);

// invalidate fields
$entity->setErrors('your_field', 'error message');
$this->set('$entity', $entity);

and in action.ctp

// create form based on your entity
echo $this->Form->create($entity);
// and include your control
echo $this->Form->control('your_field');

if your form based on table, and for modelless forms first you need to create src/Form/YourForm.php with schema definition and then call setErrors() on YourForm instance from controller.

Upvotes: 0

mate.gvo
mate.gvo

Reputation: 1192

If you want to invalidate an associated model, you can use something like this:

$this->Model1->Model2->invalidate('Model2', __("Your validation message"));

In my case it invalidates associated select multiple (HABTM) field.

Upvotes: 1

skywalker
skywalker

Reputation: 826

Since a lot has passed since this has been answered in order to pass correct message you need to put it like this:

$this->Model->validationErrors['limitTime'] = array("time is less than 30");

Form is expecting array of error messages.

Upvotes: 0

drmonkeyninja
drmonkeyninja

Reputation: 8540

This can be achieved using the invalidate method that will flag the field as having an error:-

$this->Model->invalidate('field_name', 'error message');

Upvotes: 15

sharmil
sharmil

Reputation: 689

if the $validate is defined in the model, bindModel wont cause closs of $var validate.

As for you primary question; you can set/unset/update $validationErrors of the models..eg

($remainTime < 30) {
   $this->Model->validationErrors['limitTime'] = "time is less than 30";
}

Upvotes: 15

Nik Chankov
Nik Chankov

Reputation: 6047

Probably you are looking for something like this

Upvotes: 0

Related Questions