Validation row with others rows in cakephp
i need validate "date range" to save with others "date ranges" values.
Something like this:
function dateNotColision($check) {
foreach($this->data[$this->name] as $row){
if(($row['date_start']>=$date_start && $date_start<=$row['date_end']) ||
($row['date_start']>=$date_end && $date_end<=$row['date_end']) ){
return false;
}
}
return true;
}
how i could?
public function customDateValidation($field) {
return ($this->data[$this->alias]['date_start'] >= $date_start && $this->data[$this->alias]['date_end'] <= $date_start) || ($this->data[$this->alias]['date_start'] >= $date_end && $this->data[$this->alias]['date_end'] <= $date_end)
}
in your validate array just set something like
'start_date' => array(
'rule' => 'customDateValidation',
'message' => 'wrong dates'
)
Finally i did this:
In Model:
public $validate = array(
'date_start' =>array('rule'=>'dateNotColision',
'message' => 'Date Colision'
),
'date_end' =>array('rule'=>'dateNotColision',
'message' => 'Date Colision'
)
);
var $dataArray=array();
public function setDataArray($array){
$this->dataArray=$array;
}
function dateNotColision($check) {
foreach($this->dataArray as $row){
if(($row['date_start']>=$check && $check<=$row['date_end'])){
return false;
}
}
return true;
}
In Controller:
$this->Hotel->Season->setDataArray($this->request->data['Season']);
foreach($this->request->data['Season'] as $reviewData){
$this->Hotel->Season->saveAssociated($reviewData);
}
Related
I have this variable called $projectFieldOptions and it's output is like this:
https://prnt.sc/7HtxrfTy9HiI.
Now, In the Controller I need to update this. What I am doing this, first delete all the existing rows based on id_feed and id_project and then loop through this variable $projectFieldOptions and insert it. Like this:
if( $request->feed_type !== 'scrape' ) {
$delete_mapping = DB::connection($db_name)->table($db_name . '.feed_mappings')
->where('id_feed', '=', $id_feed)
->where('id_project', '=', $token)
->delete();
}
// now insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->insert($data);
}
Now, I don't want to delete existing rows instead I want to update those rows based on the id_feed_mappings. Can you tell how can I do this?
Check if this would work, to update based on id_feed_mappings value, you can use the ->where('id_feed_mappings', '=' ,'a value or variable') before ->update($data)
if( $request->feed_type !== 'scrape' ) {
// try using update instead of insert
$field_mapping = true;
if( $request->feed_type !== 'scrape' ) {
if( count($projectFieldOptions) ) {
foreach ($projectFieldOptions as $mapping) {
$data[] = [
'id_feed' => $id_feed,
'id_project' => $token,
'import_field_slug' => $mapping['value'],
'internal_field_slug' => $mapping['custom'] ? $mapping['custom_field'] : $mapping['text'],
'custom_field' => $mapping['custom'],
'updates' => $mapping['updates'],
'removes' => $mapping['removes'],
'import' => 1,
'date_add' => now(),
'date_upd' => now()
];
}
} else {
$data = [];
}
$field_mapping = DB::connection($db_name)->table($db_name . ".feed_mappings")->update($data);
}
I have a form that accepts delivery of products which I noticed if I enter 0 in the quantity field it doesn't save in the database even if I add data in the calendar or in Notes field.
I already commented out the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,iin kernel.php still doesn't work.
how can I forced laravel to save my data even if I want to put 0 in quantity? thanks in advance!
update
public function store(Request $request)
{
$input = $request->all();
$items = [];
for ($i = 0; $i <= count($input['order_id']); $i++) {
if (empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
$acceptItem = [
'order_id' => $input['order_id'][$i],
'product_id' => $input['product_id'][$i],
'order_item_id' => $input['order_item_id'][$i],
'delivery_date' => $input['delivery_date'][$i],
'company_id' => $input['company_id'][$i],
// 'stock_in_qty' => intval($input['stock_in_qty'])[$i],
'stock_in_qty' => $input['stock_in_qty'][$i],
// 'stock_out_qty' => $input['stock_out_qty'][$i],
// 'transfer_to' => $input['transfer_to'][$i],
'delivery_note' => $input['delivery_note'][$i],
'user_id' => $input['user_id'][$i],
];
array_push($items, Warehouse1stocks::create($acceptItem));
$stockSummary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['stock_in_qty'][$i],
'qty_out' => null,
]);
if (!$stockSummary->wasRecentlyCreated) {
$stockSummary->increment('qty_in', $input['stock_in_qty'][$i]);
}
}
if ($input['rd'] == $input['stock_in_qty'] || $input['rd'] == 0) {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 4;
}
$setStatus->save();
} else {
$order_idAcceptedItem = $acceptItem['order_id'];
$setStatus = \App\Orders::where('id', '=', $order_idAcceptedItem)->first();
if ($setStatus) {
$setStatus->status_id = 3;
}
$setStatus->save();
}
return redirect()->route('orders.index');
}
empty() will return true with 0 or '0' which will mean that if you try to change the quantity to 0 the for loop will just continue on to the next loop. If you need to check if the value exists you can instead use isset().
Changing your first if statement to the following should be all you need:
if(!isset($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
public function insert_employee($fldCompanyStringID) {
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$data2 = array(
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert('tblUser', $data)&& $this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
The tblUser table auto generates a userID. I want to take that userID and store it into the tblWorkHistory table **
Here CodeIgniter transactions will help you.
https://www.codeigniter.com/user_guide/database/transactions.html
Please use this code --
<?php
public function insert_employee($fldCompanyStringID) {
$this->db->trans_start();
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
/* Insert User */
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$this->db->insert('tblUser', $data)
$insert_id = $this->db->insert_id();
/* Insert Work History */
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
$this->db->insert('tblWorkHistory', $data2)
/* Manage Transaction */
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->session->set_flashdata('error_msg', 'Failed, please try again');
}else{
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
?>
$this->db->insert_id() is used to get the last insert auto increment id data.
$this->db->insert('tblUser', $data);
$insert_id = $this->db->insert_id();
if($insert_id) {
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
} else {
$this->session->set_flashdata('error_msg', 'Something went wrong');
}
Hie guys i need help with my code I don't know how to do it. I have a form where a student selects an exam body, if the exam body selected is zimsec marks should be empty and if the exam body is cambridge marks should not be empty and should take a range depending on grade. validMarks is the function I am using to validate marks and it stopped working when i allowed marks to be empty so as to accomodate Zimsec.
My add.ctp
echo "<td>";
echo $this->Form->label('Mark(%): ');
echo "</td><td>";
echo $this->Form->input("ApplicantOlevelQualification.mark.$s",array('label'=>''));
echo "</td></tr>";
echo $this->Form->label('Exam Body<font color=red>*</font>');
$exambody=array(
'ZIMSEC'=>'ZIMSEC',
'CAMBRIDGE'=>'CAMBRIDGE'
);
echo $this->Form->select('exam_body_code',$exambody,array('empty'=>'Please Select','selected'=>false,'label'=>'Exam Body<font color="red">*</font>'));
My Controller
$exam_body_code = $this->data['ApplicantOlevelQualification']['exam_body_code'];
'mark' => $this->data['ApplicantOlevelQualification']['mark'][$i],
My model
'exam_body_code' => array(
'notempty' => array(
'rule' => array('notempty'),
),
),
'mark' => array(
//'numeric' => array(
//'rule' => array('numeric'),
'rule' => array('validMarks'),
'message' => 'Wrong mark for this grade, please try again.',
'allowEmpty' => true,
// ),
),
public function validMarks($check) {
$grade=($this->data['ApplicantOlevelQualification']['grade']);
$mark=($this->data['ApplicantOlevelQualification']['mark']);
//var_dump($mark);
if($grade== 'A' && $mark>74) {
// $this->validationError( 'grade', 'Grade A must be greater than or equal to 75%' );
//Access $this->data and $check to compare your marks and grade;
return true;
} elseif( ($grade)== 'B' && ($mark>64)) {
return true;
} elseif( ($grade)== 'C' && ($mark)>50) {
return true;
} elseif( ($grade)== 'D' && ($mark)>40) {
return true;
} elseif( ($grade)== 'E' && ($mark)>30) {
return true;
} elseif( ($grade)== 'U' && ($mark)>0) {
return true;
} else {
return false;
}
//Access $this->data and $check to compare your marks and grade..
}
if the exam body selected is zimsec marks should be empty and if the exam body is cambridge marks should not be empty and should take a range...
In that case you should split validation into 2 functions:
function emptyIfZimsec($data) {
return $this->data['ApplicantOlevelQualification']['exam_body_code'] != 'ZIMSEC'
|| empty($this->data['ApplicantOlevelQualification']['mark']);
}
function validMarks($data) {
if ($this->data['ApplicantOlevelQualification']['exam_body_code'] != 'CAMBRIDGE')
return true;
...
emptyIfZimsec will result in a validation error if the code is ZIMSEC and mark is not empty. and validMarks will check CAMBRIDGE marks (and skip if ZIMSEC)
This way you can also output separate validation error messages for each case.
Hope this helps.
Can someone please help me with this conditional field validation in CodeIgniter?
Trying to collect some customer data and if the user selects 'Yes' in the mail radio buttons, some of the fields such as (address, city, postcode etc) becomes mandatory.
I have the CodeIgniter form validation code in config/form_Validation.php as below:
$config = array ( 'customer/new_customer' => array
(
array ( 'field' => 'firstName', 'label' => 'First Name', 'rules' => 'required' ),
array ( 'field' => 'lastName', 'label' => 'Last Name', 'rules' => 'required'),
array ('field' => 'mail', 'label' => 'Mail', 'rules' => 'required' ),
array ('field' => 'address', 'label' => 'Address','rules' => ''),
//other fields here
)
);
I have the code below in the controller to add/edit customer:
function new_customer()
{
$customer_id = $this->input->post('customer_id');
if ($this->form_validation->run() == FALSE)
{
if(($customer_id != "X") && ($customer_id != "")){
$data['add_or_edit'] = "add";
return $this->edit_customer($customer_id, 'add');
}else {
$data['title'] = "New Customer";
$data['add_or_edit'] = 'add';
$this->load->view('customer_form_view',$data);
}
}else{
$data['firstName'] = $this->input->post('firstName');
$data['lastName'] = $this->input->post('lastName');
if($this->input->post('mail') == "Yes")
{
$data['address'] = $this->input->post('address');
$data['city'] = $this->input->post('city');
//other fields
}
if(($customer_id == 'X') || ($customer_id == ''))
{
//add new customer
$customer_id = $this->customers_model->insertCustomer($data);
redirect("/customer/customerList");
}else{
//edit the customer matching the customerID
$this->customers_model->editCustomer($customer_id, $data);
redirect("/customer/customerlist");
}
}//end validation if
}//end function
I am not sure how to make the address, postcode and other fields as 'required' if the user selects 'Yes' in the mail option.
It will be great if someone can help me with this.
Thanks a lot
Regards,
PS
You could use callback function, as your mail option validation rule... Something like
$this->form_validation->set_rules('mail', 'Mail', 'callback_mail_check');
Then in callback function, you could have something like
function mail_check($str)
{
if ($str == 'YES')
{
$this->form_validation->set_message('mail_check', 'You need to fill other fields.');
return FALSE;
}
else
{
return TRUE;
}
}