how to retain user input data after validation using codeigniter - codeigniter

I am creating a web app using codeigniter and I am trying to retain user input data on a login form I am using the set value function but the user input is disappearing.
<?php echo form_open('Authentication/login_check',$attributes);?>
<div class="medium-12 columns">
<?php
echo form_label('Email');
$data = array(
'class'=>'form-control',
'name'=>'email',
'id'=> 'email',
'placeholder'=>'Email',
'value' => set_value('email')
);
echo form_input($data);
?>
</div>
<?php echo form_close();?>

You can load form helper in :
application/config/autoload.php
$autoload['helper'] = array('form');
You can set your form look like :
<?php echo form_open('authentication/login_check', '', array('id' => (!empty($attributes)) ? $attributes->id : 0)); ?>
<div class="medium-12 columns">
<?php
echo form_label('Email');
$data = array(
'class'=>'form-control',
'name'=>'email',
'id'=> 'email',
'placeholder'=>'Email',
'value' => set_value('email',($this->input->post('email')) ? $this->input->post('email') : ((!empty($attributes)) ? $attributes->email : ''))
);
echo form_input($data);
?>
</div>
<?php echo form_close();?>

Related

Show second dependent dropdown without reloading the page

I am trying to build a "price calculator" on my website, to show repair prices for various smartphones.
I already managed to create to dropdowns, the second one only showing after the first one is selected.
After making a choice in the first dropdown, the page reloads and then shows the second one. I would like to achieve the same without reloading the page. This is the code I have so far:
<form method="POST" action="">
<div>
<?php
$args = array(
'hierarchical' => 1,
'depth' => 1,
'orderby' => 'name',
'echo' => 0,
'taxonomy' => 'marke',
// this leads to variable name $_POST['marke']
'name' => 'marke-sel'
);
if( ! isset($_POST['marke-sel']) ):
$args['show_option_none'] = 'Hersteller auswählen';
else:
$args['selected'] = $_POST['marke-sel'];
endif;
$marke = wp_dropdown_categories( $args );
// this enables the buttonless js possibility
$marke = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $marke);
echo $marke;
?>
<noscript>
<div>
<input type="submit" value="marke" />
</div>
</noscript>
</div>
</form>
<?php
if( isset($_POST['marke-sel']) && $_POST['marke-sel'] ):
?>
<form method="POST" action="<? bloginfo('url'); ?>">
<input type="hidden" name="marke" value="<?php echo $_POST['marke-sel'] ?>">
<div>
<?php
$the_query = new WP_Query( array(
'post_type' => 'reparaturpreise',
'tax_query' => array(
array (
'taxonomy' => 'marke',
'field' => 'id',
'terms' => $_POST['marke-sel'],
)
),
) );
if ( $the_query->have_posts() ) :
?>
<div class="form-option parent-field-wrapper">
<label for=""></label>
<select name='modell' id='modell' onchange='document.location=this.value'>
<option value="">Modell auswählen</option>
<?php while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<option value="<?php the_permalink();?>"><?php the_title(); ?></option>
<?php endwhile; ?>
</select>
</div>
<?php endif;
wp_reset_postdata();
$modell = preg_replace("#<select([^>]*)>#", "<select$1 onchange='this.form.submit()'>", $modell);
echo $modell;
?>
<noscript>
<div>
<input type="submit" value="modell" />
</div>
</noscript>
</div>
</form>
<?php endif; ?>
<?php
if( isset($_POST['marke-sel']) && $_POST['modell'] ):
$args = array(
'post_type' => 'reparaturpreise',
'cat' => $_POST['marke-sel'],
'posts_per_page' => 1
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;
endif;
?>
I finally managed to get it working using this code from here: http://webprow.com/blog/dynamic-dependent-dropdown-categories-posts/
For anyone else looking for a similar solution, this is the code you need to insert in functions.php:
if ( ! class_exists( 'frontendAjaxDropdown' ) ):
class frontendAjaxDropdown {
function __construct() {
add_shortcode( 'ajax-dropdown', array($this, 'init_shortocde') );
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
}
function init_shortocde()
{ ?>
<div class="ajax-dropdown">
<?php
$args = array(
'name' => 'main_cat',
'id'=> 'main_cat',
'selected' => -1,
'hierarchical' => '1',
'depth' => 1,
'show_option_none' => 'ENTER PLACEHOLDER FOR TAXONOMY HERE',
'option_none_value' => '',
'hide_empty' => 0,
'taxonomy' => 'ENTER YOUR TAXONOMY HERE'
);
wp_dropdown_categories($args);
?>
<script type="text/javascript">
(function($){
$("#main_cat").change(function(){
$("#sub_cat").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $("#main_cat option:selected").val() },
beforeSend: function() {$("#loading").animate({ opacity: 1 });},
success: function(data) {
$("#loading").animate({ opacity: 0 });
$("#sub_cat").append(data);
}
});
});
$("select option[value='']").attr('disabled',"disabled");
$("select option[value='']").attr('selected',"selected");
})(jQuery);
</script>
<div id="loading" style="opacity: 0;">wird geladen...</div>
<div id="sub_cat"></div>
</div>
</div>
<?php }
function getSubCat() {
$cat_id = $_POST['cat_id'];
$args=array(
'post_type' => 'ENTER YOUR CPT HERE',
'tax_query' => array(
array (
'taxonomy' => 'ENTER YOUR TAXONOMY HERE',
'field' => 'id',
'terms' => $cat_id
)
),
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<select name="menu[]" onchange='document.location=this.value'>
<option value="" disabled selected>ENTER PLACEHOLDER FOR CPT HERE</option>
<?php
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<option value="<?php the_permalink();?>" ><?php the_title(); ?> </option>
<?php
endwhile;
wp_die();
?>
</select>
<?php
wp_reset_query();
die();
?> <?php }
}
}
endif;
new frontendAjaxDropdown();
After that, you can place the dropdowns using this shortcode:
<?php echo do_shortcode("[ajax-dropdown]"); ?>

Yii2: Load modal form and submit data via Ajax without redirecting to view

I have two models in my Yii2 project. One model: ApartmentBuilding depends on another model: Caretaker via a relationship. Assuming I am creating an ApartmentModel via a form whereby I select the caretaker from a dynamic dropdown. I then realize that the caretaker I need is not added yet to the database, hence, I have to add the details of the caretaker from the ApartmentBuilding model form then proceed filling in the details of the ApartmentBulding form. That is the usecase of my problem.
So far, I have managed to launch the Caretaker model form via a modal from the ApartmentBulding form. On submitting the details of the Caretaker model form, the site redirects to the view of the CaretakerController. However, what I need is to be able to get the dropdown form refresh with the new details of the caretaker that I just added via a modal, and be able to proceed with the filling of the rest of the form.
Any help in cracking this will be appreciated.
Here are my codes so far:
ApartmentBuilding _form.php
<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use app\models\Landlord;
use app\models\Caretaker;
use yii\helpers\ArrayHelper;
use yii\bootstrap\Button;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $model app\models\ApartmentBuilding */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="apartment-building-form">
<?php $form = ActiveForm::begin([
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_TINY],
]); ?>
<?= $form->field($model, 'apartment_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'landlord_id')->dropDownList(ArrayHelper::map(Landlord::find()->select(['landlord_id', 'first_name', 'last_name'])->all(), 'landlord_id', 'displayName'),['class' => 'form-control inline-block', 'prompt'=>'Select Landlord']) ?>
<?= $form->field($model, 'physical_address')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'plot_number')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'address')->widget(\kalyabin\maplocation\SelectMapLocationWidget::className(), [
'attributeLatitude' => 'latitude',
'attributeLongitude' => 'longitude',
'googleMapApiKey' => 'YOUR_API_KEY_HERE',
]) ?>
<?= $form->field($model, 'number_of_floors')->textInput() ?>
<?= $form->field($model, 'apartment_desc')->textInput(['maxlength' => true]) ?>
<div class="form-group kv-fieldset-inline">
<?= Html::activeLabel($model, 'caretaker_id', ['label'=>'Caretaker', 'class'=>'col-sm-3 control-label']) ?>
<div class="col-sm-8">
<?= $form->field($model, 'caretaker_id',['showLabels'=>false])->dropDownList(ArrayHelper::map(Caretaker::find()->select(['caretaker_id', 'first_name', 'last_name'])->all(), 'caretaker_id', 'displayName'),['class' => 'form-control inline-block', 'prompt'=>'Select Caretaker']) ?>
</div>
<div class="col-sm-1">
<?= Html::button('<i class="glyphicon glyphicon-plus"></i>', ['value'=>Url::to(['caretaker/new']), 'title' => 'Create New Caretaker', 'class' => 'btn btn-success showModalButton']) ?>
</div>
</div>
<?= $form->field($model, 'other_apt_details')->textInput(['maxlength' => true]) ?>
<div class="col-sm-offset-3 col-sm-9">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Caretaker _form.php
<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\widgets\DatePicker;
/* #var $this yii\web\View */
/* #var $model app\models\Caretaker */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="caretaker-form">
<?php $form = ActiveForm::begin([
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_TINY],
]); ?>
<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'sex')->dropDownList(['Male' => 'Male', 'Female' => 'Female'],['prompt'=>'Select Sex']) ?>
<?= $form->field($model, 'date_of_birth')->widget(DatePicker::classname(), ['options' => ['placeholder' => 'Enter birth date ...'], 'pluginOptions' => ['autoclose'=>true, 'format' => 'yyyy-mm-dd']]) ?>
<?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'mobile')->widget(\yii\widgets\MaskedInput::className(), ['mask' => '254999999999',]) ?>
<div class="col-sm-offset-3 col-sm-9">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
CaretakerController actionNew()
public function actionNew()
{
$model = new Caretaker();
$model->company_id = Yii::$app->user->identity->company_id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return false;
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Modal Handler:
<?php
yii\bootstrap\Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => FALSE]
]);
echo '<div id="modalContent"><div style="text-align:center"><?= Html::img("#web/img/loading.gif");?></div></div>';
yii\bootstrap\Modal::end();
?>
modal-popup.js
$(function(){
//get the click of modal button to create / update item
//we get the button by class not by ID because you can only have one id on a page and you can
//have multiple classes therefore you can have multiple open modal buttons on a page all with or without
//the same link.
//we use on so the dom element can be called again if they are nested, otherwise when we load the content once it kills the dom element and wont let you load another modal on click without a page refresh
$(document).on('click', '.showModalButton', function(){
//check if the modal is open. if it's open just reload content not whole modal
//also this allows you to nest buttons inside of modals to reload the content it is in
//the if else are intentionally separated instead of put into a function to get the
//button since it is using a class not an #id so there are many of them and we need
//to ensure we get the right button and content.
// if ($('#modal').data('bs.modal').isShown)
if ($("#modal").data('modal') && $("#modal").data('modal').isShown){
$('#modal').find('#modalContent')
.load($(this).attr('value'));
//dynamically set the header for the modal
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
} else {
//if modal isn't open; open it and load content
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
//dynamiclly set the header for the modal
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
}
});
});
$(function(){
//load the current page with the conten indicated by 'value' attribute for a given button.
$(document).on('click', '.loadMainContent', function(){
$('#main-content').load($(this).attr('value'));
});
});
Note
The modal handler code and the modal-popup.js are reused by several other modals such as view and create forms. The code for the modal handler is in the main.php of the layouts folder.
I have managed to solve the problem by doing the following (More thoughts on the same still welcome, I know there could be more perfect way of doing this):
I added the following Javascript code to the caretaker _form.php
<?php
$this->registerJs("$('#createcaretaker').click(function() {
var firstName = $('#caretaker-first_name').val();
var lastName = $('#caretaker-last_name').val();
var sex = $('#caretaker-sex').val();
var dOB = $('#caretaker-date_of_birth').val();
var address = $('#caretaker-address').val();
var mobile = $('#caretaker-mobile').val();
$('#modal').modal('hide');
$.get('new?firstName='+firstName+'&lastName='+lastName+'&sex='+sex+'&dOB='+dOB+'&address='+address+'&mobile='+mobile, function(success){
$('.refreshcaretaker').html(success);
});
});");
?>
Then, the submit button on the same form, I changed it to:
<button id="createcaretaker" type="button" class="btn btn-success">Create</button>
Hence, the button id is able to trigger the Javascript code above to send data to the server side.
I then created a controller action in the ApartmentBuilding controller to handle the data entry as follows:
public function actionNew($firstName, $lastName, $sex, $dOB, $address, $mobile)
{
$model = new Caretaker();
$model->company_id = Yii::$app->user->identity->company_id;
if ($firstName != '0' && $lastName != '0' && $sex != '0' && $dOB != '0' && $address != '0' && $mobile != '0') {
$model->first_name = $firstName;
$model->last_name = $lastName;
$model->sex = $sex;
$model->date_of_birth = $dOB;
$model->address = $address;
$model->mobile = $mobile;
$model->save();
$caretakers = Caretaker::find()->all();
foreach ($caretakers as $caretaker) {
echo '<option value="'.$caretaker->caretaker_id.'">'.$caretaker->displayName.'</option>';
}
} else {
return $this->renderAjax('caretaker_create', [
'model' => $model,
]);
}
}
Having done that, I changed the dropdown entry of the parent form to be able to refresh its values via ajax upon submitting the modal form to create the caretaker model as follows:
<?= $form->field($model, '[{$i}]caretaker_id',['showLabels'=>false])->dropDownList(ArrayHelper::map(Caretaker::find()->select(['caretaker_id', 'first_name', 'last_name'])->all(), 'caretaker_id', 'displayName'),['class' => 'form-control inline-block refreshcaretaker', 'prompt'=>'Select Caretaker']) ?>
Note the refreshcaretaker class that is triggered by the Javascript code above when the modal is submitted.
The following link talks more about using modal forms in Yii2.

how does one load a div using its id to a view?

how does one load a div using its id to a view?
this is my view
<div id="register" class="animate form">
<section class="login_content">
<form <?php echo form_open('User/register'); ?>
<h1>Create Account</h1>
<div class="inputlogin">
<div class="form-group">
how will i pass it to
if ($this->form_validation->run() === false) {
// validation not ok, send validation errors to the view
$index['title']="Welcome to Hoovie";
$index['mainContent']="login";
$index['results'] = $this->users_model->get_category();
$this->load->view('includes/redirect', $index, $data);
First, form_open tag makes <form> so you can't echo it inside of form it would look like <form <form>>
here is example of login form inside of view:
echo form_open('path/to/controller');
echo form_input(array(
'name' => 'username',
'class' => 'form-control input-lg',
'placeholder' => 'username'
));
echo form_password(array(
'name' => 'password',
'class' => 'form-control input-lg',
'placeholder' => 'password'
));
echo form_submit(array(
'name' => 'LoginSubmit',
'class' => 'btn btn-lg btn-info',
'value' => 'Login'
));
echo form_close();}
After that inside of your controller you have to activate form_validation library if it is not auto-loaded and then you have to set rules for your inputs
example :
$dugme = $this->input->post('LoginSubmit');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if(isset($dugme) && $this->form_validation->run()){
//if everything ok, do something
}
else {
//if validation did not pass load view
$this->load_view('login'); }
and after that inside of view you have to echo errors
//I am using bootstrap so alert-danger will show this div with red background
<?php echo validation_errors('<div class="alert alert-danger">','</div>');?>
you can check more about form validation here :
Codeigniter 3: https://www.codeigniter.com/userguide3/libraries/form_validation.html
Codeigniter 2: https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html

How to reuse form in codeigniter for update and add

Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.
<?php
$attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
echo form_open($form_submission, $attributes);
?>
<input type="text" name="name" value="<?php echo set_value('name')?"> >
<input type="text" name="rank" value="<?php echo set_value('rank')?"> >
<button type="submit" class="btn btn-primary">Save</button>
<?php echo form_close()?>
My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.
In your controller update function add a condition like:
if ($this->input->server('REQUEST_METHOD') === 'POST') {
$this->_get_userinfo_form_fields();
} else {
$this->_get_userinfo_form_fields($user_data); //$user_data from database
}
For add function you can directly call - $this->_get_userinfo_form_fields();
Then declare a function as below:
protected function _get_userinfo_form_fields($user_data = array()) {
$this->data['rank'] = array(
'placeholder' => 'Rank',
'name' => 'rank',
'id' => 'rank',
'class' => '',
'value' => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
'style' => '',
);
//Add rest of the fields here like the above one
}
In view file add code like:
<?php echo form_input($rank);?>

Yii2 ajax validate and submit form

I have very little AJAX's Information. That's why I asked my question here...
in yii2 how can create and submit form with ajax validation?
So I searched but could not find the right solution...
for example: (according to the official training site)
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
]); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'extra_txt')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
and in controller:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
} else {
return $this->render('create', [
'model' => $model,
]);
}
My problems:
1- ajax validation
2- submit form with ajax
Why don't you use Pjax? Use yii\widgets\Pjax and add Pjax::begin() and Pjax::end() around your form.
A decent guide over here:
http://www.yiiframework.com/wiki/772/pjax-on-activeform-and-gridview-yii2/

Resources