Can't Display Form Errors in Codeigniter - php

I am Creating a Blogging Application with Codeigniter. So therefor i have created admin panel for admin. But on my new article controller i cant display form errors. Here is my code.
Add Article and Store Article Controllers
public function add_article()
{
$this->load->model('dashboardmodel');
$username = $this->dashboardmodel->get_username();
$this->load->helper('form');
$this->load->view('admin/add_article', ['user'=>$username]);
}
public function store_article()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="alert alert-dismissible alert-danger">', '</div>');
$this->form_validation->set_rules('title', 'Post Title', 'required|trim|alpha');
$this->form_validation->set_rules('body', 'Post Content', 'required');
if ($this->form_validation->run()) {
$title = $this->input->post('title');
$body = $this->input->post('body');
echo 'Successful';
} else {
return redirect('admin/add_article');
}
}
Add Article View
<?php
include_once('admin_header.php');
?>
<div class="container">
<fieldset>
<legend>New Post</legend>
//Here ERRORS SHOULD BE DISPLAYED
<?php echo validation_errors(); ?>
<?php echo form_open('admin/store_article', ['class'=>'form-horizontal']);
if ($error = $this->session->flashdata('login_failed')) : ?>
<div class="alert alert-dismissible alert-danger">
<?= $error ?>
</div>
<?php endif; ?>
<div class="form-group">
<div class="col-lg-10">
<?php echo form_input(['name'=>'title', 'class'=>'form-control', 'placeholder'=>'Post Title', 'value'=>set_value('title')]); ?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<?php echo form_textarea(['name'=>'body', 'class'=>'form-control', 'placeholder'=>'Post Content']); ?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<?php echo form_reset(['name'=>'reset', 'value'=>'Reset', 'class'=>'btn btn-default']),
form_Submit(['type'=>'submit', 'value'=>'Publish', 'class'=>'btn btn-primary']); ?>
</div>
</div>
</fieldset>
</form>
</div>
<?php
include_once('admin_footer.php');
?>
Dont What's Going On but i am Stuck in it.

Your problem is that when the form submission contains errors, you redirect to the page again, which refreshes the page and all errors are gone. What you need to do is replace your return redirect('admin/add_article'); line with actually loading the same view again, which would contain the errors this time. And since you load other things for the view, you'll have to replace it with this whole code (which is the same as the other method so maybe you should give the structure of this code more thought):
$this->load->model('dashboardmodel');
$username = $this->dashboardmodel->get_username();
$this->load->helper('form');
$this->load->view('admin/add_article', ['user'=>$username]);

Related

Cannot populate field when using form_helper in Codeigniter

form were populating working in my previous project but now it isn't. I checked the code on my previous project and copy pasted it but still it doesn't populate it. When I type in it and submit it, it shows blank but when i inspected it in the browser it showed something like this:
check this image
Below is the my view:
<div class="form-group">
<?php echo form_hidden('STUD_ID', #$upd->STUD_ID); ?>
<?php echo form_label('Student name','name'); ?>
<?php echo form_input("STUD_NAME",#$upd->STUD_NAME,set_value('STUD_NAME'),["class"=>"form-control","placeholder"=>"John
Doe"]);?>
<?php echo form_error('STUD_NAME'); ?> </div> <div class="form-group">
<?php echo form_label('Password','password'); ?>
<?php echo form_input('STUD_PASS',#$upd->STUD_PASS,['class'=>'form-control','placeholder'=>'******']),set_value('STUD_PASS')
?>
<?php echo form_error('STUD_PASS'); ?> </div>
Controller
$this->form_validation->set_rules('STUD_NAME','Username','trim|required|is_unique[student.STUD_NAME]');
$this->form_validation->set_rules('STUD_PASS', 'Password', 'trim|required|min_length[5]');
$this->form_validation->set_rules('STUD_EMAIL', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('STUD_ADD', 'Address', 'trim|required');
$this->form_validation->set_rules('STUD_PHONE', 'Phone', 'trim|required|min_length[10]');
$this->form_validation->set_rules('STUD_GENDER', 'Gender', 'trim|required');
$this->form_validation->set_rules('HOBBY[]', 'Hobby', 'trim|required');
$this->form_validation->set_error_delimiters('<small style="color:red">','</small>');
if ($this->form_validation->run() == TRUE) {
.......
}
Try with this code : initialise form_input with an array like this
Form should be like this :
<div class="form-group">
<?php echo form_hidden('STUD_ID', #$upd->STUD_ID); ?>
<?php echo form_label('Student name','name'); ?>
<?php echo form_input(["name" => "STUD_NAME","value" => set_value('STUD_NAME',#$upd->STUD_NAME),"class"=>"form-control","placeholder"=>"JohnDoe"]);?>
<?php echo form_error('STUD_NAME'); ?>
</div>
<div class="form-group">
<?php echo form_label('Password','password'); ?>
<?php echo form_input(["name" => "STUD_PASS","value" => set_value('STUD_PASS',#$upd->STUD_PASS),"class"=>"form-control","placeholder" => "******"]);?>
<?php echo form_error('STUD_PASS'); ?>
</div>
See more : https://www.codeigniter.com/user_guide/helpers/form_helper.html#form_input

Codeigniter form validation does not show error and redirects to blank page

Given below is controller and view but its not validated and only redirects to about:blank page.
I Have made some changes but nothing happens.
controller:
<?php
class Home extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library(array('form_validation','session')); // load form lidation libaray & session library
$this->load->helper(array('url','html','form')); // load url,html,form helpers optional
}
public function index(){
// set validation rules
$this->form_validation->set_rules('name', 'Name', 'required|min_length[4]|max_length[10]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('number', 'Phone Number', 'required|numeric|max_length[15]');
$this->form_validation->set_rules('subject', 'Subject', 'required|max_length[10]|alpha');
$this->form_validation->set_rules('message', 'Message', 'required|min_length[12]|max_length[100]');
// hold error messages in div
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// check for validation
if ($this->form_validation->run() == FALSE) {
$this->load->view('viewform');
}else{
$this->session->set_flashdata('item', 'form submitted successfully');
redirect('Home');
}
}
}
?>
view:
<?php if(validation_errors()) { ?>
<div class="alert alert-warning">
<?php echo validation_errors(); ?>
</div>
<?php } ?>
<?php if($this->session->flashdata('item')) { ?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('item'); ?>
</div>
<?php } ?>
<?php echo form_open(); ?>
<div class="form-group">
<?php echo form_label('Your Name','name'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "name", "placeholder"=>"Enter Name","value" => set_value('name'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Email address','EmailAddress'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "email", "placeholder"=>"Enter email","value" => set_value('email'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Phone Number','number'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "number", "placeholder"=>"Enter Phone Number","value" => set_value('number'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Subject','subject'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "subject", "placeholder"=>"Enter Subject","value" => set_value('subject'))); ?>
</div>
<div class="form-group">
<?php echo form_label('Message','message'); ?>
<?php echo form_input(array("class"=>"form-control","name" => "message", "placeholder"=>"Enter Message","value" => set_value('message'))); ?>
</div>
<button type="submit" class="btn btn-default">Submit</button>
<?php echo form_close(); ?>
so when any error is there the page is redirected to about:blank even if all fields are proper or improper how to fix this?

Rendering Yii's Flash message inside the partial view with ajax call

I have a problem displaying Flash messages in Yii. Inside my view I have an ajax button, calling method update of my controller. Inside the update method I want to set a Flash message and display it inside my view when it's updated with new data.
*update.php :*
<?php
<h1>Update Campaign <?php echo $campaign->id; ?></h1>
<?php
$tabList = array();
//FORM IS DISPLAYED INSIDE A JUI TAB:
$tabList['General'] = $this->renderPartial('_form', array('campaign'=>$campaign),true);*
...
$this->widget('zii.widgets.jui.CJuiTabs',array(
'tabs'=>$tabList,
'options'=>array(
'collapsible'=>false,
),
));
?>
*_form.php:*
//HERE I WANT TO DISPLAY A FLASH MESSAGE WHEN _form IS RENDERED:
<?php foreach(Yii::app()->user->getFlashes() as $key => $message) : ?>
<div class="flash-<?php echo $key; ?>"><?php echo $message; ?></div>
<?php endforeach; ?>
<?php
Yii::app()->clientScript->registerScript(
'myHideEffect',
'$(".flash-success").animate({opacity: 1.0}, 1000).fadeOut("slow");',
CClientScript::POS_READY
);
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'campaign-form',
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($campaign); ?>
<div class="row">
<div class="span2">
<?php echo $form->labelEx($campaign,'campaign_mode_id'); ?>
</div>
<div class="span2">
<?php echo $form->dropDownList($campaign,'campaign_mode_id', CampaignMode::model()->getModes());?>
<?php echo $form->error($campaign,'campaign_mode_id'); ?>
</div>
</div>
...
<div class="row buttons">
<div class="span2">
<?php
if($campaign->isNewRecord){
echo CHtml::submitButton( 'Create');
}else{
//THIS IS MY AJAX-SUBMIT BUTTON, IT CALL CONTROLLER'S UPDATE METHOD AND UPDATE JUI TAB (DIV WITH ID '#yw0_tab0')
echo CHtml::ajaxSubmitButton(
'Save',
Yii::app()->createUrl("//campaign/update/{$campaign->id}"),
array('beforeSend' => 'function(){
$("#surveyquestions").addClass("ajaxloading");}',
'complete' => 'function(){
$("#surveyquestions").removeClass("ajaxloading");}','update' => "#yw0_tab0"),
array('id' => 'send-link-'.uniqid()));
}
?>
</div>
</div>
<?php $this->endWidget(); ?>
*Contorller:*
public function actionUpdate($id)
{
$campaign=$this->loadModel($id);
if(isset($_POST['Campaign']))
{
$campaign->attributes=$_POST['Campaign'];
if($campaign->save())
{
//HERE I'M SETTING THE FLASH MSG
Yii::app()->user->setFlash('success','Campaign is updated');
if(Yii::app()->request->isAjaxRequest){
//AND UPDATING MY VIEW
$this->renderPartial('_form', array('campaign'=>$campaign), true,true);
}else{
$this->redirect(array('update','id'=>$campaign->id));
}
}
}
$this->render('update',array('campaign'=>$campaign));
}
Actually you are rendering _form view, but without sending it to output (take a look at third param), and then you are rendering update view... The flash message has been rendered once in _form, so it won't be rendered again.
You should simply try this :
if(Yii::app()->request->isAjaxRequest) {
$this->renderPartial('_form', array('campaign'=>$campaign), false, true);
Yii::app()->end();
} else {
$this->redirect(array('update','id'=>$campaign->id));
}

how to insert multi records in yii session using ajaxSubmitButton

I have been developing an application in Yii framework. At this point, I fall in an issue that is, I have an Order form where I select a registrant (all registrants come from database) from a dropdown, an item (all product items come from database) from dropdown and a input textbox where I type the quantity. There is a "ajaxSubmitButton" button to send all these values to the controller "actionCart" using Ajax. After receiving all values in the controller, I want to put all values in session variable. When I add another new item, the session values are being replaced what I want to hold all newly added items into the session variable. In this circumstance, what should I do. Please help me. I am giving my code snippets below:
in form:
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'order-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('class'=>'form-horizontal' , 'enctype'=>'multipart/form-data', ),
)); ?>
<div class="alert alert-info" xmlns="http://www.w3.org/1999/html">
<p class="note">Fields with <strong><span class="required">*</span></strong> are required.</p>
</div>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<?php echo $form->labelEx($model,'registration_id', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Registration::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'registration_id',$data,array('class' => 'form-control chzn-select','prompt'=>'Select a Registrant'));
?>
</div>
<?php echo $form->error($model,'registration_id'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'item', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-8">
<?php
$data = CHtml::listData(Products::model()->findAll(),'id', 'name');
echo $form->dropDownList($model,'item',$data, array('class'=>'form-control chzn-select' , 'id'=>'item', 'prompt'=>'Select an Item')); ?>
<?php
?>
</div>
<?php echo $form->error($model,'item'); ?>
</div>
<div class="form-group">
<?php echo $form->labelEx($model,'quantity', array('class' => 'control-label col-lg-4')); ?>
<div class="col-lg-2">
<?php
echo $form->textField($model,'quantity',array('class' => 'form-control','size'=>60,'maxlength'=>11));
?>
</div>
<?php echo $form->error($model,'quantity'); ?>
</div>
<div class="form-group">
<div class="col-lg-8 pull-right">
<?php
echo CHtml::ajaxSubmitButton('Add to Cart',Yii::app()->createUrl('admin/order/cart'),
array(
'type'=>'POST',
'update'=>'#cartResult',
),
array('class'=>'btn btn-primary btn-sm',));
?>
</div>
</div>
<div class="form-group">
<div id="cartResult" class="col-lg-12">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
In controller:
public function actionCart()
{
if(isset($_POST["Order"])){
$item = $_POST["Order"];
$registration_id = $item["registration_id"];
$productId = $item["item"];
$quantity = $item["quantity"];
$quantity = $item["quantity"]=='' ? 1 : $item["quantity"];
$productInfo = Products::model()->findByPk(array('id'=>$productId));
$totalPrice = $productInfo->price * $quantity;
$session = Yii::app()->session;
$session['cart'] = array("product_id" => "$productId" , "product_name" => "$productInfo->name", "quantity" => "$quantity","price" => "$productInfo->price");
}
}

issues validation using render partial yii framework

I am loading a view using renderpartial, but the validations not working and not show the error messages. I tried to resolve the problem actived processOUtput in renderpartial but isn´t work.
this is my index view where I load the form view
<?php echo CHtml::link('Crear Usuario', array('create'), array('id'=>'newUsuario')); ?>
<div id="modal" class="modal hide fade"></div>
<script>
$(document).ready(function() {
$("#newUsuario").click(function() {
event.preventDefault();
$("#modal").load($("#newUsuario").attr("href"));
$("#modal").modal({show:true});
});
});
</script>
This is my action that load the view
public function actionCreate() {
$model = new Usuarios;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Usuarios']))
{
$model->validate();
$model->attributes=$_POST['Usuarios'];
$_POST['Usuarios']['check_tipo'] == 1 ? $model->tipo = 'Administrador' : $model->tipo = 'Normal';
$model->pass_php = md5($model->pass);
$model->session = $model->generateSalt();
$model->pass_hash= $model->hashPassword($_POST['Usuarios']['pass'], $model->session);
$this->transaction = $model->dbConnection->beginTransaction();
try {
if($model->save()) {
$this->transaction->commit();
$this->actionIndex();
}
} catch(Exception $e) {
$this->transaction->rollBack();
}
}
$this->renderPartial('create', array('model'=>$model));
}
And this is the view with the form
<h4 align="center">Nuevo Usuario</h4>
<div class="form">
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'usuarios-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>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,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su email')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'check_tipo'); ?>
<?php echo $form->checkBox($model,'check_tipo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nombre'); ?>
<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su nombre')); ?>
<?php echo $form->error($model,'nombre'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'pass'); ?>
<?php echo $form->passwordField($model,'pass',array('size'=>60,'maxlength'=>255, 'placeholder'=>'Escriba su contraseña')); ?>
<?php echo $form->error($model,'pass'); ?>
</div>
</div>
<center>
<?php echo CHtml::button('Close', array('class'=>'btn', 'data-dismiss'=>'modal', 'aria-hidden'=>true)); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save', array('class'=>'btn btn-primary')); ?>
</center>
<?php $this->endWidget(); ?>
When I used render the validations and error messages work, the problem is just with renderpartial.
Help me please and sorry if my english is bad.

Categories