Using Model to validata data based on hours in cakephp - mysql

I am new to cakephp.Below the number being bold is the time the data is being created and code to validate .My problem is to validate the data should between 8 hours not more that using Model. is there any wrong in my code?
sample data=L02A-180129-1215-A
The code to find the table based on data
public function sa01() {
$trv_no = $this->data[$this->alias]['TRV_No_01'];
$line_no = intval(substr($trv_no, 1, 2));
$table_name = 'Ticket_L' . $line_no;
$this->Ticket->setSource($table_name);
$this->Ticket->recursive =-1;
code for validation
Batch_time is a column name for the table
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time))
{
$table_name = 'Ticket_L0';
$this->Ticket->setSource($table_name);
//$ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.TRV_No' => $trv_no)));
$time = $this->Ticket->find('all',array('conditions' => array('Ticket.Batch_Time >=' => date('Y-m-d H:i:s', strtotime('-8 hour')))));
if(empty($time)) { return false; } else { return true; }
}
else
{ return true; }
}

Related

How to retrive from other table and input it again into another table in laravel?

I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.

Make FileInput Optional for user in Yii2

I have a file Input field in my form which works good to upload the file. But I want to keep the provision for user that they might not upload any file at all.
My Code looks like below -
Model Rule -
[['jha'],'file','skipOnEmpty' => true,'extensions' => 'pdf'],
Form
<?= $form->field($model, 'jha')->fileInput(['accept' => 'application/pdf']); ?>
Controller -
public function actionCreatenewworkbasic()
{
$model = new Workpermit();
$model->wp_timeissued = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()))
{
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}else{
return $this->renderAjax('createnewworkbasic', [
'model' => $model,
]);
}
}
By this code, If I leave the upload field untouched, I get error -
Call to a member function saveAs() on null
Check empty before saveAs()
if ($model->load(Yii::$app->request->post())) {
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}

Cakephp 2.61 and comboboxes

Using Cakephp 2.6.1, I have successfully captured and stored single characters in my database using the following code
echo $this->Form->input('grade', array('options' => array( 'G' => 'Good', 'P' => 'Pass','R'=>'Practice Required','F'=>'Fail')));
What I would like to know is how to convert these values back to the display values when retrieving them from the database, ie if the database contains 'P', I want to display 'Pass' in the view and index pages.
I'm certain the answer is simple and straightforward, and sheepishly apologise in advance for my ignorance.
Step-1
Create two new files under Vendor folder.
master-arrays.php
common-functions.php
and Import this two files
Process of import :
Dir : app\Config\bootstrap.php
Add this two lines:
App::import('Vendor', 'common-functions');
App::import('Vendor', 'master-arrays');
Step-2
Now open 'master-arrays.php'
and add this array
function grade_type()
{
$GRADE_TYPE['G'] = 'Good';
$GRADE_TYPE['P'] = 'Pass';
return $GRADE_TYPE;
}
Step-3
Change your view -
echo $this->Form->input('grade', array('options' =>grade_type())));
Step-4
Now add this function in 'common-functions.php'
function id_to_text($id, $arr_master=array()) {
$txt_selected = "";
$id = ''.$id; //Added this as it was creating some warnings online for wrong parameter types
if(is_array($arr_master) && array_key_exists($id,$arr_master)) {
$txt_selected = $arr_master[$id];
} else {
$txt_selected = "";
}
return $txt_selected;
}
Step-5
In Controller or in view
Input:
id_to_text('P',grade_type());
Output:
Pass
Try this,
// In controller
function fun()
{
$grade = array(
'G' => 'Good',
'P' => 'Pass',
'R' => 'Practice Required',
'F' => 'Fail'
);
$this->set('grade', $grade);
if ($this->request->data) {
$key = $this->request->data['Model']['grade'];
$this->request->data['Model']['grade'] = $grade[$key];
$this->Model->save($this->request->data);
}
}
// in view
echo $this->Form->input('grade', array(
'options' => $grade
));
Updated Code
// add in Model
function afterFind($results) {
foreach ($results as $key => $val) {
if (isset($val['MyModel']['status'])) {
$results[$key]['MyModel']['grade_text'] = $this->getGradeText($results[$key]['MyModel']['grade']);
}
}
return $results;
}
public function getGradeText($key)
{
$grades = array(
'G' => 'Good',
'P' => 'Pass',
'R' => 'Practice Required',
'F' => 'Fail'
);
$txt_selected = "";
if(array_key_exists($key,$grades)) {
$txt_selected = $grades[$key];
} else {
$txt_selected = "";
}
return $txt_selected;
}
// in controller
public function index() {
$this->set('data' , $this->paginate('MyModel'));
}
// in view
foreach($data as $value) {
echo $value['MyModel']['grade_text'];
}
I hope it will be help you.

fat models and thin controllers in codeigniter

this is a user.php controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
this is model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
is this a good way of quering database?
i am new to mvc and i am reading everywhere about "fat models and this controllers"
what can be done to make it a good mvc architecture?
its only acceptable to echo out from the controller when you are developing:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
if checking login is false then either show a view or go to a new method like
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
the check login code in the controller is a great example of something that could be refactored to a model. then if you need to check login from another controller its much easier. putting the form validation code in a model would be another choice. often times when you are validating form code you are also inserting/updating to a database table -- so having all those details together in a model can make things easier long term.
"fat model" does not mean one method in a model that does a hundred things. it means the controller says -- did this customer form validate and insert to the database? yes or no? 3 lines of code.
the model has the code that is looking into the "fat" details of the form, validation, database, etc etc. say 50 or more lines compared to the 3 in the controller. but the methods in the model should still be clean: small and specific.

insert if not exists Codeigniter

my controller:
function getFeed()
{
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')
);
$this->load->model('membership_model');
$this->membership_model->feeds($feeds);
}
Model:
function feeds($feeds_data)
{
$this->db->insert_batch('feeds', $feeds_data);
}
Is there a function to insert if only the row doesn't exists in the table? I have a table with 4 column : id,title,url,username. I have an anchor when i click him it calls geFeed function and insert the info into table. But i want to insert only if not exists.
I had the same challenge, so i eventually come up with a function which might be helpful to you.
function safe_update_batch($table_name,$records,$filter_field)
{
$filters=array();
foreach($records as $record)$filters[]=$record[$filter_field];
$this->db->query("SET SESSION group_concat_max_len=10000000");
$query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);
$row=$query->row();
$found_fields=explode(',',$row->existing_keys);
$insert_batch=array();
$update_batch=array();
foreach($records as $record)
{
if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
else $insert_batch[]=$record;
}
if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);
}
//sample usage
$this->safe_update_batch('feeds', $feeds_data,'title');
You can try this in your model!!
function insertClient($array)
{
$this->db->from('MyTable');
$this->db->where('Id', $array['Id']);
$query = $this->db->get();
if($query->num_rows() != 0){
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->where('Id', $array['Id']);
$this->db->update('CLIENTS', $data);
}else{
$data = array(
'name'=>$array['name'],
'phone'=>$array['phone'],
'email'=>$array['email']
);
$this->db->insert('CLIENTS',$data);
}
}
In controller:
$this->site_model->insertClient($_POST);
Sadly if you are using the active record class an INSERT IF NOT EXISTS function doesn't exist. You could try
Extending the active record class (easier said than done)
You could set indexes on certain columns as UNIQUE so that MySQL will check to see if it already exists
You could do some kind of SELECT before your INSERT to determine if the record is already there
For the queries where you need to do INSERT IF NOT EXISTS do $this->db->query('INSERT IF NOT EXISTS...')
function getFeed()
{
// Load the model up here - otherwise you are loading it multiple times
$this->load->model('membership_model');
$feed_url = $this->input->get("url");
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
foreach($x->channel->item as $entry) {
// check if the feed is unique, if true then add to array
if( $this->membership_model->singleFeedIsUnique($entry) == TRUE ){
$feeds[] = array(
'title' => (string)$entry->title,
'url'=> (string)$entry->link,
'username' => $this->session->userdata('username')); }
} //foreach
// check to make sure we got any feeds with isset()
// if yes, then add them
if (isset($feeds)){ $this->membership_model->feeds($feeds); }
}
You can try this in your model and leave you controller without changes
function feeds($feeds_data)
{
$data = array(
title => $feeds_data[0],
url => $feeds_data[1],
username => $feeds_data[2]
);
$this->db->select('*');
$this->db->from('mytable');
$this->db->where('title',$feeds_data[0]);//you can use another field
if ($this->db->count_all_results() == 0) {
$query = $this->db->insert('mytable', $data);//insert data
} else {
$query = $this->db->update('mytable', $data, array('title'=>$feeds_data[0]));//update with the condition where title exist
}
}
you can check the id if you have it, adding in the data array and use it to check if exist