I have created a form using CActiveForm in yii. I am using ajax to submit the form using CHtml::ajaxSubmitButton. Form submission using ajax is working correctly and I am able to get the values in the control using $_POST['modelname']['fieldname']. But the ajax form validation is not working correctly. Below is the code
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'item-brand-form',
'enableAjaxValidation' => true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
'htmlOptions'=>array(
'class'=>'form-horizontal',
),
)); ?>
<div class="form-group">
<?php echo $form->labelEx($model,'Brand Name',array('class'=>'control-label col-lg-4','for'=>'ItemBrand_brand_name')); ?>
<div class="col-lg-6">
<?php echo $form->textField($model,'brand_name',array('class'=>'form-control')); ?>
<?php echo $form->error($model,'brand_name'); ?>
</div>
<!-- End col-lg-6 -->
</div><!-- End Form Group -->
<div class="form-group">
<?php echo $form->labelEx($model,'Brand Code',array('class'=>'control-label col-lg-4','for'=>'ItemBrand_brand_code')); ?>
<div class="col-lg-6">
<?php echo $form->textField($model,'brand_code',array('class'=>'form-control')); ?>
</div>
<!-- End col-lg-6 -->
</div><!-- End Form Group -->
<div class="form-group">
<div class="col-lg-4"></div>
<div class="col-lg-2">
<?php echo CHtml::ajaxSubmitButton('Apply',array('class'=>'btn btn-lg btn-primary')); ?>
</div>
</div>
<?php $this->endWidget(); ?>
Also in the controller action following code is not working.
if(isset($_POST['ajax']) && $_POST['ajax']==='item-brand-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
so instead I am using
if(Yii::app()->getRequest()->getIsAjaxRequest())
{
echo CActiveForm::validate( array( $model));
Yii::app()->end();
}
While checking in the browser I am getting the response
{"ItemBrand_brand_name":["Brand Name cannot be blank."]}
But the error message is not displaying in the form. Also why the $_POST['ajax'] is not working ? Please help.
Thanks in advance.
I have solved this by using CHtml::submitButton instead of CHtml::ajaxSubmitButton and then submitting the form using jQuery $.ajax function in the form 'afterValidate' option. Please see the details here
Related
In view I have a form:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true, 'placeholder' => 'Name'])->label(false) ?>
<?= $form->field($model, 'phone')->textInput(['maxlength' => true, 'placeholder' => 'Phone'])->label(false) ?>
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Controller is:
if ($model->load(Yii::$app->request->post()) && $model->save()) {
\Yii::$app->session->setFlash('success', 'Created');
}
return $this->redirect(Yii::$app->request->referrer);
Then in view I put a modal:
<?php if (Yii::$app->session->hasFlash('success')) :?>
<!-- <div class="container">
<?= Yii::$app->session->getFlash('success', null, true) ?>
</div> -->
<div class="modal hide fade" id="myModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p><?= Yii::$app->session->getFlash('success', null, true) ?></p>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
<?php endif ;?>
And JS code is:
$(window).load(function(){
$('#myModal').modal('show');
});
I want to open success modal window after clicking submit button. But now nothing happens. Just reloads the page. How to do that I want? And please explain how to do that without reloading the page.
This might be no the best decidion, but i use class myAjaxModalClass and a simple js code, that submit all form with that class via ajax and parse json result:
{result:0, data:'new modal content'}
That allows me to load form with validation erros without page reloading. Also you may add your result status to submit redirect. Expample:
{result: 2, url:'http://yoursite.net'}
I have an application where user has to fill a lengthy form, so I split the form into three and created steps - Step 1, Step 2 etc. So it has to be convenient for users. Now I face a problem, after filling out the details, a text field shows an error. When using model->get Errors() the error is 'address cannot be blank'. When I use $_POST the arrays displays value for the field address. I started yii framework last week and I do not know where I have gone wrong. Any help appreciated.
The view code i use forloop to reduce my code -
<fieldset>
<?php if(!Yii::app()->user->hasFlash('success')):
Yii::app()->user->setFlash('warning','All Fields are mandatory!');
endif; ?>
<?php echo CHtml::errorSummary($model, null, null, array(
'class' => 'alert alert-danger col-lg-offset-2',
)); ?>
<?php $rrr = -1;
foreach($model->attributeLabels() as $a){ $rrr++;
if($rrr<27 && $rrr>=12){
?>
<div class="form-group">
<?php echo CHtml::activeLabel($model, $a, array('class' => 'col-lg-3 control-label')); ?>
<div class="col-lg-7">
<?php echo CHtml::activeTextField($model,array_keys($model->attributeLabels())[$rrr],array('value'=>'a','size'=>255,'maxlength'=>255,'class'=>'form-control formtype1')); ?>
</div>
</div>
<?php
}}
?>
<?php $rrr = -1;
foreach($model2->attributeLabels() as $a){ $rrr++;
if($rrr>1 && $rrr<6){
?>
<div class="form-group">
<?php echo CHtml::activeLabel($model2, $a, array('class' => 'col-lg-3 control-label')); ?>
<div class="col-lg-7">
<?php echo CHtml::activeTextField($model2,array_keys($model2->attributeLabels())[$rrr],array('value'=>'a','size'=>255,'maxlength'=>255,'class'=>'form-control formtype1')); ?>
</div>
</div>
<?php
}}
?>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button class="btn btn-sm btn-primary" type="submit"><?php echo Yii::t("user", "Submit") ?></button>
</div>
</div>
</fieldset>
</form>
So I am having trouble with the form_submit in codeigniter. I have a controller named welcome with a method named email. Whenever I hit my submit button the page refreshes but then just appends ?firstname=&email=&message=&submit=Submit to my url but doesn't carry out the method. Any reason this may be happening?
below is my html code.
<form role="form">
<div class="form-group">
<label>Name</label>
<?php $this->load->helper("form"); ?>
<?php echo validation_errors('<p class = "error">'); ?>
<?php echo form_open('welcome/email');
$data = array('type'=>'text','class'=>'form-control', 'name'=>'firstname');
echo form_input($data);
?>
</div>
<div class="form-group">
<label>Email</label>
<?php
$data = array('type'=>'email','class'=>'form-control', 'name'=>'email');
echo form_input($data);
?>
</div>
<div class="form-group">
<label>Message</label>
<?php
$data= array('type'=>'text','name'=>'message','class'=>'form-control','rows'=>7);
echo form_textarea($data);
?>
</div>
<div class="pull-right">
<!--<button type="submit" class="btn btn-custom btn-lg" action="welcome/email">Submit</button> -->
<?php
echo form_submit('submit','Submit');
echo form_close();
?>
</div>
This is my controller
<?php /*if ( ! defined('BASEPATH')) exit('No direct script access allowed');*/
class Welcome extends CI_Controller {
function index(){
$this->load->view('index-sidebar');
}
function email(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email Address','required|valid_email');
$this->form_validation->set_rules('firstname', 'Name', 'required|min_length[2]|max_length[30]');
$this->form_validation->set_rules('message', 'Message', 'required|min_length[5]|max_length[200]');
if ($this->form_validation->run()==FALSE){
$this->load->view('message not sent');
}
else{
$this->load->library('email');
$this->email->from(set_value('email'),set_value('name'));
$this->email->to("mhansen1989#gmail.com");
$this->email->subject('tutoring');
$this->email->message(set_value('message'));
$this->email->send();
echo $this->email->print_debugger();
$this->load->view('success');
}
}
}
there is no action parameter in your form tag.how do you submit the form?
try this
<form action="<?= base_url().'welcome/email'?>" role="form" method="post">
so here
if ($this->form_validation->run()==FALSE){
$this->load->view('message not sent');
}
put in your correct view name where it says 'message not sent'
$this->load->helper("form");
load your helpers in the controller -- better yet do it config/autoload
and this
$data = array('type'=>'text','class'=>'form-control','name'=>'firstname');
echo form_input($data);
in the form you repeat $data over and over. technically it will work but its going to mess up at some point so make them different names
$first = array('type'=>'text','class'=>'form-control','name'=>'firstname');
echo form_input($first);
and you need something to show the values in the form again if the validation is false. check out http://www.codeigniter.com/user_guide/libraries/form_validation.html#repopulatingform
I'm using Twitter bootstrap 3 and CodeIgniter. In my website I have a list of posts on the left and a sidebar column of the right. In this sidebar I have a search box with input field and a dropdown, another box with a list of 10 popular posts, and another box with a list of categories.
I would like to move only the search box of the sidebar to the top of the site in smaller screen devices. Because it's a search box I would like it to show first and then the posts in mobile view.
I am having trouble doing this. I've managed to reorder the columns, but it's not the result is that the entire column shows first, and I want the search box on top.
Any suggestions?
pull-left and pull-right did not work for me, or I was unable to make it work. Would using classes with hidden and show values be a better approach?
This is my template for post view
<div class="container">
<div class="row">
<div class="col-sm-8">
<div id="content" class="content-page">
<h2><?php echo $title; ?></h2>
<?php echo $content; ?>
</div> <!-- // content -->
</div><!-- // col-sm-8 -->
<div class="col-lg-4">
<?php $this->load->view('templates/posts_sidebar');?>
</div><!-- // col-lg-4 -->
</div><!-- // row -->
<hr>
</div><!-- // container -->
Sidebar search view is:
<div class="well post_search">
<?php $attributes = array('id' => 'search', 'role' => 'form', 'autocomplete' => 'off'); ?>
<?php echo form_open('posts/filter', $attributes); ?>
<div class="form-group">
<h4><label for="title"><i class="fa fa-search"></i> <?php echo $text_posts_sidebar_search; ?></label></h4>
<div class="input-group">
<?php echo form_input('title', set_value('title', $this->input->get('title')), 'class="form-control" id="title" placeholder="'.$text_posts_sidebar_search_placeholder.'"'); ?>
<span class="input-group-btn">
<?php echo bt_submit('', '<span class="fa fa-search"></span>', 'btn btn-default'); ?>
</span>
</div>
</div>
<div class="form-group">
<label for="parent_id"><i class="fa fa-folder-open-o"></i> <?php echo $text_posts_sidebar_search_in; ?></label>
<?php echo form_dropdown('parent_id', $dropdown_postcategories, $this->input->get('parent_id') ? $this->input->get('parent_id') : '', 'id="parent_id" class="form-control"'); ?>
</div>
<!-- // input-group -->
<?php echo form_close(); ?>
</div><!-- /well -->
Okay, I sorted my issue.
Just in case this is helpfull for someone else.
In my template I actually have two search forms now.
One visible and one hidden.
Depending on screen resolution, using media querys I show or hide what I need.
I can access the registration form which appears in a model window via ajax on any page as coded in the menu layout .
I need some thing on click of submit button of registration form it should get display a thank you message which is also via ajaxin the same div as that of wherein the registration form appears
registratiincontrooler
if ($model->save()) {echo "thank you for registration";return; }
registration view
<?php
/* #var $this UserProfileController */
/* #var $model UserProfile */
$this->breadcrumbs=array(
'User Profiles'=>array('index'),
'Create',
);
?>
<div id="ajax101" >
<div class="form" >
<?php $form=$this->beginWidget('UActiveForm', array(
'id'=>'registration-form',
'enableAjaxValidation'=>true,
'disableAjaxValidationAttributes'=>array('RegistrationForm_verifyCode'),
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
'htmlOptions' => array('enctype'=>'multipart/form-data'),
)); ?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $form->errorSummary(array($model/*,$profile*/)); ?>
<div class="row">
<div class="rlabel">
<?php echo $form->labelEx($model,'username', array("style"=>"display:inline")); ?>
</div>
<div class="rtextfield">
<?php echo $form->textField($model,'username', array("style"=>"margin-left:43px")); ?>
</div>
<div class="rerror">
<?php echo $form->error($model,'username', array("style"=>"margin-left:113px")); ?>
</div>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password', array("style"=>"display:inline")); ?>
<?php echo $form->passwordField($model,'password', array("style"=>"margin-left:43px")); ?>
<?php echo $form->error($model,'password', array("style"=>"margin-left:113px")); ?>
<p class="hint">
<?php echo UserModule::t("Minimal password length 4 symbols."); ?>
</p>
</div>
<div class="row">
<?php echo $form->labelEx($model,'verifyPassword', array("style"=>"display:inline")); ?>
<?php echo $form->passwordField($model,'verifyPassword'); ?>
<?php echo $form->error($model,'verifyPassword', array("style"=>"margin-left:113px")); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email', array("style"=>"display:inline")); ?>
<?php echo $form->textField($model,'email', array("style"=>"margin-left:65px")); ?>
<?php echo $form->error($model,'email', array("style"=>"margin-left:113px")); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'user_type', array("style"=>"display:inline")); ?>
<?php echo $form->dropDownList($model,'user_type',$model->getUType()); ?>
<?php echo $form->error($model,'user_type', array("style"=>"margin-left:113px")); ?>
</div>
<?php if (UserModule::doCaptcha('registration')): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
<?php echo $form->error($model,'verifyCode'); ?>
<p class="hint"><?php echo UserModule::t("Please enter the letters as they are shown in the image above."); ?>
<br/><?php echo UserModule::t("Letters are not case-sensitive."); ?></p>
</div>
<?php endif; ?>
<div class="row submit">
<?php echo CHtml::ajaxSubmitButton(UserModule::t("Register"),array('/user/register'),array('update'=>'#ajax101')); ?>//div for form
</div>
<?php $this->endWidget(); ?>
</div>
</div><!-- form -->
<?php endif; ?>
I think the problem exists here
<?php echo CHtml::ajaxSubmitButton(UserModule::t("Register"),array('/user/register'),array('update'=>'form')); ?>//div for form
</div>
example if I have 3 menu items
home
aboutus
contact
suppose visited home when I click on register a model window with registration form appears and when i click on submit button model->save as well make another call using ajax to update that model window with thank you message
similarly with other items in menu
whats happening is it saves and redirects to /user/registration with thank you but i need same model window and not to be updated with thank message and not redirected thank message
I did try this but it did not save
<?php echo CHtml::ajaxSubmitButton(UserModule::t("Register"),'',array('update'=>'form-content')); ?>
I am calling ajax within ajax .
try with
<?php
echo CHtml::ajaxSubmitButton(signup , CHtml::normalizeUrl(array('<controller>/<action>', 'render' => true)), array(
'dataType' => 'json',
'type' => 'post',
'success' => 'function(data) {
}',
'beforeSend' => 'function(){
}','complete' => 'function(){
}',
), array('id' => 'signup', 'class' => ''));
?>
The problem is in your controller, you have to stop Yii, return; alone won't cut it.
if ($model->save()) {
if($this->isAjaxRequest)
{
ehco 'thank you for registration';
Yii::app()->end(); // to stop yii
}
else
{
// probably redirect
}
}