issue validation startdate and enddate codeigniter - php

i want to validate startdate and endate codeigniter, if stardate > enddate, not saving in my database, or show error message
my controller like this
function buat_lagi() {
if ($this->input->post('IDKategori')) {
$this->MKalender->addEvents();
$id = $_POST[IDKategori];
$this->session->set_flashdata('message', 'Agenda Pimpinan baru telah dibuat !');
redirect('admin/kalenderkategori/lihat/' . $id . '', 'refresh');
} else {
$data['title'] = "Tambah Agenda Pimpinan";
$data['kategori'] = $this->MKalenderKategori->getKategoriDropDown();
$data['main'] = 'admin/kalender/kalender_buat_lagi';
$this->load->vars($data);
$this->load->view('layout/dashboard');
}
}
my model like this
function addEvents() {
$data = array(
'IDKategori' => $this->input->post('IDKategori'),
'TanggalMulai' => $this->input->post('TanggalMulai'),
'TanggalAkhir' => $this->input->post('TanggalAkhir'),
'judul' => $this->input->post('judul'),
'konten' => $this->input->post('konten'),
'create_by' => $_SESSION['username'],
);
$this->db->insert('kalender', $data);
}
my form like this
<form action="<?= base_url(); ?>index.php/admin/kalender/buat_lagi/" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<label for='ptitle'>Kegiatan / Lokasi :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);
echo "<p><label for='long'>Uraian Kegiatan / Keterangan / Catatan :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Mulai :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Akhir :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2', 'onblur' => 'function compareDate()');
echo form_input($data) . "</p>";
echo form_hidden('IDKategori', $this->uri->segment(4));
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate my issue ??

You haven't given the format of your dates or even which the date fields are (keep in mind most of the users here speak primarily English) You also haven't stated if you want this check server side or client side. By the compare dates function called in your form I am assuming you want it at least client side, I would suggest though that form validation needs to be done server side as well. Client side is great for immediate notification to the user but it's useless for actually protecting input to the form server side.
jQuery for the client side (since I am not sure which field is which this is pseudo code:
function compareDate()
{
var startDate = Date.parse($("#startDate).val()");
var endDate = Date.parse($("#endDate).val()");
if(startDate>endDate)
{
alert("Your start date must be earlier than your end date.");
}
}
Codeigniter function (the callback should work but I haven't tested it.) You really only have to run the function on one of the date fields, you only want to return one error and it's irrelevant which you return it on since it's comparing the two.
//validation rule
$this->form_validtion->set_rules('endDate', 'End Date','trim|callback_compareDates');
function compareDates()
{
$start = strtotime($this->input->post('startDate'));
$end = strtotime($this->input->post('endDate'));
if($start > $end)
{
$this->form_validation->set_message('compareDates','Your start date must be earlier than your end date');
return false;
}

Related

Codeigniter : how to update mulitiple record where id

I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.
my view :
<?php echo form_open('stock/updating_stock');?>
<div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
<?php foreach($critical_plus_warning as $data){?>
<input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
<h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<?php }?>
</div>
<div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
<?php echo form_close();?>
and my controller :
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data);
}
and my models :
function update_stok($data){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}
You need a where clause:
$this->db->where('id', $id);
...I think.
Try this:
Controller
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data,$id);
}
Model:
function update_stok($data,$id){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}
I think in your example update_batch will generate incorrect query beacues you need to update each record in db instead of updating them together - update_batch replaces values in multiple rows which fulfills conditions so there is possibility to update also incorrect rows (check example in documentation). So better idea is to update each single product using it's ID. It could look like that:
Model
function update_stok($data, $id_product){
$this->db->where('id_product', $id_product);
return $this->db->update($this->table, $data);
}
Controller
function updating_stock(){
$ids = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
foreach($ids as $key => $id_product) {
$data = array(
'stok' => $stok[$key],
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
);
$this->stok_adm->update_stok($data, $id_product);
}
}
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch

Insert session userdata into a new database in CodeIgniter

How would I go about inserting the session userdate id into my new table using the form I have in my view so that I may use the id as a foreign key?
Controller:
function validate_credentials() {
$this->load->model('member_model');
$query = $this->member_model->validate();
if ($query) { // if user credentials validate the user session start
$data = array(
'username' => $query->username,
'id' => $query->id,
'first_name'=>$query->first_name,
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('members/members_area');
} else {
$this->index();
echo 'Incorrect Password or Username';
}
}
View:
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Try this :
echo form_open('banks/create_bank');
echo form_input('bank_name', set_value('bank_name', 'Account Name'));
echo form_input('interest', set_value('interest', 'Interest'));
echo form_input('start_amount', set_value('start_amount', 'Starting Balance'));
echo form_input('length', set_value('length', 'Length'));
**echo form_input('id', set_value('id', $this->session->userdata('id'));**
echo form_submit('submit', 'Create Account')
echo validation_errors('<p class="error"/>');
Note : where 'id' in first parameter of form_input function can be replace by any name you want to pass when form will be submit.
In the method used in the controller banks where you handle the posted data from the from.
add something like this:
$data = array('bank_name' => $this->input->post('bank_name'), // add more post data
'id' => $this->session->userdata('id') ); //this will take the
//value 'id' from session
and pass it to your respective model.

How to load a view + form in a modal window in Yii

In Yii I have 2 models --> schedule and dossiers
What I want to achieve: In model schedule a view that shows a list of fiches. Each fiche has
a button that opens a modal window. The content of the modal window is a form to create a dossier + shows the 5 latest dossiers.
What I have so far:
viewSchedule.php
<?php $this->renderPartial('_fiches',array(
'schedule'=>$model,
'fiches'=>$fiches,
)); ?>
_fiches.php
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>"dialogFiche",
// additional javascript options for the dialog plugin
'options'=>array(
'title'=>'dossier',
'autoOpen'=>false,
'buttons' => array(
//array('text'=>'Route','click'=> 'js:function(){'.$target.'}'),
array('text'=>'Cancel','click'=> 'js:function(){$(this).dialog("close");}'),
),
'height'=>400,
'width'=>650,
'show'=>'fade',
'hide'=>'fade',
),
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
<?php foreach($fiches as $fiche): ?>
//fiche html ...
<div class="editDossier">
<?php
// the link that may open the dialog
echo CHtml::htmlButton("Edit dossier",
array(
'ajax'=>array(
'url' => CController::createUrl('dossier/getDossierById'), //only if you want an action here
'type' => 'get',
'data' => array(
'id' => $fiche['id'],
'isAjax' => 1,
),
"success" => "function(data){
$('#dialogFiche').html(data);
$('#dialogFiche').dialog('open');
return false;
}",
),
'class'=>'btn btn-primary btn-medium btn2',
),
array('id' => 'get-dossier-'.uniqid())
);
?>
</div>
<?php endforeach; ?>
dossierController.php
public function actionGetDossierById($id){
$dossiersById = dossier::model()->getDossiersById($id, 5);
$fiche = Fiche::model()->findByPk($id);
$dossier = $this->newDossier($fiche);
$myHtml = $this->renderPartial(
'viewDossierInModal',
array(
'dossiers'=>$dossiersById,
'dossier'=>$dossier,
),
true
);
echo $myHtml;
Yii::app()->end();
return;
}
protected function newDossier($fiche)
{
$dossier = new Dossier;
if(isset($_POST['Dossier']))
{
$dossier->attributes = $_POST['Dossier'];
$dossier->fiche_Id = $fiche->id;
if($dossier->save())
{
echo 'succes';
}else{
echo 'failed';
}
}
return $dossier;
}
dossierModal.php
public function getDossiersById($id, $limit = null){
$crit = new CDbCriteria();
$crit->condition = "fiche_Id = :ficheId";
$crit->params = array("ficheId"=>$ficheid);
if(isset($limit)){
$crit->limit = $limit;
}
$crit->order = "datum DESC";
return $this->findAll($crit);
}
After I create a dossier in the modal, the page does a redirect and shows the form and latest 5 dossiers on a new blank page. How can I return to my viewSchedule.php and maybe open the modal window with the content updated?
Or is there another, easier or maybe already in Yii, solution?
i hope i can help you,
The code that is making you the redirection is in the
actionGetDossierById
$myHtml = $this->renderPartial(
'viewDossierInModal',
array(
'dossiers'=>$dossiersById,
'dossier'=>$dossier,
),
true
);
if you remove or modify your $myHtml you will be able to handle redirection.
Also check your newDossier() function i think you miss an "s" in success so your ajax is not getting a success but a succes...
Regards

CakePHP: FormHelper not showing default values from associated model

We have two models which are related by a has and belongs to many (HABTM) relationship: Jobs, Tests. We are able to add/edit the relationships successfully (we know because they show up in the join table), but we can't get the existing values to appear in the view. The select/checkboxes (we've tried both) are always empty.
Here are the model relationships:
//Job.php
public $hasAndBelongsToMany = array (
'Test' => array (
'classname' => 'Test',
'foreignKey'=>'job_id',
'joinTable' => 'jobs_tests',
'associatedForeignKey' => 'test_id'
)
);
//Test.php
public $hasAndBelongsToMany = array(
'Job' => array(
'className'=> 'Job',
'joinTable'=>'jobs_tests',
'foreignKey' => 'test_id',
'associatedForeignKey'=> 'job_id'
)
);
Here is the /view/Jobs/edit.ctp
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
//This is always empty (nothing selected/checked).
What are we doing wrong?
Update:
Here is the JobsController action:
public function admin_edit( $id=NULL ) {
$this->layout = 'admin';
if (!$id)
$this->redirect( array('controller'=>'jobs', 'action'=>'index'));
$this->loadModel('Company');
$companies = $this->Company->find('all');
$company_options = array();
foreach ($companies as $company) {
$company_options[ $company['Company']['id'] ] = $company['Company']['name'];
}
$this->set('company_options', $company_options);
$this->loadModel('Test');
$tests = $this->Test->find('all');
$tests_options = array();
foreach ($tests as $test) {
$test_options[ $test['Test']['id'] ] = $test['Test']['name'];
}
$this->set('test_options', $test_options);
$category_options = $this->Job->validCategories;
$this->set('category_options', $category_options);
if ($this->request->isPut() ) {
$data = $this->request->data;
//debug($data);exit;
$save = $this->Job->save( $data );
if ($save) {
$this->Session->setFlash('Job edited');
//$job = $this->Job->findById( $id );
} else {
$this->Session->setFlash('Error editting job');
}
}
$job = $this->Job->findById($id);
$this->request->data = $job;
$this->set('job', $job);
}
Here is the form in the admin_edit.ctp view:
<?php echo $this->Form->create('Job'); ?>
<fieldset>
<?php
echo $this->Form->input('id', array('type'=>'hidden'));
echo $this->Form->input('name', array('class'=>'form-control'));
echo $this->Form->input('email', array('class'=>'form-control'));
echo $this->Form->input('location', array('class'=>'form-control'));
echo '<label>Type</label>';
echo $this->Form->select('type', array('FT'=>'Full Time', 'PT'=>'Part Time', 'IN'=>'Internship'), array('empty'=>false, 'class'=>'form-control'));
echo '<label>Company</label>';
echo $this->Form->select('company_id', $company_options, array('class'=>'form-control'));
echo $this->Form->input('short_description', array('label' => 'Short Description', 'class'=>'form-control'));
echo $this->Form->input('full_description', array('type'=>'textarea', 'label' => 'Full Description', 'class'=>'form-control'));
echo $this->Form->input('is_private', array('label'=>'Is Private?', 'class'=>'form-control') );
echo '<label>Category</label>';
echo $this->Form->select('category', $category_options, array('class'=>'form-control'));
echo '<label>Tests</label>';
//echo $this->Form->select('Test.id', $test_options, array('class'=>'form-control', 'multiple'=>true));
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]=$test['id'];
//$selected[ $test['id'] ] = $test['name'];
}
debug($selected);
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
PHEW! This was a stumper but the solution turned out to be simple... The values in $options['selected'] were strings (of numbers), which was confusing CakePHP. We converted them to ints using intval() and it works perfectly now, using all the original settings...
Here's the revised version of what is in the view (notice the intval()):
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]= intval($test['id']);
}
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
Also, as a sidenote, this is evidence that pretty much everything that was challenged in the comments above works completely fine:
$options['selected'] does not need to be key=>value pairs.
The pattern we're using does not overwrite the request->data and passes the data to the form helper just fine.
non-camelCased variable names passed to the view ($some_variable_name) are still picked up correctly by the form helper.
Hopefully this comes in handy to someone else.
What if you pass set the default values using Model::find('list').
//controller
$this->set('test_options', $this->YourModel->find('list'));
//view
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));

Fusion Chart with ajax in YII

I have use fusion chart extension in my Yii application. I am using an ajax submit to create various graphs. It renders, but when i try to filter it with ajax, i get the same output.
This is my code in the view:
<?php
$this->renderPartial('_search'); ?>
<p id="ChartArea" style="text-align:center;">
<?php
$this->renderPartial('_chart',array('cchart'=>'mychart',
'chartType'=>'Line','chartName'=>'callTrend','data'=>array('')));?>
In _search.php:
$form=$this->beginWidget('CActiveForm', array(
'id'=>'calltrend-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('onsubmit'=>"return false;"),
));
echo CHtml::hiddenField('chartType','Line');
echo CHtml::hiddenField('chartName','callTrend');
echo " ".CHtml::Label('From:','from_date',
array('style'=>'display:inline;clear:both;'))." ";
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'attribute'=>'from_date',
'name'=>'from_date',
'htmlOptions'=>array('class'=>'input-small','style'=>'margin-top:9px;'),
'options'=>array(
'dateFormat' => 'yy-mm-dd',
'altField' => '#self_pointing_id',
'altFormat' => 'yy-mm-dd',
'changeYear'=>'true',
'changeMonth'=>'true',
),
));
echo " ".CHtml::Label('To:','to_date',array('style'=>'display:
inline;clear:both;'))." ";
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'attribute'=>'to_date',
'name'=>'to_date',
'htmlOptions'=>array('class'=>'input-small','style'=>'margin-top:9px;'),
'options'=>array(
'dateFormat' => 'yy-mm-dd',
'altField' => '#self_pointing_id',
'altFormat' => 'yy-mm-dd',
'changeYear'=>'true',
'changeMonth'=>'true',),
));
echo " ".CHtml::Label('Project:','project',array('style'=>'
display:inline;clear:both;'))." ";
echo CHtml::dropDownList('project','',CHtml::listData(Project::model()->findAll()
,'id','name'),array('empty' => '--- Choose---','class'=>'inputmedium','style'=>'
clear:both;margin-top:9px;'));
echo " ".CHtml::submitButton(Yii::t('app',
'Generate'),array('class'=>'btn btn-primary','style'=>'clear:both;'));
echo " ".CHtml::ajaxSubmitButton('Generate',
CHtml::normalizeUrl(array('site/chart')),
array(
'data'=>'js:jQuery(this).parents("form").serialize()+ "&request=added"',
'success'=>'function(data){
$("#ChartArea").html(data);
}'
),
array(
'id'=>'ajaxSubmitBtn',
'name'=>'ajaxSubmitBtn',
'class'=>'btn btn-primary'
));
$this->endWidget();
In the controller: actionChart() method:
public function actionChart()
{
if(Yii::app()->request->isAjaxRequest)
{
$chartName=$_POST["chartName"];
if($chartName=="callTrend")
{
$data = array('from_date'=>$_POST["from_date"],'to_date'
=>$_POST["to_date"],'project_id'=>$_POST["project"]);
$cchart="mychart";
}
elseif($chartName=="topProducts"){
$data = array('from_date'=>$_POST["from_date1"],'to_date'=>$_POST["to_date1"]);
$cchart="mychart1";
}
elseif($chartName=="topCallers"){
$data = array('project_id'=>$_POST["project1"]);
$cchart="mychart2";
}
$chartType=$_POST["chartType"];
}
else
{
$data=array();
$chartName="callTrend";
$cchart="mychart";
$chartType="Line";
}
$this->renderPartial('_chart',array('cchart'=>$cchart,'chartName' =>$chartName,
'chartType'=>$chartType,'data'=>$data));
}
In my controller: actionCallTrend method:
public function actionCallTrend($from_date=NULL,$to_date=NULL,$project_id=NULL)
{
echo Yii::trace(CVarDumper::dumpAsString($from_date),'vardump');
echo Yii::trace(CVarDumper::dumpAsString($to_date),'vardump');
Yii::app()->fusioncharts->setChartOptions( array( 'caption'=>'Last Week Call Trend',
'xAxisName'=>'Date', 'yAxisName'=>'Calls' ) );
$con="";
if($from_date!=NULL && $to_date==NULL)
{
$con="DATE(answer_ts) >= '$from_date'"; // date is database date column field
}elseif($to_date!=NULL && $from_date==NULL)
{
$con="DATE(answer_ts) <= '$to_date'";
}elseif($from_date!=NULL and $to_date!=NULL){
$con="DATE(answer_ts) >= '$from_date' and DATE(answer_ts) <= '$to_date'";
}
if(($from_date!=NULL or $to_date!=NULL) && $project_id!=NULL)
{
$con.=" and project_id = '$project_id'"; // date is database date column field
}
$stats=Creport::model()->findAll(array(
'select'=>'COUNT(id) as data_count, DATE(answer_ts) as unique_date, answer_ts',
'condition'=>$con,
'group'=>'DATE(answer_ts)',
'order'=>'answer_ts desc',
'limit'=>10,
));
$ddg=Yii::app()->dateFormatter;
foreach ($stats as $s){
Yii::app()->fusioncharts->addSet(array('label'=>$ddg->format("dd",$s->answer_ts)."-"
.$ddg->format("MMM",$s->answer_ts), 'value'=>$s->data_count));
}
Yii::app()->fusioncharts->useI18N = true;
Yii::app()->fusioncharts->addTrendLine(array('startValue'=>'700000',
'color'=>'009933', 'displayvalue'=>'Target'));
Yii::app()->fusioncharts->addDefinition(array('name'=>'CanvasAnim',
'type'=>'animation', 'param'=>'_xScale', 'start'=>'0', 'duration'=>'1'));
Yii::app()->fusioncharts->addApplication(array('toObject'=>'Canvas',
'styles'=>'CanvasAnim'));
Yii::app()->fusioncharts->getXMLData();
}
This is my code. it works without ajax but when i filtering the fields using ajax the same output will be displayed, they will not get the from_date, to_date & project_id in the actionCallTrend controller.
to get access to variables in :
public function actionCallTrend($from_date=NULL,$to_date=NULL,$project_id=NULL)
you need to have those mapped in your url manager,
it is better to write:
public function actionCallTrend() {
$from_date = Yii::app()->request->getQuery('from_date ', null);
$to_date = Yii::app()->request->getQuery('to_date', null);
$project_id = Yii::app()->request->getQuery('project_id', null);
you could also use the Yii::app()->request->getParam() if you're unsure about POST or GET

Categories