Zend 2.2 form submit success message using flashMessenger? - php

I am trying to do simple contact us page with flashmessenger helper plugin.
I have implemented it as below, but my problem is i have to submit the form twice to get the flashmessagers showing in the page.
What i am i doing wrong here ..
show the messages on the first submit ?
how do i hide the form the after submit ?
in my controller
// Add content to this method:
public function contactAction()
{
$form = new ContactForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
if ($request->isPost()) {
$contact = new Contact();
$form->setInputFilter($contact->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$data=$form->getData();
//var_dump($data);
$mail = new Mail\Message();
$mail->setBody($data['comment'])
->setFrom($data['email'], $data['name'])
->addTo(IEMAIL, COMPANY )
->addReplyTo($data['email'], $data['name'])
->setSubject($data['subject']);
$transport = new Mail\Transport\Sendmail();
$transport->send($mail);
$this->flashMessenger()->addMessage('Thanks you for the submission ');
}
else{
$this->flashMessenger()->addMessage('Opps somethinge went wrong ..!');
}
}
/**/
return new ViewModel(array(
'customMessage' => 'Welcome to the sales',
'form' => $form
));
}
IN my view i have the coding as
<?php
$title = 'Contact Us';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php echo $this->customMessage ?>
<?php
if ($this->flashMessenger()->hasMessages()):
echo $this->flashMessenger()->render('success', array('alert', 'alert-danger'));
// In any of your .phtml files:
$flash = $this->flashMessenger();
$flash->setMessageOpenFormat('<div%s>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×
</button>
<ul><li>')
->setMessageSeparatorString('</li><li>')
->setMessageCloseString('</li></ul></div>');
echo $flash->render('error', array('alert', 'alert-dismissable', 'alert-danger'));
echo $flash->render('info', array('alert', 'alert-dismissable', 'alert-info'));
echo $flash->render('default', array('alert', 'alert-dismissable', 'alert-warning'));
echo $flash->render('success', array('alert', 'alert-dismissable', 'alert-success'));
?>
<? endif ?>
<?php
$form->setAttribute('action', $this->url('contact', array('action' => 'submit')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('subject'));
echo $this->formRow($form->get('comment'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

The flash messenger does not work in the way you are expecting. It is designed for showing messages to the user after a redirect. To do this it adds any messages you pass to it to a session container so they can be retrieved on the next request. This behaviour (Post/Redirect/Get) is a common pattern in web applications as it reduces of the chance of a user accidentally re-submitting form submissions by refreshing the page.
If you add a redirect after your $transport->send($mail);, then the successful submissions should work how you expect. For the failed ones to work you'll need to write your own helper that does same-request messaging as well (which is what I normally do). Instead you might want to get rid of the fail message and just let the form's inbuilt error messaging do its thing.

Change this code in controller...
$message = '';
$flashMessenger = $this->flashMessenger();
if ($flashMessenger->hasMessages()) {
$message = $flashMessenger->getMessages();
}
And in View
<?php if(is_array($message) && count($message) > 0){
foreach($message as $messageKey => $messageValue){?>
<div style= "color:red"> <?php echo $messageValue; ?> </div>
<?php } } ?>

Related

Handle unique values in tabular input

Hope you all doing fine.
Scenario
I have a junction model resumeSkills that takes the id of resume and the id of skill from different tables and another field "proficiency level" to determine the expertise in that particular skill.
I have multiple instances of this model loaded in my page based on "Add New" button click (which triggers a Jquery AJAX callback which interns, creates a model against given index counter).
Every model instance is validated based on model rules defined so it works fine if I have different values selected for every instance created.
Target
Now, I want to add skills in a way that If I select "php" in any model-instance in my view either I am not able to select "php" in any of newly generated model-instances or I don't see in there respective drop-down/tags.
Problem
Now if I select the same value for multiple instances (above figure), Validation fails against second or later record as I have rule that skills can not be duplicated against a resume.
This is where I need Help from the community.
Here is my controller action method to add new model instance (record) in the view (append the content container)
public function actionAddNewRecord($idresume, $index)
{
$model = new OresumeResumeSkill();
$model->idresume = $idresume;
$model->isDeleted = 0;
$model->isFromDb = 0;
$response = [];
$response['content'] = $this->renderPartial('_partials/_add_new_form', [
'model' => $model, 'i'=>$index
]);
return Json::encode($response);
}
Here is the code to my main partial file:
_edit_file.php
<div class="row">
<!-- container that has form and its operations in it -->
<div class="col-xs-12">
<?php
$form = ActiveForm::begin([
'id' => 'form_edit_resume_skill_multiple',
'options' => [
'enctype' => 'multipart/form-data',
'class' => 'section_form',
],
]);
?>
<div id="add_new_record_container">
<!--
Add new Item related item_container will be placed in here dynamically in parallel
This loaded content is based on _add_new_form partial view
Content is added via AJAX request caused by btn_add_new_record
-->
</div>
<div class="row form_controls">
<div class="col-xs-12 text-right">
<input type="hidden" name="hdnCounter" id="hdnCounter" value="<?php echo count($skills); ?>" />
<?php echo Html::a(T::t('main', 'Add New'), ['/oresume/resume-skill/add-new-record', 'idresume'=>$model_resume->idresume], ['id'=>'btn_add_new_record', 'class'=>'btn btn-primary' ]); ?>
</div>
<div class="col-xs-12 text-right">
<?php echo Html::a(T::t('main', 'Cancel'), ['/oresume/attachment/discard-all-drafts'], ['class'=>'btn btn-default', 'id'=>'btnDiscardChanges', 'data'=>['confirm_message'=>T::t('main', 'Discard Changes?'), ] ]);?>
<?php echo Html::submitButton(T::t('main', 'Save Changes'), ['class' => 'btn btn-success']); ?>
</div>
</div>
<?php $attributes = Json::htmlEncode($form->attributes);?>
<script type="text/javascript">
jQuery(document).ready(function($){
<?php
$options = Json::htmlEncode($form->options);
$attributes = Json::htmlEncode($form->attributes);
?>
$("#<?php echo $form->options['id'];?>").yiiActiveForm(<?php echo $attributes;?>, <?php echo $options;?>);
$(".resume_skills").select2({
tags: true,
multiple: true,
maximumSelectionLength: 1,
language: "<?php echo \Yii::$app->language; ?>",
allowClear: true,
placeholder: {
idskill: "",
placeholder: "<?php echo T::t('main', 'Please select'); ?>"
},
});
var attributes = <?php echo $attributes;?>;
for(var i = 0; i < attributes.length; i++) {
$("#form_edit_resume_skill_multiple").yiiActiveForm('add', attributes[i]);
}
});
</script>
<?php ActiveForm::end(); ?>
</div>
<!-- //container that has form and its operations in it -->
</div>
Here is the code for my sub_partial file (to add a new model instance):
_add_new_form.php
$title = T::t('main', 'Add New Record');
$skills = OresumeSkill::listSkills();
$proficiencyLevels = OresumeResumeSkill::listProficiencyLevels();
$form = ActiveForm::begin();
?>
<div class="col-xs-12 item_container">
<div class="row single_value_row">
<div class="col-xs-6">
<?php echo $form->field($model, "[$i]idskill")->dropDownList($skills, ['style'=>['width'=>'100%'], 'class'=>'resume_skills', 'placeholder'=>T::t('main', 'Please select')]); ?>
</div>
<div class="col-xs-5">
<?php echo $form->field($model, "[$i]level")->dropDownList($proficiencyLevels, ['prompt' => T::t('main', 'Please Select')]); ?>
</div>
<div class="col-xs-1 text-left">
<button class="btn btn-danger pull-right btn_remove_record" id="btnRemoveResumeSkill-<?php echo $i;?>"><?php echo T::t('main', '<i class="fa fa-times"></i>'); ?></button>
<?php echo $form->field($model, "[$i]isDeleted")->hiddenInput(['class'=>'isDeleted_input'])->label(false); ?>
<?php echo $form->field($model, "[$i]isFromDb")->hiddenInput(['class'=>'isFromDb_input'])->label(false); ?>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#form_edit_resume_skill_multiple").yiiActiveForm('add', 'OresumeResumeSkill[<?php echo $i; ?>]');
$(".resume_skills").select2({
tags: true,
multiple: true,
maximumSelectionLength: 1,
language: "<?php echo \Yii::$app->language; ?>",
allowClear: true,
placeholder: {
idskill: "",
placeholder: "<?php echo T::t('main', 'Please select'); ?>"
},
});
<?php $attributes = Json::htmlEncode($form->attributes);?>
var attributes = <?php echo $attributes; ?>;
for(var i = 0; i < attributes.length; i++) {
$("#form_edit_resume_skill_multiple").yiiActiveForm('add', attributes[i]);
}
});
</script>
</div>
<?php ActiveForm::end(); ?>
And here is the code for my action that handles the dynamically generated models and save them in db.
Public function actionGetResumeSkills($idresume)
{
$model_resume = OresumeResume::findOne($idresume);
$models = OresumeResumeSkill::getResumeSkills($model_resume->idresume);
$response = [];
$postedArray = \Yii::$app->request->post('OresumeResumeSkill');
// print_r($postedArray);
if( count($postedArray) ) //case: Its a postback and we have some models in it
{
if(count($models) < count($postedArray) )//case: postback has more number of models as compared to in db
{
// Generate empty models array to be filled by loadMultiple() method of model class
// create emoty models and add in models array counter so that
// we've equal number of sent / recieved models for processing
for ($i=count($models); $i< count($postedArray); $i++ )
{
$model = new OresumeResumeSkill();
$model->idresume = $idresume;
$models[] = $model;
}
}
}
if( count($models) == 0) // we need to check if this array has something to process
{
$response['status'] = false;
$response['message'] = T::t('main', 'No records found to process');
}
if(OresumeResumeSkill::loadMultiple($models, \Yii::$app->request->post())) // load multiple models of models array
{
$status = true;
foreach ($models as $model)
{
// Delete models that are flaged to do so
// execute continue statement on deletion
// Validate and save models that are to be saved/updated
$model->idskill = OresumeResumeSkill::getSkill($model->idskill);
$model->level = ($model->level != null)? $model->level : OresumeResumeSkill::LEVEL_BEGINNER;
if( $model->validate() ) // Case: Model data is valid
{
// Save Model in database
$status &= $model->save();
}
else
{
$status = false;
// print_r($model->errors['idskill'][0]);
$response['message'] = T::t("main", "Storing of record \"{$model->idskill0->name}\" got some validation issues\n");
}
}
if($status)
{
$model_resume = OresumeResume::findOne($model->idresume);
$models = OresumeResumeSkill::getResumeSkills($model->idresume);
$response['status'] = true;
$response['content'] = $this->renderPartial('_partials/_edit_form', ['model_resume' => $model_resume, 'skills' => $models]);
$response['counter'] = count($models);
$response['message'] = T::t('main', 'Record(s) updated Successfully');
}
else
{
$response['status'] = false;
// $response['message'] = T::t('main', 'Records could not be updated.\n Something went wrong');
}
}
else // case: page loads for the first time
{
$response['content'] = $this->renderPartial('_partials/_edit_form', ['model_resume'=>$model_resume, 'skills' => $models]);
}
return Json::encode($response);
}
Any Help is Appreciated.
thankx in advance.
I'm reading this on a phone so there are a few parts of your code I'm not sure I totally get and I won't be able to type much. However, from my understanding, you don't want already selected skills to show up in next drop down.
You can have a hidden field to keep the IDs of selected skills (comma separated) and pass that as an argument to the listSkills method. Means your listSkills method will change a bit to accept a parameter.
In your listSkills method you have to use a where clause that says where skill ID NOT IN the list of IDs coming from the hidden field. Means you will be selecting back only the skills that have not been selected before into your array for the drop down.
Sorry I'm on a phone, I can't add code samples.

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.

Yii: Change login page

When we create a yii webapp using yiic, a login function is already made.
However, I want to use the navbar as a login widget (and bootstrap for design) as shown in here. That's when I encountered my problem. When I try to login using the toolbar/widget, the details I have input are displayed in the browser's bar and then nothing. See here.
This my LoginWidget.php
<?php class LoginWidget extends CWidget {
public function run() {
$model=new LoginForm;
$form= $this->beginWidget('CActiveForm', array(
'id'=>'login-form',
// 'action'=>
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
)
));
echo $form->errorSummary($model);
?>
<div class="form-group">
<?php echo $form->textField($model,'username',array('placeholder'=>'Employee Code','class'=>'form-control')); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="form-group">
<?php echo $form->passwordField($model,'password',array('placeholder'=>'Password','class'=>'form-control')); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<?php
echo CHtml::submitButton('Sign in', array('class'=>'btn btn-success'));
$this->endWidget();
}
} ?>
This is my Controller (just the necessary part).
public function actionIndex()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect('myprofile/index');
}
// display the login form
$this->render('index',array('model'=>$model));
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
// $this->render('index');
}
When I try to login using localhost/project/index.php/site/login, it works.
Make sure the form sends data with POST
$form= $this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'method' => 'POST',
'enableClientValidation'=>true,
'clientOptions'=>
array(
'validateOnSubmit'=>true,
)
));

Confirm box in CodeIgniter anchor link to delete record

I am using the following code to delete a record from a database. But I am facing a problem: when I click on "cancel" in the confirm box then it deletes the record. If I click cancel it returns false but how does it delete the record?
What am doing wrong?
Javascript code:
function ConfirmDialog() {
var x=confirm("Are you sure to delete record?")
if (x) {
return true;
} else {
return false;
}
}
PHP code in view:
<?php
echo anchor('user/deleteuser/'.$row->id, 'Delete', array('class'=>'delete', 'onclick'=>"return ConfirmDialog();"));
?>
Everything in one line
<?=anchor("user/deleteuser/".$row->id,"Delete",array('onclick' => "return confirm('Do you want delete this record')"))?>
Try This:
Delete
and use this in your script:
<script type="text/javascript">
var url="<?php echo base_url();?>";
function delete(id){
var r=confirm("Do you want to delete this?")
if (r==true)
window.location = url+"user/deleteuser/"+id;
else
return false;
}
</script>
Are you getting any Javascript errors in the console? I suspect that some other Javascript may be interfering. This simple test page works fine:
<?php echo anchor('user/deleteuser/'.$row->id, 'Delete', array('class'=>'delete', 'onclick'=>"return confirmDialog();")); ?>
<script>
function confirmDialog() {
return confirm("Are you sure you want to delete this record?")
}
</script>
In your View:
<?= anchor("admin/delete_article/{$article->id}", 'Test', ['name'=>'submit', 'value'=>'Delete', 'class'=>'btn btn-danger', 'onclick'=>'return confirm()']);
?>
OR
<?=
form_open('admin/delete_article'),
form_hidden('article_id', $article->id),
form_submit(['name'=>'submit', 'value'=>'Delete', 'class'=>'btn btn-danger', 'onclick'=>'return confirm()']),
form_close();
?>
JavaScript in your View:
<script>
function confirm(){
job=confirm("Are you sure to delete permanently?");
if(job!=true){
return false;
}
}
</script>
See webGautam answer Here
I use This in my code
<a href='<?php site_url('controler/function/$id');?>' onClick='javascript:return confirm(\"Are you sure to Delete?\")'>Delete</a>
Try this
Delete
Then your function will be like:
function isconfirm(url_val){
alert(url_val);
if(confirm('Are you sure you wanna delete this ?') == false)
{
return false;
}
else
{
location.href=url_val;
}
<?=
form_open('admin/delete_noti'),
form_hidden('noti_id',$notification->id),
form_submit('submit','Delete',array('onclick' => "return confirm('Do you want delete this record')",'class'=>'btn btn-danger float-center')),
form_close();
?>
This is the deletion code. first of all we open form admin is our controller name and delete_noti is the function inside admin controller. We are sending id as hidden form. Here $notification is the variable which is passed through method which is available in controller.
Finally, if you want javascript confirm: so when the user clicks, it asks to confirm and then goes to delete if the user clicks okay. You're asking confirmation when the row has already been deleted.
In View Page :-
<td>DELETE</td>
Controller Code:-
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class user extends CI_Controller {
public function deleteuser($userid)
{
$this->db->delete('user', array('user_id'=>$userid));
$this->session->set_flashdata('success','User deleted Successfully!!!');
redirect(base_url().'admin/user');
}
}
?>
Then Show Success Message on View:-
<div class="row col-md-12">
<?php
if($this->session->flashdata('success')){
?>
<div class="alert alert-success " style="display:none;">
<?php echo $this->session->flashdata('success'); ?>
<?php
} else if($this->session->flashdata('error')){
?>
<div class = "alert alert-danger" style="display:none;">
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php } ?>
</div></div>

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