Cake PHP - Form Validiation doesn't work - php

my CakePHP (1.2.5.) doesn't validate my form correct.
$this->UserData->save($this->data);
gives me always a true value back. I can't find the problem. The label for UserData.nichname works.
That's the View:
<?php
echo $form->create('UserData');
echo $form->error('UserData.nick_name');
echo $form->input('UserData.nick_name', array('id' => 'UserDatanick_name', 'rule' => 'alphaNumeric', 'label' =>'Nickname:', 'error' =>'false'));
echo $form->end( array( 'label' => ' Save ') );
?>
Here is my Controller:
class UserDatasController extends AppController {
var $name = 'UserDatas';
function add(){
if (!empty ($this->data)){
$this->UserData->create();
if ($this->UserData->save($this->data)){
$this->Session->setFlash('input is valid');
} else {
$this->Session->setFlash('input is not valid');
}
}
}
}
The rules for are not in the model, that's the reaseon i don't post it.
What else is necessary for a validation?
Thanks in advance
Steve

The validation rules have to be defined in the model, not in the view, see also the chapter about data validation in the cakebook.

^^ also check what your files are called.
you have named your model file user_data.php right? and your controller user_data_controller.php?
Note the underscores because of your CamelCasing. If you get the model file name wrong, it wont complain but will instead use a default magic model - which could be why your validation rules within the model didnt get picked up.

I believe you only specify the rules in the model, but the label would be kept in the $form->input() function

Related

How to solve Argument 1 passed to CodeIgniter\Validation\Validation::run() must be of the type array or null, object given?

I'm facing a problem while working on file validation in Codeigniter 4. Codes are given below.
Codes in the validation file are:
public $image = [
'image_path' => [
'label' => 'Image',
'rules' => 'uploaded[image_path]|is_image[image_path]|max_size[image_path, 1024]|mime_in[image_path,image/jpg,image/jpeg,image/png]'
]
];
And, codes in the controller are:
if($image->isValid() && !$image->hasMoved()):
if(!$this->validation->run($image, "image")):
$this->session->setFlashdata('image_errors', $this->validation->getErrors() ?? "");
return redirect()->back()->withInput();
endif;
endif;
But whenever I'm trying to run these code, the following error happened:
Argument 1 passed to CodeIgniter\Validation\Validation::run() must be of the type array or null, object given.
Please suggest me possible solution for this.
Thank you.
When we need to validate form in the controller we follow this steps:
use validate() method instead of using $validation property
see Controller Validate Data
set flashdata within recirect()->with() method
see Common functions
if condition syntax should be with brackets { }, use if else endif in view files only (optional).
see Alternate Syntax
It's very important and recommended to read User Guide
if ($image->isValid() && ! $image->hasMoved())
{
if (! $this->validate('image'))
{
return redirect()->back()->withInput()->with('image_errors', $this->validator->getErrors())
}
}
if you want to use validation class just do this
if ($image->isValid() && ! $image->hasMoved())
{
$this->validation->setRuleGroup('image');
if (! $this->validation->withRequest($this->request)->run())
{
return redirect()->back()->withInput()->with('image_errors', $this->validation->getErrors())
}
}
I hope it will work fine with your code.

"Undefined property" error when using CodeIgniter db and active record

I'm trying to insert demo records from some simple form using active records and codeigniter
function create_httpPost()
{
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content')
);
$this->newsModel->createData($data); //error occures here
$this->index();//aka redirectToAction
}
but after posting form I'm getting following error
**Message: Undefined property: News::$newsModel
Filename: controllers/news.php Line Number: 29**
Inside model I have this method
function createData($data)
{
$this->db->insert('News', $data);
return;
}
what I'm doing wrong here?
According to the CodeIgniter documentation, model class names must begin by an upper case letter with the rest of the name being lower case.
See: http://ellislab.com/codeigniter/user-guide/general/models.html
In the section titled Anatomy of a Model:
Class names must have the first letter capitalized with the rest of the name lowercase...
The file name will be a lower case version of your class name.
In your case, newsModel violates the rule, and the CodeIgniter name parser is probably not finding the class (or the relevant .php file), which is why it thinks newsModel is a property (that does not exist).
Try this:
function create_httpPost()
{
$this->load->model('newsModel'); // you need to load model
$this->newsModel->createData(array(
'title' => $this->input->post('title', TRUE),
'content' => $this->input->post('content', TRUE)
));
$this->index();
}
This is very comman problem with CI2.
this function must be inside one of ur models right ?
if so, please note that u can't reference model from inside other model ! for some reason. u need to let controller handle that

Changing error 'cannot be blank' in Yii

Regarding handling error message in Yii: Commonly, Yii has configured form's validation, and when one of the required field isn't filled, then the error message will be shown as
"Blablabla cannot be blank."
How can I customize that error message? For example, I'd like to change into this:
"Blablabla tidak boleh kosong."
Its not clear what you are trying to do exactly, but
assuming you want to make a completely other message use :
public function rules()
{
return array(
array('title, content', 'required',
'message'=>'Please enter a value for {attribute}.'),
// ... other rules
);
}
if you, on the other hand, are looking for translations, the best way to do it is by setting your language in the config
'language'=>'de',
'components'=>array(
'coreMessages'=>array(
'basePath'=>null,
),
......
),
if your language is not defined, copy framework/messages/en/yii.php to protected/messages/{yourlanguage}/yii.php and start translating, even if you wonna add messages, put the them in protected/messages/{yourlanguage}/ and never translate them in the framwork, so you can update without a fuss.
I hope this is what you look for:
url: Yii docs
class Post extends CActiveRecord
{
public function rules()
{
return array(
array('title, content', 'required',
'message'=>'Please enter a value for {attribute}.'),
// ... other rules
);
}
}

CakePHP: Access Model in other Model / in app_model.php for Validation of Banknumber

I am wondering how I could use data from a Model B while I am validating Model A, here to check if an entered Banknumber is a correct one:
My Users specify their bankaccount during the registration. E.g. the "banknumber". I am validating this the normal way in my user.php model
var $validate = array(
'banknumber' => array(
'minLength' => array(
'rule' => array('minLength', 8),
'message' => '...',
'required' => true,
),
Now I want to know if the entered Banknumber is a real one, so I got a table "Banks" in my DB with all real Banknumbers, and I am using some own validation functions which I specify in app_model.php.
function checkBankExists($data) {
if (!$this->Bank->findByBanknumber($data)) {
return false;
} else {
return true;
}
}
But this is never working, because while I am validating the User-Model, I can only use this one in an app_model - function, accessing it with $this->name or so... a $this->Bank is NOT possible, I get:
Undefined property: User::$Bank [APP\app_model.php
Call to a member function findByBanknumber() on a non-object
Is there ANY way to import/access other models in a function in app_model.php?
Thank you!
ClassRegistry should generally be used instead of AppImport as AppImport only loads the file, rather than registering it properly, cake style.
Using the example above.
$bnk = ClassRegistry::init('Bank');
$bnk->findByBanknumber($data);
you can import your model, create instance of it and use it as you like:
App::import('model','Bank');
$bnk = new Bank();
$bnk->findByBanknumber($data);

CodeIgniter - Variable scope

I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.

Categories