My Activeform triggers when page is loaded or reloaded - php

Whenever the page is loaded or reloaded through a redirect/render/refresh, it seems to auto submit the last information that was submited to the database constantly. I tried adding restrictions to the add method but it seems to hold information from the previous submit, which allows it to by pass the isset $_POST.
view which contains the actionform.
<div class="form offset2">
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'userTeam-form',
'enableAjaxValidation'=>false,
// Check thta the action method below is correct
'action'=> array('/User/AddTeamMessage', 'id' => $model->id),
)); ?>
<!--
Would allow user to access specific team messages and control how much gets display.
still under construction.
-->
<div class="row">
<?php
echo CHtml::dropDownList("teamId", 'id', Chtml::listData($model->memberOfTeams, 'id', 'teamName'),array(
'empty'=>'Select Team',
'ajax'=>array(
'type'=>'POST', // request type
'url'=>CController::createUrl('DisplayMessage'),
'update'=>'#teamMessages', // selector to update
'data'=>array('teamId'=>'js:this.value'),
)
)
);
echo CHtml::dropDownList("teamMessages", '', array(), array('prompt'=>'Select Messages'));
?>
</div>
<!--
Only works for coaches
Allows coaches to submit team messages.
-->
<?php if ($model->isCoach()) { ?>
<!-- Text area for the coach to enter messages in -->
<textarea name="addTeamMessage" class="span5" rows="5" style="resize: none;"></textarea>
<!-- submit button -->
<?php echo CHtml::submitButton('Submit Message', array(
'class' => 'btn btn-primary',
'name' => 'submitTeamMessage'
)); ?>
<?php } ?>
<!-- end the widget. everything will be send to UserController/AddTeamMessages -->
<?php $this->endWidget(); ?>
controller when the activeform is surppose to be trigger.
/* add a team message submitted by the coach of the team */
public function actionAddTeamMessage($id)
{
/* check if team and message aren't null */
if(isset($_POST['submitTeamMessage']))
{
if(isset($_POST['teamId']['addTeamMessage']))
{
try
{
/* creates a new message */
$teamModel = new TeamMessage;
$teamModel->teamId = $_POST['teamId'];
$teamModel->content = $_POST['addTeamMessage'];
$teamModel->sendTime = new CDbExpression('NOW()');
$teamModel->save();
}
catch(Exception $e)
{
echo "Unable to save.";
}
}
}
/* render the profile page for the current user */
$user=User::model()->findByPk($id);
$this->render('profile', array(
'model' => $user));
}

Is it also sending the data when you go to the page when logged in as a Coach?
if not:
the problem is likely to be the submit button, since the active form can't be submitted.
place it outside of the isCoach if statement.
<?php if ($model->isCoach()) { ?>
<!-- Text area for the coach to enter messages in -->
<textarea name="addTeamMessage" class="span5" rows="5" style="resize: none;"></textarea>
<?php } ?>
<!-- submit button -->
<?php echo CHtml::submitButton('Submit Message', array(
'class' => 'btn btn-primary',
'name' => 'submitTeamMessage'
)); ?>

Related

Yii Ajax Validation in widget not working

I'm using Ajax validation in my widget. here is the code.
Widget function
public function run(){
if(!Yii::app()->user->isGuest){
$this->controller->redirect('/');
}
$model= new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
// blah blah.......
Widget View:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=> true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<div class="row">
<?php echo $form->textField($model,'username',array('placeholder'=>'email','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login', array('class'=>'btn btn-primary btn-block')); ?>
</div>
...
Right now the form is not submitting. After I click login nothing happens.
If I make enableAjaxValidation fale, form works but not AJAX.
If I make enableClientValidation false, form works but still no AJAX.
Any ideas? Thanks.
The thing is you are using a single submit button, instead of an ajax submit button.
For this, you may use, for example, an ajaxSubmitButton widget from Yii Bootstrap (or Yii booster).
So, in the SiteController :
...
$model= new LoginForm;
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['LoginForm']))
{
$model->unsetAttributes();
$model->attributes=$_POST['LoginForm'];
if($model->validate() && $model->login())
{
$array = array('login' => 'success');
$json = json_encode($array);
echo $json;
Yii::app()->end();
}
else{ //This is the important point
if(Yii::app()->getRequest()->getIsAjaxRequest())
{
$array=$model->getErrors();
$json = json_encode($array);
echo $json; //JSON containing the errors set in /models/LoginForm.php
Yii::app()->end();
}
}
}
...
In your view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=> true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
?>
<div class="row">
<?php echo $form->textField($model,'username',array('placeholder'=>'email','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row" >
<?php
/** THIS IS THE AJAX SUBMIT BUTTON **/
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType' => 'ajaxSubmit',
'label' => 'Login',
'ajaxOptions' => array(
'success' =>
'function(data){
var obj = $.parseJSON(data);
if(obj.login=="success"){
//...
// $(location).attr("href","BASEURL/someController/someAction")
}
else{
if("username" in obj){
$("#LoginForm_username_em_").text(obj.username[0]);
$("#LoginForm_username_em_").show();
$("#LoginForm_username").css({"background":"#FEE","border-color":"#C00"});
}
if("password" in obj){
$("#LoginForm_password_em_").text(obj.password[0]);
$("#LoginForm_password").css({"display":"block"});
$("#LoginForm_password").css({"background":"#FEE","border-color":"#C00"});
}
$("#LoginForm_password_em_").show();
}
}'),
));
?>
</div>
In order to use the ajaxSubmitButton widget of Yii Bootstrap (or Yii Booster), you have to download it from http://yiibooster.clevertech.biz/, extract it in your /protected/extensions folder and include it in /protected/config/main.php :
...
Yii::setPathOfAlias('bootstrap',dirname(__FILE__).'/../extensions/bootstrap'); //booster insead of bootstrap if you download the Yii Booster.
return array(
...
'components'=>array(
...
'bootstrap'=>array(
'class'=>'ext.bootstrap.components.Bootstrap', // assuming you extracted bootstrap under extensions
),
)
)
Yii Booster has many other widgets, for this reason I use it. If you don't want to use Yii booster for the ajax submit button, just use the CHtml::ajaxSubmitButton
Ajax validation needs a bit of care.
Please check response at console for ajax call. In ajax validation the output of ajax call should be pure json. In case of ajax validation from widget may include some html with response of ajax call.
have a look at http://www.yiiframework.com/forum/index.php/topic/12222-ajax-validation-in-widget-does-not-work/ hope it may help you.

Cjuiautocomplete on a CActiveForm in a Create method in yii

Brief explanation of what I'm trying to do. I am trying to implement an autocomplete in a create form. I know this seems strange but the table that is being added to is a list of "out of office" people. So my autocomplete looks up user names on the user table, my actionCreate, can use the Last, First to look up the user id and add them to the table. This all works fine. I can see the autocomplete. The issue is this:
When I type in a partial name the list of names pops up but i cannot select from them. Whenever I mouse over the drop down the list disapears, the same thing happens when I press "down".
Here is the code for the form. I have tried multiple different ways of implementing an autocomplete and so far this one works the best I am just unable to get the autocomplete to fill the field.
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'away-mentor-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo "Last-Name, First-Name"; ?><br/>
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'name_search',
'value'=>$model->name_search,
'source'=>Yii::app()->createUrl('/AwayMentor/FindUserName'),// <- path to controller which returns dynamic data
// additional javascript options for the autocomplete plugin
'options'=>array(
'minLength'=>'1', // min chars to start search
'select'=>'js:function(event, ui) { console.log(ui.item.id +":"+ui.item.value); }'
),
'htmlOptions'=>array(
'id'=>'name_search',
'rel'=>'val',
),
));
echo $form->error($model,'name_search'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
Try Something Like: -
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'name_search',
'value' => $model->name_search,
'source' => Yii::app()->createUrl('/AwayMentor/FindUserName'), // <- path to controller which returns dynamic data
// additional javascript options for the autocomplete plugin
'options' => array(
'minLength' => '1', // min chars to start search
'select' => "js: function(event, data) {
$('#name_search').val(data.item.value);
$(this).data('id',data.item.id);
return false;
}",
'focus' => "js: function(event,data){
$(this).val(data.item.value);
return false;
}"
),
'htmlOptions' => array(
'id' => 'name_search',
'rel' => 'val',
),
));
echo $form->error($model, 'name_search');
Yii::app()->clientScript->registerScript('autocomplete', "
jQuery('#name_search').data('autocomplete')._renderItem = function( ul, item ) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a>' + item.value + '<br><i>' + item.id + '</i></a>')
.appendTo(ul);
};",
CClientScript::POS_READY
);
?>

Get data from dropdownlist and insert the value in dataBase

I am trying to get a value from a drop-down list in order to insert in a table in my dataBase. I am using ajax in order to capture this value and draw a button that will insert the value in my database when the user clicks on it.
This is my code :
Yii::app()->clientScript->registerScript('register_script_name', "
$('#editButton').click(function(){
alert('edit');
return false;
});
", CClientScript::POS_READY);
<div class="row">
<?php echo $form->labelEx($model,'Escolha a opção correta <span class="required">*</span>')?>
<?php echo $form->dropDownList($model, 'Opcoes_idOpcoes',$this->getOpcoesResposta(),
array(
'ajax' => array(
'type' => 'POST',
'url'=>$this->createUrl('perguntaOpcoes/State'),
'data'=>array('Opcoes_idOpcoes'=>'js: $(this).val()'),
'update' => '#data',
)
));
?>
</div>
<div id="data">
</div>
And this is my code in controller:
public function actionState()
{
$data= $_POST['Opcoes_idOpcoes'];
echo CHtml::button("Edit",array('title'=>"Edit",'id'=>"editButton",'onclick'=>'edit()'));
}
Can anyone help me ?

How can I make a gridView in yii-booster bootstrap widget with popups for buttons in one of its column

I am a fresher in Yii, I need to make a gridView for employee details in Yii, for that I have followed the procedures mentioned in http://yii-booster.clevertech.biz/components.html#tables.
And I have created a gridView with some sample data, exactly like clevertech.biz has done, and i succeeded in that. But my actual requirement is to make a gridView with popup windows for viewing and editing employee details and a javascript confirmation before deleting entries. Here is my code, that created a grid and a popup window but the actions for each button is not separated, the popup works for the entire cell under a particular column, not for a button in that cell. Can anyone help me to resolve this issue?
$stu->id = 3;
$stu->name = 'Stu';
$stu->address = 'Dent';
$stu->position = 'SE';
$stu->joinDate = '2012-12-14';
$stu->age = 30;
$stu->phone = 1112226789;
$persons = array($mark, $jacob, $stu);
$gridDataProvider = new CArrayDataProvider($persons);
// $gridColumns
$gridColumns = array(
array('name'=>'id', 'header'=>'#', 'htmlOptions'=>array('style'=>'width: 60px')),
array('name'=>'name', 'header'=>'Name'),
array('name'=>'address', 'header'=>'Address'),
array('name'=>'position', 'header'=>'Position'),
array('name'=>'joinDate', 'header'=>'Join Date'),
array('name'=>'age', 'header'=>'Age'),
array('name'=>'phone', 'header'=>'Phone'),
array('header'=>'Options',
'htmlOptions' => array('data-toggle'=>'modal',
'data-target'=>'#myModal'),
'class'=>'bootstrap.widgets.TbButtonColumn',
'viewButtonUrl'=>null,
'updateButtonUrl'=>null,
'deleteButtonUrl'=>null,),
);
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'type'=>'bordered',
'dataProvider'=>$gridDataProvider,
'template'=>"{items}",
'columns'=>$gridColumns,
));
?>
<!-- View Popup -->
<?php
$this->beginWidget('bootstrap.widgets.TbModal', array('id'=>'myModal')); ?>
<!-- Popup Header -->
<div class="modal-header">
<h4>View Employee Details</h4>
</div>
<!-- Popup Content -->
<div class="modal-body">
<p>Employee Details</p>
</div>
<!-- Popup Footer -->
<div class="modal-footer">
<!-- save button -->
<?php $this->widget('bootstrap.widgets.TbButton', array(
'type'=>'primary',
'label'=>'Save',
'url'=>'#',
'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
<!-- save button end-->
<!-- close button -->
<?php $this->widget('bootstrap.widgets.TbButton', array(
'label'=>'Close',
'url'=>'#',
'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
<!-- close button ends-->
</div>
<?php $this->endWidget(); ?>
<!-- View Popup ends -->
My columns its a little bit different but i think you'll understand.
You'll have to change your TbButtonColumn this way:
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'type'=>'bordered',
'dataProvider'=>$model->search(),
'filter'=>$model,
'template'=>"{items}",
'columns'=>array(
'id',
'firstName',
'lastName',
'language',
'hours',
array(
'header'=>'Options',
'class'=>'bootstrap.widgets.TbButtonColumn',
'buttons'=>array(
'view'=>
array(
'url'=>'Yii::app()->createUrl("person/view", array("id"=>$data->id))',
'options'=>array(
'ajax'=>array(
'type'=>'POST',
'url'=>"js:$(this).attr('href')",
'success'=>'function(data) { $("#viewModal .modal-body p").html(data); $("#viewModal").modal(); }'
),
),
),
),
)
)));
?>
<!-- View Popup -->
<?php $this->beginWidget('bootstrap.widgets.TbModal', array('id'=>'viewModal')); ?>
<!-- Popup Header -->
<div class="modal-header">
<h4>View Employee Details</h4>
</div>
<!-- Popup Content -->
<div class="modal-body">
<p>Employee Details</p>
</div>
<!-- Popup Footer -->
<div class="modal-footer">
<!-- close button -->
<?php $this->widget('bootstrap.widgets.TbButton', array(
'label'=>'Close',
'url'=>'#',
'htmlOptions'=>array('data-dismiss'=>'modal'),
)); ?>
<!-- close button ends-->
</div>
<?php $this->endWidget(); ?>
<!-- View Popup ends -->
and your actionView from your personController this way:
public function actionView($id)
{
if( Yii::app()->request->isAjaxRequest )
{
$this->renderPartial('view',array(
'model'=>$this->loadModel($id),
), false, true);
}
else
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
}
and then, all you have to do it's do the same thing with your update.
If you can't understand anything, feel free to ask any question.
Refer: TbButtonColumn class file (TbButtonColumn.php)
#param array $button the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements.
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
'buttons'=>array(
'view'=>array(
'visible'=>'true/false',
'label'=>'Description',
'url'=>'link',
'imageUrl'=>'linkImage',
'options'=>array(
),
),
),
),

Displaying error messages

I'm using Codeigniter framework to create my web application.
I have a login form for the users to input their username and password as well as a remember me checkbox. After the user submits the form it uses jQuery ajax to submit the form and send the post data to the login controller submit function for data checking and manipulation. After the submit function is ran a JSON array is returned if the user was logged in. If the user is successfully logged in he/she is sent to the dashboard and if they weren't logged in successfully then an error message is displayed and under each of the user inputs displays the corresponding message to the rule that didn't pass the CI form validation rules.
As of right now it displays a message saying it didn't pass validation but I'm having an issue with figuring out how to display the validation rule that didn't pass under the user input box.
<div style="display:none" id="message_container"><button type="button" class="close" data-dismiss="alert">×</button></div>
<div class="login_container">
<?php $attributes = array('id' => 'login_form', 'class' => 'form-horizontal'); ?>
<?php echo form_open('login/submit', $attributes); ?>
<div class="form-row row-fluid">
<div class="spa12">
<div class="row-fluid">
<?php $attributes = array('class' => 'form_label span12'); ?>
<?php echo form_label('Username<span class="icon16 icomoon-icon-user-3 right gray marginR10"></span>', 'username', $attributes); ?>
<?php $attributes = array('name' => 'username', 'id' => 'username', 'value' => '', 'class' => 'span12 text valid'); ?>
<?php echo form_input($attributes); ?>
</div>
</div>
</div>
<div class="form-row row-fluid">
<div class="span12">
<div class="row-fluid">
<?php $attributes = array('class' => 'form_label span12'); ?>
<?php echo form_label('Password<span class="icon16 icomoon-icon-locked right gray marginR10"></span><span class="forgot">Forgot your password?</span>', 'password', $attributes); ?>
<?php $attributes = array('name' => 'password', 'id' => 'password', 'value' => '', 'class' => 'span12 password'); ?>
<?php echo form_password($attributes); ?>
</div>
</div>
</div>
<div class="form-row row-fluid">
<div class="span12">
<div class="row-fluid">
<div class="form-actions">
<div class="span12 controls">
<input type="checkbox" id="keepLoged" value="Value" class="styled" name="logged" />Keep me logged in
<button type="submit" class="btn btn-info right" id="loginBtn">
<span class="icon16 icomoon-icon-enter white"></span>
Login
</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
public function submit()
{
$output_status = 'Notice';
$output_title = 'Not Processed';
$output_message = 'The request was unprocessed!';
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_check_username');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember Me', 'trim|xss_clean|integer');
if ($this->form_validation->run() == TRUE)
{
}
else
{
$output_status = 'Error';
$output_title = 'Form Not Validated';
$output_message = 'The form did not validate successfully!';
}
echo json_encode(array('output_status' => $output_status, 'output_title' => $output_title, 'output_message' => $output_message));
}
public function check_username($str)
{
if (preg_match('#[0-9]#', $str) && preg_match('#[a-z]#', $str))
{
return TRUE;
}
$this->form_validation->set_message('check_username', 'This is not have an accepted value!');
return FALSE;
}
EDIT:
"error_messages":{"username":"This is not have an accepted value!"}}
Since I'm submitting this form via jQuery ajax function I'm trying to figure out how I'm going to make my if statement. Take into consideration I'll have multiple inputs that will have to be placed under each text field unless there's a better idea.
If all you are trying to do is append the string of error messages to your $output_message you might be able to do this:
$output_message = 'The form did not validate successfully! Errors: ' . $this->form_validation->error_string();
You can set custom error messages using:
$this->form_validation->set_message('username', 'Invalid Username');
Edit as per your comment, if you want to send back the error messages you should try something like this:
echo json_encode(array('output_status' => $output_status, 'output_title' => $output_title, 'output_message' => $output_message, 'error_messages' => $this->form_validation->error_array()));
And to display those error messages I would add placeholders in your html and append the message there
CodeIgniters Form Validation Library Source:
/**
* Get Array of Error Messages
*
* Returns the error messages as an array
*
* #return array
*/
public function error_array()
{
return $this->_error_array;
}
So it seems this is a new addition coming in Version 3.0, so for now you could just extend the Form Validation Library by adding a file inside your application/libraries/ and name it MY_Form_validation.php and inside it place this:
class MY_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
/**
* Get Array of Error Messages
*
* Returns the error messages as an array
*
* #return array
*/
public function error_array()
{
return $this->_error_array;
}
}

Categories