How to create forms with multiple submit buttons - php

I'm new to Yii framework.I'm using the form.php to update the fields of the table. So now I use this form with three submit buttons - [Save, Accept, Reject]. The form now has the following fields.
<div class="row">
<?php //$model->ReviewedDate=date('Y-m-d H:i:s');?>
<?php echo $form->labelEx($model,'ReviewedDate'); ?>
<?php echo $form->textField($model,'ReviewedDate',array('value'=>'0000-00-00 00:00:00','readonly' => true));te ?>
<?php echo $form->error($model,'ReviewedDate'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Approved'); ?>
<?php echo $form->textField($model,'Approved'); ?>
<?php echo $form->error($model,'Approved'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('confirm' => 'Are you sure to save')); ?></div>
Above there is Approved field.Now, when I click on save all the other fields has to be updated except for approved. (Approved is 0 by default). So when I click on Approve button it should update Approved as well as other fields. When I click on Reject, it should update the approved field to 0. How can I do this.

You can use three submit button and can manage functionality as per that.
In the form create 3 buttons as per below :
<?php echo CHtml::submitButton('Save', array('name' => 'save')); ?>
<?php echo CHtml::submitButton('Accept', array('name' => 'accept')); ?>
<?php echo CHtml::submitButton('Reject', array('name' => 'reject')); ?>
In the controller check which button is clicked as per below :
<?php
if(isset($_POST['save'])){
//save submit button is click and code for save button will be here
}
if(isset($_POST['accept'])){
//accept submit button is click and code for accept button will be here
}
if(isset($_POST['reject'])){
//reject submit button is click and code for reject button will be here
} ?>
All the best :)

Instead of having 3 submit buttons, I'd suggest you use a dropdown list so your users can pick the desired action. Then you check for the value of the dropdown control in order to either "Save", "Accept" or "Reject".
echo CHtml::dropDownList('action', '', array('Accept', 'Reject'));
And in your controller:
if (isset($_POST['ModelName'])) {
switch ($_POST['action']) {
case 'Accept':
# code for Acceptance
break;
case 'Reject':
# code for Rejection
break;
}
//Continue with Saving the Model data here
}

You can add a hiddenField with the action:
<?php echo $form->hiddenField($model, 'typeSubmit'); ?> // Add 'typeSubmit' attribute on the model
And 3 submit buttons. Each button puts on the hidden field the type of Submit.
<?php echo CHtml::submitButton('Save', array('class'=>'btn','onclick'=>'$("#ModelName_typeSubmit").val("save");')); ?> // #ModelName = $model name class.
<?php echo CHtml::submitButton('Accept', array('class'=>'btn','onclick'=>'$("#ModelName_typeSubmit").val("accept");')); ?>
<?php echo CHtml::submitButton('Reject', array('class'=>'btn','onclick'=>'$("#ModelName_typeSubmit").val("reject");')); ?>

Related

Yii collecting data from two models into single form

In my web application I need to collect data from two models in a single form. The first model form is like an update action for making changes in existing data and the second form is for creating a new record. Below is the code I tried but when I click "save" button Its not saving and redirecting instead it is just staying in the same page and the changes I made are reverting back to their previous values for I model and second model the attribute are becoming empty.
My code for the controller
public function actionBookvegetable($id){
$BookVegetable=new BookVegetable;
$model=$this->loadModel($id);
if(isset($_POST['ProducerOffer'])AND (isset($_POST['BookVegetable'])) ) {
$model->attributes=$_POST['ProducerOffer'];
$BookVegetable->attributes=$_POST['BookVegetable'];
if($ProducerOffer->validate() AND $BookVegetable->validate()) {
$BookVegetable->save();
$BookVegetable->booked_by=Yii::app()->user->id;
$BookVegetable->producer_offer_id=$model->id;
$model->save();
}
if (($model->hasErrors() === false)&&($BookVegetable->hasErrors===false))
{
$this->redirect(Yii::app()->user->returnUrl);
}
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,'BookVegetable'=>$BookVegetable));
}
My code for the view form.
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array('id'=>'non-ajax_form','enableAjaxValidation'=>false,)); ?>
<p class="help-block">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model,$BookVegetable); ?>
<?php echo "<br>" ?>
<?php echo $form->dropDownList($model,'vegetable_id', CHtml::listData(Vegetable::model()->findAll(),'id', 'name'), array('prompt'=>'Select Vegetable')); ?>
<?php echo CHtml::encode($model->getAttributeLabel('offered_qty')); ?>
<?php echo CHtml::textField("offered_qty",$model->offered_qty,array('readonly'=>true)); ?>
<?php echo CHtml::encode($model->getAttributeLabel('unit_cost')); ?>
<?php echo CHtml::textField("unit_cost",$model->unit_cost,array('readonly'=>true)); ?>
<?php echo CHtml::encode($model->getAttributeLabel('unit_delivery_cost')); ?>
<?php echo CHtml::textField("unit_delivery_cost",$model->unit_delivery_cost,array('readonly'=>true)); ?>
<?php echo CHtml::textField("booked_quantity",$BookVegetable->booked_quantity); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=> 'Save',)); ?
How should I resolve this Anybody help me out .I am unable to debug the source of error
You are saving the values before assigning the requested values.
Try this code, if it works:
public function actionBookvegetable($id){
$BookVegetable=new BookVegetable;
$model=$this->loadModel($id);
if(isset($_POST['ProducerOffer'])AND (isset($_POST['BookVegetable'])) )
{
$model->attributes=$_POST['ProducerOffer'];
$BookVegetable->attributes= $_POST['BookVegetable'];
/*** The below two lines should be before "$BookVegetable->save()" function ***/
$BookVegetable->booked_by=Yii::app()->user->id;
$BookVegetable->producer_offer_id=$model->id;
/*** Validate() function will check for the errors **/
if($ProducerOffer->validate() AND $BookVegetable->validate())
{
$BookVegetable->save();
$model->save();
$this->redirect(Yii::app()->user->returnUrl);
}
/***There is no need to check again for the errors as validate() will do that, So you can comment this three lines ***/
/**if (($model->hasErrors() === false)&&($BookVegetable->hasErrors===false))
{
$this->redirect(Yii::app()->user->returnUrl);
} */
}
else
{
Yii::app()->user->setReturnUrl($_GET['returnUrl']);
}
$this->render('book',array('model'=>$model,'BookVegetable'=>$BookVegetable));
}
Try changing these input text fields in your view file:
<?php echo $form->dropDownList($model,'vegetable_id', CHtml::listData(Vegetable::model()->findAll(),'id', 'name'), array('prompt'=>'Select Vegetable')); ?>
/*** The first field for below input text field is for "name" of the text fields, so this must follow "ModelName[field_name]" format **/
<?php echo CHtml::textField("ProducerOffer[offered_qty]",$model->offered_qty,array('readonly'=>true)); ?>
<?php echo CHtml::textField("ProducerOffer[unit_cost]",$model->unit_cost,array('readonly'=>true)); ?>
<?php echo CHtml::textField("ProducerOffer[unit_delivery_cost]",$model->unit_delivery_cost,array('readonly'=>true)); ?>
<?php echo CHtml::textField("BookVegetable[booked_quantity]",$BookVegetable->booked_quantity); ?>
I hope this would definitely work.. :)

stay on the same page after error validation in yii

I would like to avoid redirecting after error validation.
I display a list of post and for each post the user can give a comment after clicking on a button.
This display the comment form under the choosen post.
If there is an error in validation of the comment I want to stay on the page and display errors beside the field in error (as default).
Here is My controller action for the comment
public function actionCreate()
{
$model=new Comment;
if(isset($_POST['Comment']))
{
$model->attributes=$_POST['Comment'];
if($model->save()) {
$this->redirect(Yii::app()->request->urlReferrer);
} else {
Yii::app()->end();
}
}
$this->render('create',array(
'model'=>$model,
));
}
and the view
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'enableClientValidation'=>true,
)); ?>
<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,'comment'); ?>
<?php echo $form->textField($model,'comment',array('size'=>60,'maxlength'=>140)); ?>
<?php echo $form->error($model,'comment'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
For the moment, with Yii::app()->end(); it shows a blank page, if I dont do nothing in the else part , then it continues and displays the create view (loosing some decoration)
---Adding some more information
Actually, what I have in my page is this
Post 1
(Comment form)
Commment : ........
Save
Post 2
Post 3
when I click on save without comment, I want to stay in this page, giving the user the possibility to see where the error is (comment is missing) and save it again.
Can you tell me where is my mistake?
Thank you for your help
in the else block you have to tell yii to render the same page again. After calling $model->save() you get errors back in the model. So before Yii::app()->end(); call rendering of your page $this->render('create',array('model'=>$model,));

Set Field Empty When Change Password in Yii

I want to set empty this field:
This is my code from _form.php
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password',array('size'=>50,'maxlength'=>50)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
how to that, please teach me. Thanks all
You can explicitly set the value to be an empty string like this:
<?php echo $form->passwordField($model,'password',array(
'size'=>50,
'maxlength'=>50,
'value'=>'',
)); ?>
Where you are starting your form, you can add htmlOptions like this;
'htmlOptions' => array(
'autocomplete' => 'off'
)
This will disable autocomplete for the whole form. If you just want to do it for a single field, add it to the htmlOptions for that file instead.
This strange behaviour is happen for me too.
I fix it with javascript code to set the password field value to empty.
Yii code:
<div class="row">
<?php echo $form->labelEx($model,'newpassword'); ?>
<?php echo $form->passwordField($model,'newpassword',array('size'=>60,'maxlength'=>128,'value'=>'')); ?>
<?php echo $form->error($model,'newpassword'); ?>
</div>
Javascript code (I am using jQuery) :
<script>
$(document).ready(function()
{
$("#ChangePasswordForm_newpassword").val("");
});
</script>
echo CHtml::passwordField('User[password]','')

Passing combobox selected value to a dialog using ajaxlink

I' trying to pass the dropDownList selected value to this Dialog.
Any ideas on how I can do this?
I tried adding another parameter to the ajaxlink, using array('id'=>'showEventoDialog','tipoaux'=>$data["tipo"]), or only $data->tipo but can't seem to do what I want.
I'm also trying to get the value via $_GET from the Dialog form.
Here's my form and the Dialog link within the form
<?php echo $form->labelEx($model,'tipo'); ?>
<?php echo $form->dropDownList($model,'tipo',Lookup::items('Teste')); ?>
<?php echo $form->error($model,'tipo'); ?>
...
<?php echo $form->labelEx($model,'eventoid'); ?>
<div id="evento">
<?php echo $form->dropDownList($model,'eventoid',CHtml::listData(Evento::model()->findAll(),'id', 'designacao'),array('prompt'=>'Escolha','class'=>'required')); ?>
<?php echo CHtml::ajaxLink(Yii::t('evento','Novo Evento'),$this->createUrl('evento/addnewcom'),array(
'onclick'=>'$("#eventoDialog").dialog("open"); return false;',
'update'=>'#eventoDialog'
),array('id'=>'showEventoDialog'));?>
<div id="eventoDialog"></div>
</div>
Any ideas on how to do this?
Plus will the solution work with any other type of value, like textfield or something else on my form, so I can pass the values to dialogs BEFORE the parent form is submitted.
You can hook up some code to the open event of the dialog that will fire right before the dialog appears. In this code you can query the selected option and write it to the dialog:
<?php echo $form->labelEx($model,'eventoid'); ?>
<div id="evento">
<?php echo $form->dropDownList($model,'eventoid',CHtml::listData(Evento::model()->findAll(),'id', 'designacao'),array('prompt'=>'Escolha','class'=>'required')); ?>
<?php echo CHtml::ajaxLink(Yii::t('evento','Novo Evento'),$this->createUrl('evento/addnewcom'),array(
'onclick'=>'$("#eventoDialog").dialog({open: function(){ $("#selectedvalue").text($("#eventoid").val()); }}) .dialog("open"); return false;',
'update'=>'#eventoDialog'
),array('id'=>'showEventoDialog'));?>
<div id="eventoDialog">
<span>Selected value: </span><span id="selectedvalue" />
</div>
</div>

Yii framework radiobuttonlist

Can anyone shine a light on how to determine which radio button has been selected when the form has been submitted?
I am using CActiveForm::radioButtonList?
You don't need to determine it. Client will transmit its value in POST data.
For example such code
<?=$form->radioButtonList($person,'gender_code',array('m'=>'Male','f'=>'Female')); ?>
will form POST[gender_code]=m or POST[gender_code]=f
Radio List Reflects simple form Submitting process. If you have following list implementation for example
<div class="form">
<?php echo CHtml::beginForm(); ?>
<div class="row">
<?php
echo CHtml::radioButtonList(
'registerMode',
'consumer',
array(
'consumer'=>'I am a FOODIE ',
'staff'=>'I want to give Services ',
),
array('template'=>'<div class="rb">{input}</div><div class="rb">{label}</div><div class="clear"> </div>')
);
?>
</div>
<div class="row">
<?php echo CHtml::submitButton('Register',array('class'=>'submit')); ?>
</div>
<?php echo CHtml::endForm(); ?>
</div><!-- form -->
when submitted following input is generated
array
(
'registerMode' => 'consumer'
'yt0' => 'Register'
)
it represents name or Index of the option Selected
following code can get values
if(isset($_POST['registerMode']))
CVarDumper::Dump($_POST['registerMode'],100,true);
Good Luck

Categories