Cakephp: Validation of elements in an array - validation

I have a form where a student to enter subjects using a drop down list. The dropdown list takes subjects from a table. I want to validate this dropdown so that a subject is only selected once by the student. The subjects are being looped. How can i do this?
My controller
for ($i = 1; $i < sizeof($this->data['ApplicantOlevelQualification']['olevel_subject_code']); $i++) {
if ($this->data['ApplicantOlevelQualification']['olevel_subject_code'][$i] != "") {
$this->ApplicantOlevelQualification->create();
$this->ApplicantOlevelQualification->id = null;
$this->ApplicantOlevelQualification->set(array(
'applicants_detail_id' => $app_id,
'olevel_subject_code' => $this->data['ApplicantOlevelQualification']['olevel_subject_code'][$i],
'grade' => $this->data['ApplicantOlevelQualification']['grade'][$i],
'mark' => $this->data['ApplicantOlevelQualification']['mark'][$i],
'centre_number'=> $centre_number,
'candidate_number'=> $candidate_number,
'exam_body_code'=> $exam_body_code,
'year_written'=> $year_written,
)
);
My add.ctp
echo "<tr><td>" . $this->Form->label('Subject: ');
echo "</td><td>";
echo $this->Form->select("ApplicantOlevelQualification.olevel_subject_code.$s",$mySubjects);
echo "</td><td>";
Model
'olevel_subject_code' => array(
'numeric' => array(
'rule' => array('valids'),
),
),

This can be unique by adding GROUP BY on dropdown list
$subjects = $this->ApplicantOlevelQualification->OlevelSubject->find('list',array('fields'=>‌​array('code','name'),'group'=>array(code)));

Related

Disable items in dropdown which are previously selected using codeigniter

I have created a dropdown which contains Job Positions. I want to disable the dropdown item which user has previously applied. Here to reduce my code i have created options_selected static to get selected job profile lists.
Here $job_positions contains all job profiles and $options_selected contains all the items which he previously selected from job_positions. Now he can't select these options again these should be disabled.
$job_positions =array('0' => 'Select', '1' => 'IT Staff', '2' => 'Customer Care', '3' => 'Sales', '4' => 'Doctor');
$options_selected =array('1' => 'IT Staff','2' => 'Doctor');
$opt_array=array();
// extract the job position
for ($i=0; $i < count($job_positions); $i++) {
$disabled = '';
// extract the options_selected and compare with the job position and if match overwrite the variable disabled
for ($x=1; $x <= count($options_selected); $x++) {
if ($options_selected[$x]==$job_positions[$i]) {
$disabled = 'disabled';
}
}
$opt_array[]= '<option '.$disabled.' value="'.$job_positions[$i].'">'.$job_positions[$i].'</option>';
}
echo form_dropdown('category', $opt_array);
You can use the array_diff() function which compare the values of two arrays and returns the differences.
$job_positions =array('0' => 'Select', '1' => 'IT Staff', '2' => 'Customer Care', '3' => 'Sales', '4' => 'Doctor');
$options_selected =array('1' => 'IT Staff','2' => 'Doctor');
$position = array_diff($job_positions,$options_selected);
echo form_dropdown('category', $position);

Show Out Of Stock text in Magento

I need to add on my dropdown list an style into thee out of stock text, im already using this:
if (count($productsIndex) == 1) {
$stockItem = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($productsIndex[0]);
if ($stockItem->getQty() == 0) {
$value['text'] .= ' Out Of Stock';
}
}
$info['options'][] = array(
'id' => $value['value_index'],
'label' => $value['label'],
'price' => $configurablePrice,
'oldPrice' => $this->_prepareOldPrice($value['pricing_value'], $value['is_percent']),
'products' => $productsIndex,
);
But this will show
12 Out Of Stock
This will display next to the size, how can i give style to this ?

Laravel insert or update multiple rows

Im new in laravel, and im trying to update my navigation tree.
So i want to update my whole tree in one query without foreach.
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
);
I just want to ask - is there posibility in laravel to insert(if new in array) or update my current rows in database?
I want to update all, because i have fields _lft, _right, parent_id in my tree and im using some dragable js plugin to set my navigation structure - and now i want to save it.
I tried to use
Navigation::updateOrCreate(array(array('id' => '3'), array('id'=>'4')), array(array('name' => 'test11'), array('name' => 'test22')));
But it works just for single row, not multiple like i tried to do.
Maybe there is another way to do it?
It's now available in Laravel >= 8.x
The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of columns that should be updated if a matching record already exists in the database:
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
I wonder why this kind of feature is not yet available in Laravel core (till today). Check out this gist The result of the query string would look like this: here
I am putting the code here just in case the link breaks in the future, I am not the author:
/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
*
* insertOrUpdate([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*
* #param array $rows
*/
function insertOrUpdate(array $rows){
$table = \DB::getTablePrefix().with(new self)->getTable();
$first = reset($rows);
$columns = implode( ',',
array_map( function( $value ) { return "$value"; } , array_keys($first) )
);
$values = implode( ',', array_map( function( $row ) {
return '('.implode( ',',
array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row )
).')';
} , $rows )
);
$updates = implode( ',',
array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) )
);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";
return \DB::statement( $sql );
}
So you can safely have your arrays inserted or updated as:
insertOrUpdate(
array(
array('id'=>1, 'name'=>'some navigation point', 'parent'='0'),
array('id'=>2, 'name'=>'some navigation point', 'parent'='1'),
array('id'=>3, 'name'=>'some navigation point', 'parent'='1')
)
);
Just in case any trouble with the first line in the function you can simply add a table name as a second argument, then comment out the line i.e:
function insertOrUpdate(array $rows, $table){
.....
}
insertOrUpdate(myarrays,'MyTableName');
NB: Be careful though to sanitise your input! and remember the timestamp fields are not touched. you can do that by adding manually to each arrays in the main array.
I've created an UPSERT package for all databases: https://github.com/staudenmeir/laravel-upsert
DB::table('navigation')->upsert(
[
['id' => 1, 'name' => 'some navigation point', 'parent' => '0'],
['id' => 2, 'name' => 'some navigation point', 'parent' => '1'],
['id' => 3, 'name' => 'some navigation point', 'parent' => '1'],
],
'id'
);
Eloquent Style
public function meta(){ // in parent models.
return $this->hasMany('App\Models\DB_CHILD', 'fk_id','local_fk_id');
}
.
.
.
$parent= PARENT_DB::findOrFail($id);
$metaData= [];
foreach ($meta['meta'] as $metaKey => $metaValue) {
if ($parent->meta()->where([['meta_key', '=',$metaKey]] )->exists()) {
$parent->meta()->where([['meta_key', '=',$metaKey]])->update(['meta_value' => $metaValue]);
}else{
$metaData[] = [
'FK_ID'=>$fkId,
'meta_key'=>$metaKey,
'meta_value'=> $metaValue
];
}
}
$Member->meta()->insert($metaData);
No, you can't do this. You can insert() multiple rows at once and you can update() multiple rows using same where() condition, but if you want to use updateOrCreate(), you'll need to use foreach() loop.
I didn't find a way to bulk insert or update in one query. But I have managed with only 3 queries. I have one table name shipping_costs. Here I want to update the shipping cost against the shipping area. I have only 5 columns in this table id, area_id, cost, created_at, updated_at.
// first get ids from table
$exist_ids = DB::table('shipping_costs')->pluck('area_id')->toArray();
// get requested ids
$requested_ids = $request->get('area_ids');
// get updatable ids
$updatable_ids = array_values(array_intersect($exist_ids, $requested_ids));
// get insertable ids
$insertable_ids = array_values(array_diff($requested_ids, $exist_ids));
// prepare data for insert
$data = collect();
foreach ($insertable_ids as $id) {
$data->push([
'area_id' => $id,
'cost' => $request->get('cost'),
'created_at' => now(),
'updated_at' => now()
]);
}
DB::table('shipping_costs')->insert($data->toArray());
// prepare for update
DB::table('shipping_costs')
->whereIn('area_id', $updatable_ids)
->update([
'cost' => $request->get('cost'),
'updated_at' => now()
]);
in your controller
use DB;
public function arrDta(){
$up_or_create_data=array(
array('id'=>2, 'name'=>'test11'),
array('id'=>4, 'name'=>'test22')
);
var_dump($up_or_create_data);
echo "fjsdhg";
foreach ($up_or_create_data as $key => $value) {
echo "key ".$key;
echo "<br>";
echo " id: ".$up_or_create_data[$key]["id"];
echo "<br>";
echo " Name: ".$up_or_create_data[$key]["name"];
if (Navigation::where('id', '=',$up_or_create_data[$key]["id"])->exists()) {
DB::table('your_table_ name')->where('id',$up_or_create_data[$key]["id"])->update(['name' => $up_or_create_data[$key]["name"]]);
}else{
DB::insert('insert into your_table_name (id, name) values (?, ?)', [$up_or_create_data[$key]["id"], $up_or_create_data[$key]["name"]]);
}
}

limiting the input data on codeigniter

There is any function limiting the input data on codeigniter?
Example:
User input qty '3'.
Then, he took input for that 3 stuff. He can't input more than 3
i tried this so far. just for input that qty
public function ajax_add()
{
$this->_validate();
$data = array(
'nama_produk' => $this->input->post('nama_produk'),
'quantity' => $this->input->post('quantity'),
'tanggal' => $this->input->post('tanggal'),
);
$insert = $this->barangmasuk->save($data);
echo json_encode(array("status" => TRUE));
}

CodeIgniter conditional validation

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;
}
}

Resources