I'm very new in YII and sorry if it's a silly question.
in the view (_form) I'm displayng 2 different tables: billing & cost
they are connected trough colums IDCLIENT & IDBILLING
When I create a new billing I would like to select (with checkboxes) which cost insert in it, and the cost.IDBILLING must be update with the IDBILLING just created.
I've underline the unknow part.
Here _form Code:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'billing-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'IDCLIENT'); ?>
<h2><?php echo $client->IDCLIENT; ?></h2>
<?php echo $form->error($model,'IDCLIENT'); ?> <br>
<h3><?php
echo $client->name." ".$client->surname."<br>".$client->document;
?></h3>
</div>
<div class="row">
<?php echo $form->labelEx($model,'datefrom'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[datefrom]", // the name of the field
'value'=>$model->datefrom, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'datefrom'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'dateto'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[dateto]", // the name of the field
'value'=>$model->dateto, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'dateto'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'name'=>"Billing[date]", // the name of the field
'value'=>$model->date, // pre-fill the value
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd', // optional Date formatting
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<?php echo $form->error($model,'date'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state'); ?>
<?php echo $form->textField($model,'state',array('size'=>16,'maxlength'=>16)); ?>
<?php echo $form->error($model,'state'); ?>
</div>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'cost-grid',
'dataProvider'=>new CActiveDataProvider('Cost',array(
'criteria' => $criteria,
'pagination' => array('pageSize' => 10),
)),
'selectableRows' => 2,
//'filter'=>$model,
'columns'=>array(
array('class'=>'CCheckBoxColumn','value'=>'$data->IDCOST/*??????IS THIS CORRET????*/',),
'IDCOST',
'advance',
'spent',
'date',
'type',
'scope',
/*
'note',
'IDCLIENT',
*/
),
)); ?>
here the controller:
public function actionCreate($IDCLIENT)
{
$model=new Billing;
$client = new Client;
$criteria=new CDbCriteria;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
//$this->IDCLIENT= $IDCLIENT;
$client = Client::model()->findByPk((int)$IDCLIENT);
$criteria->condition = "IDCLIENT = ".$client->IDCLIENT." AND (IDBILLING IS NULL OR IDBILLING = 0)";
$criteria->order = "date DESC";
if(isset($_POST['Billing']))
{
$model->attributes=$_POST['Billing'];
$model->IDCLIENT=$client->IDCLIENT;
if($model->save()){
$cost= new Cost;
if($cost=Cost::model()->updateAll(array( 'IDBILLING' => $model->IDBILLING ), 'IDCOST = '.#########WHAT I HAVE TO INSERT HERE???########))
$this->redirect(array('view','id'=>$model->IDBILLING));
}
}
$this->render('create',array(
'model'=>$model,
'client'=>$client,
'criteria'=>$criteria,
));
}
Thanks in advance for any reply
you can refresh your grids like this (in javascript):
$.fn.yiiGridView.update("your-grid-name");
submit the data you want by ajax to another controller and save it or whatever you want, and then refresh your grid and display your new result!
cheers
Related
I have two tables basically three tables, Items, business and business_items. In items table I have two fields items_name and description and in my business table I have business_id, business_name. In my business_items table I have Items_id, business_id as foreign key and an image field and a price field. Now these foreign keys fields are actually drop down list which are dynamic in nature. So as an owner, I will select items from items drop down list and a business from business drop down list.
My problem
As an admin, I can create items and businesses and all that stuff. But suppose an owner wants to create business_items, his business is already on the drop down list, but the items which he wants to add in his business does not found in the drop down list. So how can I make sure that, if no results found in the items drop down list, the searched item by owner automatically stores in items table and then he can add image and all the data saved in business_items table. I hope I explained my problem. I will explain more on ask. Feel free to ask.
Below is my business_items table _form
<?php
/* #var $this BusinessItemsController */
/* #var $model BusinessItems */
/* #var $form BSActiveForm */
$form = $this->beginWidget('bootstrap.widgets.BsActiveForm', array(
'id'=>'business-items-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
));
?>
<p class="help-block">
Fields with <span class="required">*</span> are required.
</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->labelEx($model,'business_id'); ?>
<?php
$this->widget('ext.select2.ESelect2', array(
'name' => 'BusinessItems[business_id]',
'data' => CHtml::listData(Business::model()->findAll(), 'id', 'business_name'), //the whole available list
'htmlOptions' => array(
'placeholder'=>' search Business name?',
'style' => 'width:530px',
),
));
?>
<div class="gap-small"> </div>
<?php echo $form->labelEx($model,'items_id'); ?>
<?php
$this->widget('ext.select2.ESelect2', array(
'name' => 'BusinessItems[items_id]',
'data' => CHtml::listData(Items::model()->findAll(), 'id', 'item_name'), //the whole available list
'htmlOptions'=>array(
'placeholder'=>' search Item name?',
'style' => 'width:530px',
),
));
?>
<div class="gap-small"> </div>
<div class="row">
<div class="col-md-7">
<?php echo $form->textFieldControlGroup($model,'item_price',array('maxlength'=>60)); ?> </div>
</div>
<div class="col-md-3">
<?php echo BsHtml::activeFileField($model, 'image'); ?> <!-- // by this we can upload image-->
<?php echo $form->error($model,'image'); ?>
</div>
<div class="gap-small"> </div><br/>
<?php if ($model->isNewRecord != 1) : ?>
<div class="row">
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/'.$model->image, "image", array('width' => 250, 'height' => 250,)); ?> <!-- Image shown here if page is update page-->
</div>
<?php endif; ?>
</div>
<div class="gap-small"> </div>
<?php
echo BsHtml::submitButton('Submit', array('color' => BsHtml::BUTTON_COLOR_PRIMARY));
$this->endWidget();
?>
I have two models Register and Login.I insert data into these two tables from a single form,I want to display the entered data in a single view page,ie data from two models in a single view.php.
RegisterController.php
public function actionCreate()
{
$model = new Register;
$modelLogin = new Login;
$modelGenerate = new Generate;
$row = Generate::model()->findByPk('1') ;
$gen_reg = $row['gen_reg'];
$gen_log = $row['gen_log'];
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['btnRegister']))
{
$model->attributes=$_POST['Register'];
$modelLogin->attributes=$_POST['Login'];
$modelLogin->reg_id=$model->reg_id;
$valid = $model->validate();
$valid = $modelLogin->validate() && $valid;
if($model->save()&& $modelLogin->save())
$this->redirect(array('view','id'=>$modelLogin->log_id)
);
}
$this->render('create',array(
'model'=>$model,
'modelLogin'=>$modelLogin,
'gen_reg'=>$gen_reg,
'gen_log'=>$gen_log
));
}
_form.php
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'register-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
)); ?>
<div class="row">
<?php echo $form->textField($model,'reg_id',array('size'=>10,'maxlength'=>10,'class'=>'txt'));?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username',array('size'=>50,'maxlength'=>50,'class'=>'txt')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'email'); ?>
<?php echo $form->textField($modelLogin,'email',array('size'=>60,'maxlength'=>100,'class'=>'txt')); ?>
<?php echo $form->error($modelLogin,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'password'); ?>
<?php echo $form->passwordField($modelLogin,'password',array('size'=>50,'maxlength'=>50,'class'=>'txt')); ?>
<?php echo $form->error($modelLogin,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($modelLogin,'passwordCompare'); ?>
<?php echo $form->passwordField($modelLogin,'passwordCompare',array('size'=>60,'maxlength'=>64,'class'=>'txt')); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mobile'); ?>
<?php echo $form->textField($model,'mobile',array('size'=>10,'maxlength'=>10,'class'=>'txt')); ?>
<?php echo $form->error($model,'mobile'); ?>
</div>
<div class="row">
<?php echo $form->textField($modelLogin,'log_id',array('size'=>10,'maxlength'=>10,'class'=>'txt'));?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Register' : 'Save',array('name'=>'btnRegister','class'=>'btn')); ?>
</div>
<?php $this->endWidget(); ?>
Relation in register model
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'logins' => array(self::HAS_MANY, 'Login', 'reg_id'),
);
}
Relation in login model
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'reg' => array(self::BELONGS_TO, 'Register', 'reg_id'),
);
}
I want to display data from two models(that i just inserted before)to be displayed on my view.php page.how can i achive this??? now i got the output as not set for fields from Login model.
view.php
$this->breadcrumbs=array(
'Register'=>array('index'),
$model->reg_id,
);
$this->menu=array(
array('label'=>'List Register', 'url'=>array('index')),
array('label'=>'Create Register', 'url'=>array('create')),
array('label'=>'Update Register', 'url'=>array('update', 'id'=>$model->reg_id)),
array('label'=>'Delete Register', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->reg_id),'confirm'=>'Are you sure you want to delete this item?')),
array('label'=>'Manage Register', 'url'=>array('admin')),
);
?>
<h1>View Register #<?php echo $model->reg_id; ?></h1>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'reg_id',
'username',
'mobile',
),
)); ?>
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$row,
'attributes'=>array(
'log_id',
'password',
'email',
),
)); ?>
I have problem with CjuiDatePicker.. It's working normal when you in mode create, but when you in mode update, that can be show the time, I only need the date.
How must I do to make the time dissapear? I try to read the issue about this, but when I try to add dateFormat, nothing happen..
This is my code :
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'event-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textFieldRow($model,'event_name',array('class'=>'span5','maxlength'=>255)); ?>
<label for="Event_event_date" class="required">Event Date <span class="required">*</span></label>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'event_date',
// additional javascript options for the date picker plugin
'options'=>array(
'showAnim'=>'slideDown',
'minDate'=>'new Date()',
'changeMonth'=>true,
'changeYear'=>true,
'dateFormat' => 'yy-mm-dd'
),
));
?>
<?php echo $form->textAreaRow($model,'event_description',array('rows'=>6, 'cols'=>50, 'class'=>'span8')); ?>
<label for="Event_event_image" class="required">Event Image <span class="required">*</span></label>
<?php
if(!$model->isNewRecord){
echo CHtml::image(Yii::app()->request->baseUrl.'/uploads/event/'.$model->event_image,'image',array('width'=>300));
echo '<br />';
}
?>
<?php echo CHtml::activeFileField($model,'event_image'); ?>
<?php echo $form->error($model,'event_image'); ?>
<br /><br />
<?php echo $form->checkBoxRow($model,'published'); ?>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
)); ?>
</div>
<?php $this->endWidget(); ?>
In your model class, have a afterFind() event handler, something like:
protected function afterFind(){
$this->event_date = Yii::app()->dateFormatter->format('yyyy-MM-dd', CDateTimeParser::parse($this->event_date, 'yyyy-MM-dd'));
return parent::afterFind();
}
This will also help you: http://www.yiiframework.com/wiki/183/using-international-dates/#hh4
<?php Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
$this->widget('CJuiDateTimePicker',array(
'model'=>$model, //Model object
'attribute'=>'start_date', //attribute name
'mode'=>'datetime', //use "time","date" or "datetime" (default) <---- use this option to show date, time or datetime
'language'=>'en_us',
'options'=>array(
'regional'=>'en_us',
'timeFormat'=>'hh:mm:ss',
'minDate'=>'new Date()',
'onSelect'=>'js:function(dateText, inst){
enableEndDate(dateText);
}'
) // jquery plugin options
));
?>
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(); ?>