Related
how to pre-select option from dropdown on the base of data coming from database or model to view.
I also want to save this data if change in dropdown option.
I try this code
<select class="form-control appointment_status" >
<option <?php if ($row['status'] == 0) { ?> selected <?php } ?> value="0">In process</option>
<option <?php if ($row['status'] == 1) { ?> selected <?php } ?> value="1">Completed</option>
</select>
This is normally what I like to do(this goes intto your controller):
// Select Categories
$categories_options = array();
$categories_options[0] = 'Select Categories';
$categories_list = $this->Terms_model->get_list();
foreach($categories_list as $cat){
$categories_options[$cat->term_id] = $cat->title;
}
$data['categories_options'] = $categories_options;
Assuming that your passing a $data variable to your view, you will be able to display it like this:
<!-- Post Categories -->
<?php
$data = array(
'class' => 'form-control js-example-basic-multiple',
'value' => set_value('categories'),
'multiple' => 'multiple',
);
?>
<div class="form-group">
<?= form_label('Categories','categories'); ?>
<?= form_dropdown('categories[]', $categories_options, 0, $data); ?>
</div>
and then to edit it(a different view):
<?php
$options = array(
'' => 'Please select an option',
'0' => 'In process',
'1' => 'Completed',
);
$data = array('class' => 'form-control');
?>
<div class="form-group">
<?= form_label('Status', 'status'); ?>
<?= form_dropdown('status', $options, $item->status, $data); ?>
</div>
Obviously you will need to change more stuff but I'm sure it will give you a better idea and approach.
Try something like this:
$status = ($row['status']) ? 'selected' : '';
echo <<<END
<option value="0" $status>In process</option>
<option value="1" $status>Completed</option>
END;
Using class... most of dropdown components uses active class to definy the first element on dropdown, so just put it on which element you want and will do the trick
Hello I have dropdownlist dependant textfield. The value of the textfield should be updated via ajax request when dropdownlist is selected (I'm using Yii's CHTML textfield).
Here is my code :
view _form.php
<div class="row">
<?php echo $form->labelEx($model,'kode_rincian'); ?>
<?php
echo $form->dropDownList($model, 'kode_rincian', array(), array(
'empty'=>'--Pilih--',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('OPS/calculateRealisasi'),
//'update'=>'#OPS_contrealisasi',
'dataType'=>'json',
'data'=>array(
'kode_program' => 'js:$(\'#OPS_kode_program option:selected\').val()',
'kode_kegiatan' => 'js:$(\'#OPS_kode_kegiatan option:selected\').val()',
'kode_output' => 'js:$(\'#OPS_kode_output option:selected\').val()',
'kode_komponen' => 'js:$(\'#OPS_kode_komponen option:selected\').val()',
'kode_akun' => 'js:$(\'#OPS_kode_akun option:selected\').val()',
'kode_rincian'=>'js:this.value',
),
'success'=>"function(data)
{
$('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
)
));
?>
<?php echo $form->error($model,'kode_rincian'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'realisasi_at'); ?>
<?php
echo $form->textField($model,'realisasi_at');
?>
<?php echo $form->error($model,'realisasi_at'); ?>
</div class="row">
<?php echo $form->labelEx($model,'sisa_at'); ?>
<?php echo $form->textField($model,'sisa_at'); ?>
<?php echo $form->error($model,'sisa_at'); ?>
</div>
And controller OPSController.php:
public function actionCalculateRealisasi(){
$kode_rincian = $_POST["kode_rincian"];
$kode_program = $_POST["kode_program"];
$kode_kegiatan = $_POST["kode_kegiatan"];
$kode_komponen = $_POST["kode_komponen"];
$kode_akun = $_POST["kode_akun"];
$kode_output = $_POST["kode_output"];
$modelkode= KodePOK::model()->findByAttributes(array(
'kode_program'=>$kode_program,
'kode_komponen'=>$kode_komponen,
'kode_kegiatan'=>$kode_kegiatan,
'kode_akun'=>$kode_akun,
'kode_output'=>$kode_output,
'kode_rincian'=>$kode_rincian,
));
if($modelkode!=NULL){
$idpok=$modelkode->id_pok;
}
else{
$idpok=0;
}
$criteria = new CDbCriteria;
$criteria->select='SUM(jumlah_pengajuan) as realisasi';
$criteria->condition="id_pok='".$idpok."'";
$sum = OPS::model()->find($criteria);
$sumrealisasi=$sum->realisasi;
$sumrealisasi=(int)$sumrealisasi;
$calcsisa=POK::model()->findByPk($idpok);
$getjumlah=$calcsisa->jumlah_pagu;
$sumsisa=$getjumlah-$sumrealisasi;
echo CJSON::encode(array(
'sumrealisasi'=>$sumrealisasi,
'sumsisa'=>$sumsisa,
));
Yii::app()->end();
}
The code didn't show any error but the textfield wasn't updated. Please help me. Here is the result when I tried to inspect the page element :
I've solved the problem.
I changed
'success'=>"function(data)
{ $('#OPS_realisasi_at').html(data.sumrealisasi);
$('#OPS_sisa_at').html(data.sumsisa);
} ",
to :
'success'=>"function(data)
{ $('#OPS_realisasi_at').val(data.sumrealisasi);
$('#OPS_sisa_at').val(data.sumsisa);
} ",
I am doing a small application in Yii Framework for that my database is something like this
=== Invoices ===
id (PK)
customer_id
invoice_title
order_no
invoice_issue_date
due_date
description
=== Customers ===
id (PK)
email_address
customer_name
address
city
state
postal_code
description
I have rendered the Customer model in Invoice model so that I can enter all the values for both models in a single Invoice form.But there is one problem,let us assume that I have a customer name xyz which I had saved before.Now when I am going to again fill the Customer name with xyz,it should show all the fields of both models like invoice_title,order_no,invoice_issue_date,due_date,description,email_address,customer_name,address etc. in that input fields of the form so that I don't have to re-enter all the fields again.So how this can be achive in Yii framework.Any help and suggestions will be highly appreciable.More clarification on codes that I have done can be shared if needed.
Please help me out.I am totally stuck here.
To do this as everyone has already mentioned you need ajax, and some javascript. The logic is something like this:
When a value is selected in the dropdown for customer name, trigger an ajax call to retrieve the information about that user. This can be easily done with the ajax option, which is available as an additional htmlOption for some html element helpers in CHtml, as part of clientChange.
echo $form->dropDownList($model,'customer_name',CHtml::listData(Customers::model()->findAll(),'id','customer_name'),
array(// htmlOptions
'ajax'=>array(// special htmlOption through clientChange, for ajax
'type'=>'GET',
'url'=>$this->createUrl('controllername/customerdetails'),// action that will generate the data
'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
'dataType'=>'json',// type of data we expect back from the server
'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
)
)
);
The documentation for the above options for ajax can be seen in jquery's ajax documentation.
Then in the server side find the particular customer, and send a response to the browser. Example:
// in the controllername code an action that will return the values as json
public function actionCustomerdetails($id){
$var=Customers::model()->findByPk($id);
echo CJSON::encode($var);
}
When you receive the server response populate the respective fields. This can be done in the success function callback for ajax, in the above code it was updateFields:
Yii::app()->clientScript->registerScript('update','
function updateFields(data, textStatus, jqXHR){
// select each input field by id, and update its value
$("#Customers_postal_code").val(data.postal_code);
$("#Customers_city").val(data.city);
$("#Customers_address").val(data.address);
// similarly update the fields for the other inputs
}
');
Notes:
Your customer can have many invoices, so the question will be which invoice to select given a customer name. That's something you'll have to handle, i think my answer has enough code to get you going.
To know the input field ids, you can simply check the generated html.
You could do this in two stages, so that:
When the view is initially displayed, the customer is asked for their email address or customer_name.
The Controller Action that the form is submitted to then retrieves data from the Customer model for the submitted email address or customer_name (I'll use email_address in my example below). Once retrieved, you can display your Single Invoice Form View with the data pre-populated for the customer if available.
This concept could then be implemented as follows:
<?php
// file: controllers/InvoiceController.php
class InvoiceController extends CController
{
// ... other controller functions
public function actionCreate($step = null)
{
$invoice = new Invoice;
$customer = new Customer;
# Form has been submitted:
if ( isset($_POST['Customer']) )
{
# The submitted form was Step 1:
if ( $step == 1 )
{
# make sure the submitted email address is valid
$customer->setAttributes($_POST['Customer']);
if ( $customer->validate(array('email_address')) )
{
# retrieve the customer by email_address
$customer = Customer::model()->findByAttributes(array('email_address' => $_POST['Customer']['email_address']));
}
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
# The submitted form was Step 2:
elseif ( $step == 2 )
{
$income->setAttributes($_POST['Invoice']);
$customer->setAttributes($_POST['Customer']);
# save the data
if ( $customer->save() )
{
$invoice->customer_id = $customer->id;
if ( $invoice->save() )
{
$this->redirect(array('view', 'id' => $invoice->id));
}
}
# display any errors
$this->render('createstep2', array('invoice' => $invoice, 'customer' => $customer));
}
}
$this->render('createstep1', array('invoice' => $invoice, 'customer' => $customer));
}
// ... other controller functions
}
?>
You could split that to two separate Controller Actions if you wish.
For Step 1 View, you could then have the following:
<!-- file: views/invoice/createstep1.php -->
<h1>Create Invoice: Step 1</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 1)
));
?>
<?php echo $form->errorSummary($customer); ?>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Next'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Step 2 view, you could then look like what you already have. Maybe something like:
<!-- file: views/invoice/createstep2.php -->
<h1>Create Invoice: Step 2</h1>
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'invoice-form',
'enableAjaxValidation'=>false,
'action'=>array('invoice/create','step' => 2)
));
?>
<?php echo $form->errorSummary($invoce); ?>
<?php echo $form->errorSummary($customer); ?>
<h2>Customer Details</h2>
<div class="row">
<?php echo $form->labelEx($customer,'email_address'); ?>
<?php echo $form->textField($customer,'email_address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'email_address'); ?>
</div>
<!-- If the customer already exists, these field should be pre-populated: -->
<div class="row">
<?php echo $form->labelEx($customer,'customer_name'); ?>
<?php echo $form->textField($customer,'customer_name', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'customer_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'address'); ?>
<?php echo $form->textField($customer,'address', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'city'); ?>
<?php echo $form->textField($customer,'city', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'city'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'state'); ?>
<?php echo $form->textField($customer,'state', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'state'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'postal_code'); ?>
<?php echo $form->textField($customer,'postal_code', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'postal_code'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($customer,'description'); ?>
<?php echo $form->textField($customer,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($customer,'description'); ?>
</div>
<h2>Order Details</h2>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_title'); ?>
<?php echo $form->textField($invoice,'invoice_title', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'invoice_title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'order_no'); ?>
<?php echo $form->textField($invoice,'order_no', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'order_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'invoice_issue_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'invoice_issue_date',
'value' => $invoice->invoice_issue_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'invoice_issue_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'due_date'); ?>
<?php $form->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $invoice,
'attribute' => 'due_date',
'value' => $invoice->due_date,
'options' => array(
'showButtonPanel' => false,
'changeYear' => true,
'dateFormat' => 'yy-mm-dd',
),
)); ?>
<?php echo $form->error($invoice,'due_date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($invoice,'description'); ?>
<?php echo $form->textField($invoice,'description', array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($invoice,'description'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Create'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
Have you checked the Yii Autocomplete widget? And you wouldn't have to worry about AJAX implementation. It does it for you.
Yii Framework: CJui AutoComplete
A more customized autocomplete solution in this link.
Yii Framework: custom-autocomplete-display-and-value-submission
I am working on YII framework, and I am a newbie.
I have user register form as shown below:
Username: [Textbox]
Email: [Textbox]
Address: [Text area]
User Loan Type: (Checkbox list as below)
Loan Type 1
Loan Type 2
Loan Type 3
Loan Type 4
Loan Type 5
Status [yes/no]
Now I have 3 models:
1) User (for user data)
2) LoanType (just for loan type list)
3) UserLoanType (mapping between user and loan type)
All 3 models have HAS_MANY and BELONGS_TO relations as we generally do in YII.
Now when user click on register button I want to save data in user_loan_type table as well. I can simply add core php logic in actionCreate. But is there any standard YII practice for this?? Because I need validation, remain form selected during edit etc. Can anyone guide me how to do this? Or point me any example link, I have googled but did't help.
Thanks.
I am able to save data in database,
Now during edit I want to retrieve 3rd table's(tbl_user_loan_request_type) data. I have used below code.
$user = User::model()->findByPk(5);
print_r($user->UserLoanTypes);
But it is giving me blank array.
Where I am wrong??
You may define afterSave methods in your class, like this:
Model User
public function relations()
{
return array(
'UserLoanTypes' => array(self::MANY_MANY, 'LoanType', 'UserLoanType(userId, loanId)'),
);
}
// relation
array('UserLoanTypes', 'safe'),
// label
'UserLoanTypes' => 'User Loan Type'
protected function afterSave()
{
parent::afterSave();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
foreach ($this->UserLoanTypes as $loanId) {
$userLoanType = new UserLoanType();
$userLoanType->userId = $this->id;
$userLoanType->loadId = $loadId;
$userLoanType->save();
}
}
protected function afterDelete()
{
parent::afterDelete();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
}
In form:
<div class="row">
<?php echo $form->labelEx($model,'UserLoanTypes'); ?>
<?php echo $form->checkBoxList($model,'UserLoanTypes', CHtml::listData($LoanTypes, 'id', 'loanName')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
In view you may:
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
'UserLoanTypes' => array(
'name' => 'UserLoanTypes',
'value' => implode(',', CHtml::listData($model->UserLoanTypes, 'id', 'name')),
),
),
)); ?>
If you don't need to assign multiple loanTypes to one User, it would be easier. All you need is the User model for the form visualization:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Username'); ?>
<?php echo $form->textField($model,'Username'); ?>
<?php echo $form->error($model,'Username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Email'); ?>
<?php echo $form->textField($model,'Email'); ?>
<?php echo $form->error($model,'Email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Address'); ?>
<?php echo $form->textArea($model,'Address'); ?>
<?php echo $form->error($model,'Address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UserLoanType'); ?>
<?php echo $form->checkBoxList($model,'idLoanType', CHtml::listData(LoanType::model()->findAll, 'id', 'name')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
<?php $this->endWidget(); ?>
I am doing a yii web application
i have a drop down list that should be dependent on another , i use ajax however it doesnt work.
ive seen the yii tutorial for dependent drop downs and searched everywhere.
http://www.yiiframework.com/wiki/24
this is my main drop down list:
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source'), array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
this is the dependent drop down list :
<div class="row">
<?php echo $form->labelEx($model, 'meal'); ?>
<?php echo $form->dropDownList($model, 'meal', array()); ?>
<?php echo $form->error($model, 'meal'); ?>
</div>
this is my controller action:
public function actionAtest() {
$data = Sources::model()->findAll();
$data = CHtml::listData($data, 'sourceID', 'name');
foreach ($data as $value => $name) {
echo CHtml::tag('option', array('value' => $value), CHtml::encode($name),true);
} }
also, i added the action to the access rules.
any help is appreciated ,
thank you in advance.
You placed the ajax option after the htmlOptions. Here is the modified code
<div class="row">
<?php echo $form->labelEx($model, 'sourceID'); ?>
<?php
echo $form->dropDownList($model, 'sourceID', CHtml::listData(Sources::model()->findAll(), 'sourceID', 'name'), array('empty' => 'select source','ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('reservations/atest'),
'update' => '#meal'
)
)
);
?>
<?php echo $form->error($model, 'sourceID'); ?>
</div>
And instead of using forms dropdownlist use CHtml::dropDownList for the dependent drop-down.
echo CHtml::dropDownList('meal','', array());
You can also use CActiveForm::dropDownList but in that case you have to use CHtml::resolveNameId in the update option of ajax