Fetch and display dropdown selected value in codeigniter - codeigniter

I wanted to fetch the selected value from the database and display it in codeigniter form_dropdown() function but it displays wrong.
Controller:
$type = array(
'options' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
'attributes' => array(
'class' => 'form-control'
)
);
View:
<?php echo form_dropdown('type', $type['options'],'', $type['attributes']) ?>
The Screenshot

Try the below code:
Controller:
$this->data['type'] = array(
'name' => 'type_value',
'attributes' => 'class="form-control"',
'value' => (isset($database_type_value) && trim($database_type_value)) ? $database_type_value: $this->input->post('type_value',TRUE), //$database_type_value - value from database
'options_list' => array(
'section' => 'Section',
'transaction' => 'Transaction',
'document' => 'Document'
),
);
View:
<?php echo form_dropdown($type['name'],$type['options_list'],$type['value'],$type['attributes']);?>

Related

Codeigniter 3 textarea

I have tried to limit number of rows in textarea to 4 but its giving error
Message: Array to string conversion
this is my code of textarea using helper class
$textarea_options = array('class' => 'form-control','rows' => 4, 'cols' => 40);
echo form_textarea('vc_desc', set_value('vc_desc'), $textarea_options);
setup a $data array instead with all the options
$data = array(
'name' => 'vc_desc',
'id' => 'vc_desc',
'value' => set_value('vc_desc'),
'rows' => '50',
'cols' => '10',
'style' => 'width:50%',
'class' => 'form-control'
);
echo form_textarea($data);
Use rows and cols to get change the height and length of text area in code ignitor.
$data = array('name' => 'SupAddress','value' =>set_value('SupAddress'), 'id'=>'SupAddress', 'class' => 'form-control' ,'readonly' => 'true' ,'rows' => '3', 'cols' => '40');
echo Form_textarea($data);

CakePHP - How to dynamically change the fields in my form after selecting from drop-down list

I am having a trouble on getting the value of the selected drop-down list(package_id) to populate the next fields particularly the Departure Time and Price which is in the Package Model.
Here is my code in View/Reservations/package.ctp:
<?php echo $this->Form->create('Reservation'); ?>
<table cellspacing="10">
<?php
echo $this->Html->tableCells(array(
array(
'Date: ',
$this->Form->input('date', array('label' => false, 'type' => 'text', 'class' => 'datepicker'))
),
array(
'Package Name:',
$this->Form->input('package_id', array('label' => false, 'options' => $name, 'id' => 'PackageID', 'empty' => '-- Select Package --'))
),
array(
'Departure Time:',
$this->Form->input('departure_time', array('label' => false, 'type' => 'label', 'id' => 'test'))
),
array(
'Price:',
$this->Form->input('price', array('label' => false, 'id' => 'test'))
),
array(
'Number of Person:',
$this->Form->input('number_of_people', array('label' => false))
),
array(
'Total Price:',
$this->Form->input('price', array('label' => false))
),
array(
'',
$this->Form->Submit('Book Now', array('class' => 'button'))
),
));
?>
</table>
and Here is my code in public function package():
$options = $this->Packages->find('list'); //or whatever conditions you want
$this->set('name', $options);
I was trying to use JS helper but I can't get it right here is my code:
$this->Js->get('#PackageID');
$this->Js->event('change',
$this->Js->request(array(
'controller'=>'Reservation',
'action'=>'getPackage'
), array(
'update'=> '#test',
'async' => true,
'method' => 'post',
'dataExpression' => true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true))
)
)
);
Feel free to ask questions for clarification. Thank You in advance :)
Try this :
in the view .ctp , add this js function :
<script language="JavaScript">
jQuery(document).ready(function() {
$("#PackageID").chosen().bind('change', function() {
$.post('/project_name/controller_name/listDeparetementByPackage/'+$(this).val(), function(data) {
$("#test").empty().append(data);
$("#test").trigger("liszt:updated");
}, 'html');
});
});
</script>
and in your controller , here is the function to get the departements by pacakge id :
function listDeparetementByPackage($package = null ) {
$this->layout = 'ajax';
$this->beforeRender();
$this->autoRender = false;
$data = $this->Package->Departement->find('list', array('fields' => array('Departement.id', 'Departement.libelle'),
'conditions' => array('Departement.package_id' => $package),
'recursive' => 0 ));
if(count($data)>0){
foreach($data as $key => $val) {
echo "<option value=$key>$val</option>";
}
}else{
echo "<option></option>"; // if the result is empty , show a select empty
}
}
Hope it helps .

Yii CGridview Filter Datepicker

I have already read the forum about make custom cgridview.. I want to make filter use datetimepicker.
Datetimepicker:
I can include already the datetimepicker, but when I choose the date, it became error. :(..
My date datatype on database is 'timestamp'
This is the code
<?php
$this->breadcrumbs=array(
'Events'=>array('index'),
'Manage',
);
$this->menu=array(
array('label'=>'List Event','url'=>array('index')),
array('label'=>'Create Event','url'=>array('create')),
);
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('event-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Events</h1>
<p>
You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>
or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.
</p>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button btn')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'event-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'afterAjaxUpdate'=>"function(){jQuery('#event_date_search').datepicker({'dateFormat': 'yy-mm-dd'})}",
'columns'=>array(
array(
'type' => 'raw',
'name'=> 'event_image',
'value' => 'CHtml::image("'.Yii::app()->request->baseUrl.'/uploads/event/$data->event_image", "event_image" ,array("width"=>100))',
'filter'=> false,
),
'event_name',
array(
'name' => 'event_date',
'type' => 'raw',
'filter'=>$this->widget('zii.widgets.jui.CJuiDatepicker', array(
'model'=>$model,
'attribute'=>'event_date',
'htmlOptions' => array(
'id' => 'event_date_search'
),
'options' => array(
'dateFormat' => 'yy-mm-dd'
)
), true)
),
array(
'name'=>'published',
'filter'=>CHtml::dropDownList('Event[published]', '',
array(
''=>'',
'1'=>'Published',
'0'=>'Not Published',
)
),
'value' =>'($data->published==1)?"Published":"Not Published"',
),
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
?>
Thank you very much...
You can change search() function of model class. It can be like this:
public function search() {
....
$criteria->addCondition('DATE_FORMAT(time_field, \'%Y-%m-%d\') = ' . $this->time_field);
....
}
but it can be need to translate input value of $this->time_field.
i had the exact same problem yesterday and for some unknown reason by moving the
'dateFormat' => 'yy-mm-dd'
from option to htmloptions fixed my problem. to be honest i have it in both htmloptions and options and don't have any problems so far
'htmlOptions' => array(
'id' => 'event_date_search',
'dateFormat' => 'yy-mm-dd'
),
'options' => array(
'dateFormat' => 'yy-mm-dd'
),
hope this helps
Could you replace your code
'options' => array(
'dateFormat' => 'yy-mm-dd'
)
with
'defaultOptions' => array(
'showOn' => 'focus',
'dateFormat' => 'yy-mm-dd',
'showOtherMonths' => true,
'selectOtherMonths' => true,
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
)
Hope this help
For detail check this link http://www.yiiframework.com/wiki/318/using-cjuidatepicker-for-cgridview-filter/

CakePHP validation not working

Iam new in cakephp ,I need to validate a form.
This is the code:
Controller:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
public function index(){
}
function add_task()
{
if(!empty($this->data)) {
//print_r($this->data);
$this->Task->set($this->data);
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
// didn't validate logic
echo $errors = $this->Task->validationErrors;
}
}
}
}
?>
Model:
<?php
class Task extends AppModel
{
public var $name = 'Task';
var $useDbConfig = 'travanco_erp';
public var $useTable = 'tbl_tasks'; // This model uses a database table 'exmp'
public var $validate = array(
'task_title_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The title field is required'
),
'task_description_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The description field is required'
),
'task_from_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The from date field is required'
),
'task_to_mm' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The to date field is required'
)
);
}
?>
This is the view:
<div class="employeeForm" style="width:64%; padding:10px 30%;">
<?php echo $this->Form->create('test', array('class'=>'form'));?>
<fieldset style="width:36em; padding:0px 0px;">
<div style="width:475px; font-family:Arial, Helvetica, sans-serif; font-size:16px; color:#333333; font-weight:bold; margin-left:20px; margin-top:10px;">Add Task</div>
<br/>
<?php
/*echo $this->Form->input('task_ids_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Task ID',
));*/
echo $this->Form->input('task_title_mm', array( 'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Title',
));
echo $this->Form->input('task_description_mm', array( 'type' => 'textarea',
'cols'=>60,
'rows' => 5,
'div'=>'frm_filed_new',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'Description',
));
echo $this->Form->input('task_from_mm', array( 'div'=>'frm_filed_new','id'=>'task_from_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'From',
));
echo $this->Form->input('task_to_mm', array( 'div'=>'frm_filed_new','id'=>'task_to_mm','value'=>'',
'error' => array( 'wrap' => 'div',
'class' => 'formerror'
),
'label' => 'To',
));
?>
<br/>
<?php echo $this->Form->button('Submit', array('type'=>'submit','escape'=>true)); ?>
</fieldset>
<?php echo $this->Form->end(); ?>
</div>
The validation not working.
What is the error in my code?
How can i solve this?
EDIT:
It is the mistake of misconfiguration of databse.php file.Now its corrected .And the print_r($errors) displays the errors.But that not displayed in the view page , i mean near the textboxes.
This is that error array:
Array ( [task_title_mm] => Array ( [0] => The title field is required ) [task_description_mm] => Array ( [0] => The description field is required ) [task_from_mm] => Array ( [0] => The from date field is required ) [task_to_mm] => Array ( [0] => The to date field is required ) )
How can i put it in near the text box?
CakePHP is designed to automatically validate model and display validation errors. Auto validation runs on model save. In your case:
$this->Task->save($this->request->data);
above will trigger validation. There is no need to run: $this->Task->validates() - If you do so, you also have to take care of displaying validation error by your own. So I think you simply should try:
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $helpers = array('Html','Form','Session');
function add_task()
{
if ($this->request->is('post')) {
// If the form data can be validated and saved...
if ($this->Task->save($this->request->data)) {
//saved and validated
}
}
}
}
?>
one thing i noticed in your code that you are writing in your model
public var $validate=array();
instead try
public $validate= array() or var $validate=array();
Validation should work after words.
Thanks :)
Try this:
if ($this->Task->validates()) {
// it validated logic
//echo "ttt";
} else {
$this->validateErrors($this->Task);
$this->render();
}

Validation Errors not showing

I am trying to validate a user when they register to my application. Nothing is getting set to validationErrors, which is strange can anyone help me out?
Here is my MembersController
<?php
class MembersController extends AppController {
var $name = 'Members';
var $components = array('RequestHandler','Uploader.Uploader');
function beforeFilter() {
parent::beforeFilter();
$this->layout = 'area';
$this->Auth->allow('register');
$this->Auth->loginRedirect = array('controller' => 'members', 'action' => 'dashboard');
$this->Uploader->uploadDir = 'files/avatars/';
$this->Uploader->maxFileSize = '2M';
}
function login() {}
function logout() {
$this->redirect($this->Auth->logout());
}
function register() {
if ($this->data) {
if ($this->data['Member']['psword'] == $this->Auth->password($this->data['Member']['psword_confirm'])) {
$this->Member->create();
if ($this->Member->save($this->data)) {
$this->Auth->login($this->data);
$this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash(__('Account could not be created', true));
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
}
}
}
}
}
?>
Member Model
<?php
class Member extends AppModel {
var $name = 'Member';
var $actsAs = array('Searchable');
var $validate = array(
'first_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter your first name'
),
'last_name' => array(
'rule' => 'alphaNumeric',
'required' => true,
'allowEmpty' => false,
'message' => "Please enter your last name"
),
'email_address' => array(
'loginRule-1' => array(
'rule' => 'email',
'message' => 'please enter a valid email address',
'last' => true
),
'loginRule-2' => array(
'rule' => 'isUnique',
'message' => 'It looks like that email has been used before'
)
),
'psword' => array(
'rule' => array('minLength',8),
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a password with a minimum lenght of 8 characters.'
)
);
var $hasOne = array('Avatar');
var $hasMany = array(
'Favourite' => array(
'className' => 'Favourite',
'foreignKey' => 'member_id',
'dependent' => false
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'member_id',
'dependent' => false
),
'Guestbook' => array(
'className' => 'Guestbook',
'foreignKey' => 'member_id',
'dependent' => false
),
'Accommodation'
);
var $hasAndBelongsToMany = array('Interest' => array(
'fields' => array('id','interest')
)
);
function beforeSave($options = array()) {
parent::beforeSave();
if (isset($this->data[$this->alias]['interests']) && !empty($this->data[$this->alias]['interests'])) {
$tagIds = $this->Interest->saveMemberInterests($this->data[$this->alias]['interests']);
unset($this->data[$this->alias]['interests']);
$this->data[$this->Interest->alias][$this->Interest->alias] = $tagIds;
}
$this->data['Member']['first_name'] = Inflector::humanize($this->data['Member']['first_name']);
$this->data['Member']['last_name'] = Inflector::humanize($this->data['Member']['last_name']);
return true;
}
}
?>
login.ctp
<div id="login-form" class="round">
<h2>Sign In</h2>
<?php echo $form->create('Member', array('action' => 'login')); ?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->end('Sign In');?>
</div>
<div id="signup-form" class="round">
<h2>Don't have an account yet?</h2>
<?php echo $form->create('Member', array('action' => 'register')); ?>
<?php echo $form->input('first_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('last_name',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('email_address',array('class' => 'login-text',
'label' => array('class' => 'login-label')
));?>
<?php echo $form->input('psword' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Password')
))?>
<?php echo $form->input('psword_confirm' ,array('class' => 'login-text',
'label' => array('class' => 'login-label','text' => 'Confirm'),
'div' => array('style' => ''),
'type' => 'password'
))?>
<?php echo $form->end('Sign In');?>
</div>
I believe your problem is here:
$this->redirect(array('action' => 'login'));
pr($this->Member->invalidFields());
The validation errors are designed to show on the form, underneath the appropriate field. However, instead of continuing and trying to display the form, you are redirecting the user to a different page.
If you remove the two lines above, it should show the validation errors beneath their fields on the form when the validation fails.

Resources