cakePHP form custom validation - validation

Hi all I'm creating an invoice system and trying to make sure that the person sending the request, is sending it to a person who exists. The code that I currently have isn't working and was wondering if someone could give me a hand.
model
'exists'=>array(
'rule'=>'partytwo',
'message'=>'That username doesnt exist.'
));
function userExists($field=array(), $compare_field=null )
{
if($field['exists']= $compare_field)
return TRUE;
else return FALSE;
}
and the validation in relationship the controller
if($this->request->is('post')){
if($this->Relationship->validates(array('fieldlist'=>array('partywo','Relationship.userExists')))){
$this->Relationship->create();
if ($this->Relationship->save($this->request->data))
{
$id=$this->Relationship->id;
$this->Session->setFlash('The relationship has been saved');
}}
else { $this->Session->setFlash('The relationship could not be saved. Please, try again.'); }
}
here is my current model
<?php
class Relationship extends AppModel{
var $name='Relationship';
public $useTable = 'relationships_users';
public $primaryKey = 'id';
var $validate = array(
'date' => array(
'rule' => array('datevalidation', 'systemDate' ),
'message' => 'Current Date and System Date is mismatched'),
'partytwo'=>array(
'partytwoExists'=>array(
'rule'=> 'userExists',
'message'=>'That username doesnt exist.'
)));
function datevalidation( $field=array(), $compare_field=null )
{
if ($field['date'] > $compare_field)
return TRUE;
else return FALSE;
}
function userExists($check)
{
$userExists= $this->find('count', array('conditions'=>$check));
if($userExists == 1)
{return TRUE;
}
else
return FALSE;
}
}
its currently going straight to errors

Have you read the book on validation?
// MODEL
var $validation = array(
'field_name' => array(
'rule' => array( 'customFunction', param ),
'message' => 'Message here'
)
);
function customFunction($field=array(), $compare_field=null )
{
if($field['exists'] == $compare_field)
return TRUE;
else return FALSE;
}
And for controller:
// CONTROLLER
if($this->request->is('post')){
$this->Relationship->set( $this->request->data );
if($this->Relationship->validates(array('fieldlist'=>array('partywo','Relationship.userExists')))){
$this->Relationship->create();
if ($this->Relationship->save($this->request->data))
{
$id=$this->Relationship->id;
$this->Session->setFlash('The relationship has been saved');
}
} else {
$this->Session->setFlash('The relationship could not be saved. Please, try again.');
}
}
It is something along those lines, try that.

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Post method in REST API using codeigniter

when i use following method and pass body key as fail (non defined key) and some value getting pass message in return and empty row gets inserted in table, How do I validate?
Function that I use in REST API,
function categories_POST() {
$title = $this->post('title');
$no = $this->post('no');
$id= $this->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
}
My model,
function addDetails($x, $y, $z) {
$check = "INSERT INTO categories (title,no,id) VALUES ('$x','$y','$z')";
$query = $this->db->query($check);
if($this->db->affected_rows() > 0) {
return "pass";
} else {
return "fail";
}
}
quite honestly, you'd be better off using the query builder and (depending on what style you follow(fat/skinny controllers/models)) letting the model deal with $this->post() for processing.
Is this Phil Sturgeons/Chris A's rest server?
Something like:
function categories_post() { // doesn't need to be POST()
$this->load->model('model_check');
$msg = $this->model_check->addDetails()
if ($msg)
{
$this->response([
'status' => TRUE,
'message' => 'pass'
], REST_Controller::OK);
}
// default to fail
$this->response([
'status' => FALSE,
'message' => 'fail'
], REST_Controller::HTTP_BAD_REQUEST);
}
Your model,
function addDetails() {
// this only checks to see if they exist
if (!$this->post() || !$this->post('x') || !$this->post('y') || !$this->post('z')) {
return false;
};
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
return false; // defaults to false should the db be down
}
IF you mean form_validation you can use this instead of the above.
function addDetails() {
$this->load->library('form_validation');
$this->form_validation->set_rules('x', 'X', 'required');
$this->form_validation->set_rules('y', 'Y', 'required');
$this->form_validation->set_rules('z', 'Z', 'required');
if ($this->form_validation->run() == true)
{
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
}
return false; // defaults to false should the db be down
}
This is quite verbose, there's shorter ways to do it, but I'd rather make it easy to figure out.
Two ways of get post values in CodeIgniter
$title = $this->input->post('title');
$no = $this->input->post('no');
$id= $this->input->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
or
extract($_POST);
Then direct access post name
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
Best way is directly access post values in model files (not in controller)
Don't need the pass the POST values in model function.
If you have more queries, then ask to me

Restriction for not allowing same email and password in the database for my signup form

i want to make a restriction in my signup form which the user cant signup with the already exists email and password..
in my controller:
i already make a rules or callback
array(
'field' => 'txt_email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_check_if_valid_email|trim',
),
check_if_valid:
public function check_if_valid_email()
{
$where = array('email' =>$this->input->post('txt_email'),'password' =>$this->input->post('txt_password'));
$this->load->model('database_model');
if ($user = $this->database_model->validate_user('user', $where))
{
foreach ($user as $row) {
$checkemail = $row->email;
$checkpassword = $row->password;
}
if ($checkemail == $this->input->post('txt_email')){
$this->form_validation->set_message('check_if_valid_email', 'Email already existed!');
return false;
}
else
{
if ($checkpassword = $this->input->post('txt_password'))
{
$this->form_validation->set_message('check_if_valid_email', 'Email already exists!');
return false;
}
else
{
return true;
}
}
}
}
in my model:
public function validate_user($table, $where)
{
$this->db->where($where);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
CodeIgniter's Form Validation library comes with the rule you're looking for, called: is_unique
http://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
Your validation rules will look like this;
required|valid_email|is_unique[users.email]|trim
All you have to set it the table and column you want to be unique (users.email).
Hope this helps.

Codeigniter - Trying to count articles view

Im working with codeigniter and have a controller and 3 model functions to read, insert and update a column of table.
i want to get count of view from db and update it per each view!
but after the update an extra row added to table! with zero value for content_id.
please check once!
this is my controller:
public function daily_report($id="")
{
$counter=$this->home_model->counter($id);
if($counter)
{
$view=$this->home_model->counter($id)->row()->view;
$views=$view+1;
$this->home_model->update_counter($views,$id);
}
else{
$views=1;
$this->home_model->set_counter($views,$id);
}
}
This is the model functions:
public function counter($id)
{
$code=$id;
$lang=$this->session->userdata('lang');
$data = $this->db
->select('view')
->from('tbl_views')
->where("content_id",$code)
->where("language",$lang)
->get();
if ($data->num_rows() > 0) {
return $data;
}else{
return false;
}
}
public function set_counter($views,$id)
{
$data = array(
'content_id' => $id ,
'view' => $views,
'language'=>$this->session->userdata('lang')
);
$this->db->insert('tbl_views', $data);
}
public function update_counter($views,$id)
{
$data = array(
'view' => $views,
);
$this->db->where('content_id', $id);
$this->db->update('tbl_views', $data);
}

cakephp validation response returning data to controller

Hi i have made a custom validation in the model. How can i access the result($visitor) from this in the controller?
model:
<?php
class Visitors extends AppModel
{
var $name = 'Visitors';
var $validate = array(
'xxx' => array(
'rule' => array('checkxxx'),
'message' => 'yyy.'
)
);
function checkIxxx($check){
$visitor = $this->find('first', array('conditions' => $check));
return $visitor;
}
}
?>
in my controller i want this:
function start() {
$this->Visitors->set($this->data);
if($this->Visitors->validates())
{
if($this->Visitors->xxx->type == 'value') //this is a value from the $visitor array in the model**
{
//do something
}
}
is this possible?
Updated to be a relevant answer, apologies.
//Model
var myField = 'invalid';
function myValidation($var){
if($var === true){
// Passed your validation test
$this->myField = 'valid';
}else{
$this->myField = 'invalid';
}
}
// Controller
$this->Model->set($this->data);
$this->Model->validates($this->data);
if($this->Model->myfield == 'valid'){
// Field has passed validation
}
You will want to use
$this->Model->invalidFields()
PS: You dont follow cake conventions
the model should be "Visitor" (singular)

Resources