Fusion Chart with ajax in YII - php

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

Related

Yii - incorrect returned date range using CJuiDatePicker

Good Afternoon
I have a date picker in my view which selects the start_date and end_date.
my problem is that i cannot get the correct data with the selected date ranges.
I have a sample image below to show you what i mean.
Sample data:
if i select start_date (2015-10-01) then end_date (2015-10-29),
it only returns this.
instead of this
I only get two dates which is the selected date from and selected date to.. the thing is it should return candidate 1, 2 and 3 because their dates is within the date range start_date (2015-10-01) until end_date (2015-10-29). what is wrong with my code. please help. can someone review my code.. maybe i miss something.
this is my view.
<form>
<div class="form-group"><label>Date From</label>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'name' => 'start_date',
'options'=>array(
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'class'=>'form-control',
'placeholder'=>'From',
'value' => $search_date_start,
),
));
?>
</div>
<div class="form-group"><label>To</label>
<div class="controls" style='margin-top: 5px;'>
<?php
$end_date = date('m-d-Y');
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'name' => 'end_date',
'options'=>array(
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'class'=>'form-control',
'placeholder'=>'To',
'value' => $search_date_end,
),
));
?>
</div>
</div>
</div>
<div class="form-group">
<input type="submit" name='search_btn' value="Search" class='btn btn-primary '>
<input type="submit" name='reset_btn' value="Reset" class='btn btn-default '>
</div>
</form>
in my controller, i have added this code.
if(isset($_POST['search_btn'])) {
if (isset($_POST['start_date']) && isset($_POST['end_date'])) {
$search_date_start = $_POST['start_date'];
$search_date_end = $_POST['end_date'];
Yii::app()->session['start_date_evaluation'] = $search_date_start;
Yii::app()->session['end_date_evaluation'] = $search_date_end;
}
if (isset($_POST['search'])) {
$search = $_POST['search'];
Yii::app()->session['search_evaluation'] = $search;
}
}
in my model i have this code.
public function search($candidate_id, $search_date_start, $search_date_end, $search) {
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('evaluation_form_id', $this->evaluation_form_id);
$criteria->addSearchCondition('evaluatee', $search);
$criteria->addSearchCondition('start_date', $search_date_start);
$criteria->addSearchCondition('end_date', $search_date_end);
if ($candidate_id !== '') {
$criteria->compare('employee_id', $candidate_id);
} else {
$criteria->compare('employee_id', $this->employee_id);
$criteria->compare('evaluation_code', $this->evaluation_code);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('end_date', $this->end_date, true);
$criteria->compare('evaluatee', $this->evaluatee, true);
$criteria->compare('date_created', $this->date_created, true);
$criteria->compare('created_by', $this->created_by, true);
}
if ($search_date_end !== '' && $search_date_start !== ''){
$criteria->compare('start_date', $search_date_start, false, '>=');
$criteria->compare('end_date', $search_date_end, false, '<=');
}
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
You add 3 conditions with start_date to your model's search method:
$criteria->addSearchCondition('start_date', $search_date_start);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('start_date', $search_date_start, false, '>=');
Imagine that your sql after WHERE looks like:
WHERE
start_date='2015-10-01'
AND start_date LIKE '%2015-10-01%'
AND start_date>='2015-10-01'
the last two conditions become useless. So you need left only one condition.
P.S. Activate a trace log in main.php to look your SQL queries for debug:
'routes' => array(
array(
'class' => 'CFileLogRoute',
'logFile' => 'application_trace.log',
'levels' => 'trace',
'rotateByCopy' => true,
'enabled' => true,
)
)
try this:
if ($search_date_end !== '' && $search_date_start !== ''){
$criteria->addBetweenCondition('DATE_FORMAT(start_date,"%Y-%m-%d")',
date("Y-m-d", strtotime($search_date_start)),
date("Y-m-d", strtotime($search_date_end)), 'AND');
$criteria->addBetweenCondition('DATE_FORMAT(end_date,"%Y-%m-%d")',
date("Y-m-d", strtotime($search_date_start)),
date("Y-m-d", strtotime($search_date_end)), 'AND');
}
i knew it. i know that there is something missing with my condition..
if ($search_date_end !== '' && $search_date_start !== ''){
$criteria->compare('start_date', $search_date_start, false, '>=');
$criteria->compare('end_date', $search_date_end, false, '<=');
}
with this condition, only the start_date and end_date is validated. that is why it will only return the two dates. from and to.
this is what i did. this validates everything.
if ($search_date_end == '' && $search_date_start !== '') {
$criteria->condition = "start_date >= '$search_date_start'";
} elseif ($search_date_end !== '' && $search_date_start == '') {
$criteria->condition = "end_date <= '$search_date_end'";
} elseif ($search_date_end !== '' && $search_date_start !== '') {
$criteria->condition = "start_date >= '$search_date_start' AND end_date <= '$search_date_end'";
}

Using render() value does not update when color box open second time

I'm posting value using color box from view to controller. First time it works perfectly fine but when I reopen the color box it POST the old value to the new.
This is my color box code:
$('#equipmentPopup').colorbox({
ajax: true,
width: "620px",
height: "450px",
href: showEquipment,
data: {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
});
This is my action code:
public function actionShowEquipment()
{
$this->layout = "//layouts/popup";
$equipmentConflicts = '';
$briefingId = $_POST['briefingId'];
$briefingDate = $_POST['briefingDate'];
$briefingEndDate = isset($_POST['briefingEndDate']) ? $_POST['briefingEndDate'] : '';
$serializeBriefingEquipments = isset($_POST['briefingEquipments']) ? $_POST['briefingEquipments'] : '';
$equipment = CHtml::listData(Equipment::model()->findAll(), 'id', 'name');
$briefingCenter = BriefingCenter::model()->findByPk(Yii::app()->user->currentBriefingCenterId);
if ($briefingId) {
$briefingEquipmentArr = BriefingEquipment::model()->findAll('briefing_id = :bId', array(':bId' => $briefingId));
if (!$briefingEquipmentArr) {
$briefingEquipmentArr[] = new BriefingEquipment();
}
} else if ($serializeBriefingEquipments) {
$serializeBriefingEquipments = unserialize($serializeBriefingEquipments);
}
$briefing = Briefing::model()->findByPk($briefingId);
if (!empty($briefing->scheduled_date) && !empty($briefing->scheduled_end_date)) {
$minDate = $briefing->scheduled_date;
$maxDate = $briefing->scheduled_end_date;
} else {
$minDate = $briefingDate;
$maxDate = $briefingEndDate;
}
echo $this->render('edit/equipment', array(
'briefing' => array(
'briefingId' => $briefingId,
'briefingDate' => $briefingDate,
'briefingEndDate' => $briefingEndDate,
),
'minDate' => strtotime($minDate),
'maxDate' => strtotime($maxDate),
'briefingEquipmentArr' => $briefingEquipmentArr,
'equipments' => $equipment,
'briefingCenter' => $briefingCenter,
'serializeBriefingEquipments' => $serializeBriefingEquipments,
'dateFormat' => Yii::app()->user->currentBriefingCenterDateFormat,
));
}
Your code does not work for me. I see there is no passed data by colorbox, so try changing data to this:
data: function() {
return {
briefingId: $("#briefing_id").val(),
briefingDate: $("#Briefing_scheduled_date").val(),
briefingEndDate: $("#Briefing_scheduled_end_date").val(),
briefingEquipments: $('#BriefingEquipments').val()
}
}
Maybe it will help.

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'));

issue validation startdate and enddate codeigniter

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

Categories