Yii2: widget wbraganca Dynamic Forms Only saves one value submitted to db - forms

I'm trying to save various instances of a field using the dynamic form widget. The problem I'm having is that after I submit it only saves the last value at input.
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-plus"></i> Facilidades a realizar y costo estimado:</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelosfacilidades[0],
'formId' => 'dynamic-form',
'formFields' => [
'Descripcion',
'precio',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelosfacilidades as $i => $modelofacilidad): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Descripción de facilidad y precio</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelofacilidad->isNewRecord) {
echo Html::activeHiddenInput($modelofacilidad, "[{$i}]id");
}
?>
<?= $form->field($modelofacilidad, "[{$i}]Descripcion")->textArea(['maxlength' => true]) ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelofacilidad, "[{$i}]precio")->textInput(['placeholder' => '$']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
This is a function Gii generated at my form model for the field that receives the data.
/**
* #return \yii\db\ActiveQuery
*/
public function getFacilidadesARealizar0025s()
{
return $this->hasMany(FacilidadesARealizar0025::className(), ['id_0025' => 'id_asda_pa_0025']);
}
And this is the actionCreate controller class:
public function actionCreate()
{
$model = new AsdaPa0025();
$modelosfacilidades = [new FacilidadesARealizar0025()];
if ($model->load(Yii::$app->request->post())) {
$model->cuerdas= $model->propia + $model->usofructo + $model->arrendada;
$model->file = UploadedFile::getInstance($model, 'file');
$modelosfacilidades = Model::createMultiple(FacilidadesARealizar0025::classname());
Model::loadMultiple($modelosfacilidades, Yii::$app->request->post());
//valida los modelos
$valid = $model->validate();
$valid = Model::validateMultiple($modelosfacilidades) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelosfacilidades as $modelofacilidades) {
//Aqui le digo al controlador que id_0025 es igual al id de la instancia de la forma 0025
$modelofacilidades->id_0025 = $model->id_asda_pa_0025;
if (! ($flag = $modelofacilidades->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
// $model->file = 'uploads/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
// if ($model->save()) {
// $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
}
else{
// return $this->redirect(['view', 'id' => $model->id_asda_pa_0025]);
return $this->render('create', [
'model' => $model,
'modelosfacilidades' => (empty($modelosfacilidades)) ? [new FacilidadesARealizar0025] : $modelosfacilidades
]);
}
}
I would appreciate any help! I can't seem to find the answer to my problem anywhere.

1)Make sure that Active form has the same id as the formId in your DynamicFormWidget:
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
2)Change [new FacilidadesARealizar0025()] to [new FacilidadesARealizar0025];
3) After if ($model->load(Yii::$app->request->post())) {
add
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return Yii::$app->request->post();
and make sure that all your FacilidadesARealizar0025 model data is submitted. This helps you determine whether the problem is in your form or your create function. If not all your data is posted then focus on your form. I hope this helps

Related

How to post multiple inputs in database

I'm working with Codeigniter, on a sales targets' form for salesmen.
They have to input values for each product, locality, year, etc.
Product and locality are already get with existing database: no need to set rules (see controller).
When I checked the post (with enable_profiler of Codeigniter), I get this:
The problem is these datas don't insert into the database table.
I read and tested a lot, but always blocked.
Here is my model:
public function add($params)
{
$this->db->insert($this->table, $params);
return $this->db->insert_id();
}
My controller:
$this->load->library('form_validation');
$this->form_validation->set_rules('year', 'Year', 'required|integer');
$this->form_validation->set_rules('prevision', 'Prevision', 'required');
$this->form_validation->set_rules('value', 'Value', 'required|integer');
if ($this->form_validation->run()) {
$params = array(
'year' => $this->input->post('year'),
'prevision' => $this->input->post('prevision'),
'locality_id' => $this->input->post('locality'),
'product' => $this->input->post('product'),
'value' => $this->input->post('value'),
);
$this->Objectif_model->add($params);
redirect('admin/objectif');
} else {
$this->layout('admin/objectif/add');
}
And my view with inputs:
<?php foreach ($products as $product) : ?>
<tr class="form-group">
<td class="bg-warning">
<?= $product->grp_product; ?>
</td>
<td class="bg-warning product">
<?= $product->code; ?>
</td>
<?php foreach ($localities as $locality ) : ?>
<td>
<input type="text" class="form-control valeur" placeholder="Value k€" name="value[]" data-validation="number" data-validation-ignore="./" data-validation-optional="true" />
<input type="text" name="year[]" />
<input type="text" name="prevision[]" />
<input type="text" name="product[]" value="<?= $product->code ?>" />
<input type="text" name="localite_id[]" value="<?= $locality->id ?>" />
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
Hope you will help me.
I find my answer.
In my controller, I had to pass each post in a variable and made a loop.
//action post in a var for each data
$id = $this->input->post('id');
$prev = $this->input->post('prevision');
$year= $this->input->post('year');
$locality_id = $this->input->post('locality_id');
$product = $this->input->post('product');
$value= $this->input->post('value');
if ($this->form_validation->run()) {
$count_id = count($id);
if (isset($id)) {
for ($i = 0; $i < $count_id; $i++) {
$obj[$i] = array(
'id' => $id[$i],
'prevision' => $prev,
'year' => $year,
'locality_id' => $locality_id[$i],
'product' => $product[$i],
'value' => $value[$i]*1000
);
} // endfor
if (isset($obj)) {
$this->Objectif_model->add_obj($obj);
} // endif
}// endif isset
}// endif form validation

Yii2 dynamic form constraint violation on unique index in database table

I am creating a form with dynamic fields in which 2 fields have unique indexes in the database table. 1st 'Landline' and 2nd 'Address'. If there is no duplicate value in any of the dynamically added fields then the form submits without any error, but if I enter Address or Landline which matches any previously added field then shows constraint violation instead of showing error message even when I have already added rules in the model.
For example: I have 1 record with address = 'address', landline = 123 and I create a new record with the address = 'address' or landline = 123 then there is no error but when I submit it shows:
Exception (Integrity constraint violation) 'yii\db\IntegrityException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '15-address' for key 'unique_doctors_id__address'
If I remove the indexes from the table then data saves successfully.
I have tried to submit this normally and via ajax but same problem every time, my main interest is submitting the form via ajax.
I already have googled for this issue, but couldn't find any solution, please help.
model/DoctorClinics
class DoctorClinics extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['name', 'incharge', 'landline', 'address'], 'required', 'message' => "'{attribute}' can not be empty."],
[['name', 'incharge', 'address', 'landline', 'landmark'], 'string', 'max' => 255],
['status', 'required', 'message' => "'{attribute}' can not be unselected"],
['status', 'in', 'range' => Common::get_array('range_active_inactive'), 'message' => "'{attribute}' has an invalid value"],
['status', 'string', 'max' => 1],
[['doctors_id', 'landline'], 'unique', 'targetAttribute' => ['doctors_id', 'landline'], 'message' => 'The combination of Doctors and Landline has already been taken.'],
[['doctors_id', 'address'], 'unique', 'targetAttribute' => ['doctors_id', 'address'], 'message' => 'The combination of Doctors ID and Address has already been taken.'],
[['token'], 'string', 'max' => 50],
[['token'], 'unique'],
[['doctors_id'], 'exist', 'skipOnError' => true, 'targetClass' => Doctors::className(), 'targetAttribute' => ['doctors_id' => 'id']],
[['doctors_id', 'created_at', 'updated_at'], 'integer'],
];
}
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels))
{
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post))
{
foreach ($post as $i => $item)
{
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']]))
{
$models[] = $multipleModels[$item['id']];
}
else
{
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
controller
class DoctorsController extends Controller
{
...
public function actionCreate()
{
# models
$modelDoctors = new Doctors();
$modelDoctorClinics = [new DoctorClinics];
# scenario
$modelDoctors->scenario = Doctors::SCENARIO_CREATE;
$transaction = Yii::$app->db->beginTransaction();
# checking post method
if(($arrayPost = \Yii::$app->request->post()) != null)
{
$modelDoctorClinics = DoctorClinics::createMultiple(DoctorClinics::classname());
// $modelDoctorClinics->scenario = Doctors::SCENARIO_CREATE;
DoctorClinics::loadMultiple($modelDoctorClinics, Yii::$app->request->post());
# loading posted data to model
$modelDoctors->load($arrayPost);
# setting data
$modelDoctors->token = Common::generate_token();
$modelDoctors->added_by = \Yii::$app->user->identity->id;
$modelDoctors->auth_key = \Yii::$app->security->generateRandomString();
$modelDoctors->password_hash = \Yii::$app->security->generatePasswordHash(Common::DEFAULT_PASSWORD);
$modelDoctors->created_at = time();
# validate all models
$valid = $modelDoctors->validate();
$valid = DoctorClinics::validateMultiple($modelDoctorClinics) && $valid;
if($valid)
{
try
{
if ($flag = $modelDoctors->save(false))
{
foreach ($modelDoctorClinics as $modelDoctorClinic)
{
$modelDoctorClinic->token = Common::generate_token();
$modelDoctorClinic->doctors_id = $modelDoctors->id;
$flag = $modelDoctorClinic->save(false) && $flag;
if(!$flag)
{
$transaction->rollBack();
break;
}
}
}
if ($flag)
{
$transaction->commit();
Yii::$app->session->setFlash('success', 'Doctor\'s details saved successfully');
# setting response format
\Yii::$app->response->format = Response::FORMAT_JSON;
return true;
}
}
catch (Exception $e)
{
$transaction->rollBack();
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelDoctorClinics),
ActiveForm::validate($modelDoctors)
);
}
}
else
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelDoctorClinics),
ActiveForm::validate($modelDoctors)
);
}
}
else
{
# returning data
return $this->render('create', [
'model_doctors' => $modelDoctors,
'model_doctor_clinics' => (empty($modelDoctorClinics)) ? [new DoctorClinics] : $modelDoctorClinics
]);
}
}
public function actionValidations($scenario)
{
# fetching posted data
$arrayPost = \Yii::$app->request->post();
# models
if(empty($scenario) || !in_array($scenario, [Doctors::SCENARIO_CREATE, Doctors::SCENARIO_UPDATE]))
{
$modelDoctors = new Doctors(['scenario' => Doctors::SCENARIO_CREATE]);
}
else
{
if($scenario == Doctors::SCENARIO_UPDATE)
{
$modelDoctors = Doctors::find()
->where(['token' => $arrayPost['Doctors']['token']])
->one();
}
else
{
$modelDoctors = new Doctors();
}
# scenario
$modelDoctors->scenario = $scenario;
}
if(!empty($arrayPost) && \Yii::$app->request->isAjax)
{
# setting response format
\Yii::$app->response->format = Response::FORMAT_JSON;
# loading posted data to model
$modelDoctors->load($arrayPost);
return ActiveForm::validate($modelDoctors);
}
}
...
}
form
<?php
$form = ActiveForm::begin([
"enableAjaxValidation" => true,
"validateOnSubmit" => true,
'validationUrl' => \Yii::$app->urlManager->createUrl('doctors-validation/' . (($model_doctors->isNewRecord) ? 'create' : 'update')),
'options' => [
'id' => $model_doctors->formName(),
'class' => 'forms'
]
]);
?>
<div class="boxBody">
<div class="row form-page-image">
<div class="image mb10">
<div class="col-sm-12 thumbnail">
<?php
if(!empty($model_doctors->image) && file_exists(\Yii::getAlias('#uploads') . "/{$model_doctors->image}"))
{
echo Html::img(\Yii::$app->urlManagerFrontend->createUrl('/thumbnails') . '/' . $model_doctors->image, [
'alt' => $this->title,
'class' => 'js-thumbnail'
]);
}
else
{
echo Html::img(\Yii::$app->urlManager->createUrl('/images') . '/' . Yii::getAlias('#staff-no-image'), [
'alt' => $this->title,
'class' => 'js-thumbnail'
]);
}
?>
<div class="button-section">
<?php
echo Html::a('<i class="'. Common::ICON_IMAGE .'"></i> ' . Yii::t('app', 'Picture'), [
'images/upload-avatar',
'token' => $model_doctors->token
], [
'class' => "js-popup buttons tiny " . Common::LINK_IMAGE
]);
?>
</div>
</div>
</div>
<div class="image-form">
<div class="col-sm-12">
<div class="row">
<div class="col-xs-12 col-sm-6">
<?php
echo $form
->field($model_doctors, 'first_name')
->textInput([
'autofocus' => true,
'maxlength' => true
])
?>
</div>
<div class="col-xs-12 col-sm-6">
<?php
echo $form
->field($model_doctors, 'last_name')
->textInput([
'maxlength' => true
])
?>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6">
<?php
echo $form
->field($model_doctors, 'email')
->textInput([
'maxlength' => true
])
?>
</div>
<div class="col-xs-12 col-sm-6 selectBox">
<?php
echo $form
->field($model_doctors, 'status')
->dropDownList(Common::get_array('active_inactive'), [
'prompt' => '- Status -'
])
?>
</div>
</div>
</div>
</div>
</div>
<div class="section">
<h3 class="heading">Residence Details</h3>
<div class="res-details">
<div class="col-sm-9">
<?php
echo $form
->field($model_doctors, 'residence_address')
->textArea(['maxlength' => true]);
?>
</div>
<div class="col-sm-3">
<?php
echo $form
->field($model_doctors, 'residence_telephone')
->textInput(['maxlength' => true]);
?>
</div>
<div class="col-sm-3">
<?php
echo $form
->field($model_doctors, 'mobile')
->textInput(['maxlength' => true])
?>
</div>
</div>
</div>
<div class="section">
<?php
DynamicFormWidget::begin([
'widgetContainer' => 'jsDoctorsClinics', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.clinics-container', // required: css class selector
'widgetItem' => '.js-clinic-clonable', // required: css class
// 'insertPosition' => 'top',
'limit' => 5, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.clinic-add-item', // css class
'deleteButton' => '.clinic-remove-item', // css class
'model' => $model_doctor_clinics[0],
'formId' => $model_doctors->formName(),
'formFields' => [
'name',
'incharge',
'address',
'landline',
'landmark',
'status'
]
]);
?>
<h3 class="heading">Clinics (max. 5)</h3>
<div class="doctor-clinics">
<div class="clinics-container">
<?php
foreach ($model_doctor_clinics as $i => $clinic)
{
?><div class="col-sm-12 clinic js-clinic-clonable clonable">
<div class="row">
<div class="col-md-8 col-sm-12">
<?php
// necessary for update action.
if(!$clinic->isNewRecord)
{
echo Html::activeHiddenInput($clinic, "[{$i}]id");
}
echo $form
->field($clinic, "[{$i}]name")
->textInput(['maxlength' => true]);
?>
</div>
<div class="col-md-4 col-sm-12">
<?php
echo $form
->field($clinic, "[{$i}]incharge")
->textInput(['maxlength' => true]);
?>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<?php
echo $form
->field($clinic, "[{$i}]address")
->textArea(['maxlength' => true]);
?>
</div>
<div class="col-sm-4">
<?php
echo $form
->field($clinic, "[{$i}]landline")
->textInput(['maxlength' => true]);
?>
</div>
<div class="col-sm-4">
<?php
echo $form
->field($clinic, "[{$i}]landmark")
->textInput(['maxlength' => true])
?>
</div>
</div>
<div class="row">
<div class="col-sm-4 selectBox">
<?php
echo $form
->field($clinic, "[{$i}]status")
->dropdownList(Common::get_array("active_inactive"), [ 'prompt' => ' - Select - ' ])
?>
</div>
<div class="col-sm-4 col-sm-offset-4">
<div class="form-group">
<label class="hidden-480 control-label"> </label>
<button type="button" class="clinic-remove-item width-100 buttons <?php echo Common::LINK_CLOSE; ?>"<?php
if($clinic->isNewRecord || (!$clinic->isNewRecord && (count($model_doctor_clinics) > 1) && ($i == 0)))
{
echo ' style="display: none;"';
}
?>><i class="<?php echo Common::ICON_DELETE; ?>"></i> Delete</button>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
<div class="col-sm-12 mt-auto mb-auto js-clinic-add-more">
<div class="form-group col-md-4 col-md-offset-4 mb0">
<i class="<?php echo Common::ICON_ADD; ?>"></i> Add more clinics
</div>
</div>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<div class="boxFooter">
<?php
if(!$model_doctors->isNewRecord)
{
echo $form
->field($model_doctors, 'token', [
'options' => [ 'tag' => false ]
])->hiddenInput([
'readonly' => 'readonly'
])->label(false);
}
else
{
echo $form
->field($model_doctors, 'token', [
'options' => [ 'tag' => false ]
])->hiddenInput([
'value' => Common::generate_token()
])->label(false);
}
echo $form
->field($model_doctors, 'uploaded_files', [
'options' => [ 'tag' => false ]
])->hiddenInput([
'readonly' => 'readonly'
])->label(false);
echo $form
->field($model_doctors, 'password_hash', [
'options' => [ 'tag' => false ]
])->hiddenInput([
'readonly' => 'readonly',
'value' => Common::generate_token()
])->label(false);
echo $form
->field($model_doctors, 'auth_key', [
'options' => [ 'tag' => false ]
])->hiddenInput([
'readonly' => 'readonly',
'value' => Common::generate_token()
])->label(false);
?>
<?php
echo Html::submitButton('<i class="' . Common::ICON_SUBMIT . '"></i> ' . Yii::t('app', 'Submit'), [
'class' => 'buttons mini default pull-right'
])
?>
<?php
echo Html::button('<i class="' . Common::ICON_CLOSE . '"></i> ' . Yii::t('app', 'Cancel'), [
'class' => 'js-cancel buttons mini pull-left ' . Common::LINK_CLOSE
])
?>
</div>
<?php ActiveForm::end(); ?>
I think that $model->save(false) skip unique index validation.

Create using modal in yii2 something wrong

I've created form using modal. The problem is button "Create" in views/index.php. Proccess testing paging & searching successfully, but after that when I to click button "created" in views/index.php. Form create with modal not display, I don't know why.
Code in controller
public function actionCreate()
{
$model = new Donatur();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', 'Data berhasil disimpan!');
return $this->redirect(['index']);
return $this->refresh();
} else {
if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', ['model' => $model]);
}
else{
return $this->render('create', ['model' => $model]);
}
}
}
Code in views/index.php
<?php \yii\widgets\Pjax::begin(['timeout' => false, 'id' => 'pjax-gridview']); ?>
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* #var $this yii\web\View */
/* #var $searchModel app\models\SearchDonatur */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Data Donatur';
?>
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Informasi!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>
<?php if (Yii::$app->session->hasFlash('delete')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Informasi!</h4>
<?= Yii::$app->session->getFlash('delete') ?>
</div>
<?php endif; ?>
<div class="donatur-index">
<?php Pjax::begin(['timeout'=>false,'id'=>'pjax-gridview']); ?>
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::button('Tambah Donatur', ['value'=>Url::to('create'),'class' => 'btn btn-success','id'=>'modalButton']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'emptyCell'=>'-',
'summary'=>'',
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'kode_donatur',
'value'=>'kode_donatur',
'contentOptions'=>['style'=>'width: 200px;']
],
[
'attribute'=>'nama_donatur',
'value'=>'nama_donatur',
'contentOptions'=>['style'=>'width: 250px;']
],
[
'attribute'=>'alamat',
'value'=>'alamat',
'contentOptions'=>['style'=>'width: 350px;']
],
[
'attribute'=>'telepon',
'value'=>'telepon',
'contentOptions'=>['style'=>'width: 290px;']
],
[
'class' => \yii\grid\ActionColumn::className(),
'header' => 'Aksi',
'template' => '{update} {delete}',
'buttons' => [
'update' => function($url, $model) {
$icon = '<span class="glyphicon glyphicon-pencil"></span>';
return Html::a($icon, $url,[
'data-toggle' => "modal",
'data-target' => "#donaturModal",
]);
},
'delete' => function($url, $model) {
$icon = '<span class="glyphicon glyphicon-trash"></span>';
return Html::a($icon, $url,
[
'data-confirm' => "Apakah yakin dihapus ?",
'data-method' => 'post',
]);
},
]
],
],
]); ?>
<?php \yii\widgets\Pjax::end() ?>
<?php Pjax::end(); ?>
</div>
<?php
// for modal update
Modal::begin([
'id' => 'donaturModal',
'header' => '<h1 align="center">Ubah Data Donatur</h1>',
]);
Pjax::begin(['id'=>'pjax-modal', 'timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,]);
Pjax::end();
Modal::end();
?>
<?php
// for modal update
$this->registerJs('
$("#donaturModal").on("shown.bs.modal", function (event) {
var button = $(event.relatedTarget)
var href = button.attr("href")
$.pjax.reload("#pjax-modal", {
"timeout":false,
"url":href,
"replace":false,
});
})
');
?>
<?php
// for modal create
Modal::begin([
'header' => '<h1 align="center">Tambah Donatur</h1>',
'id' => 'modal',
]);
echo "<div id='modalContent'><div>";
Modal::end()
?>
<?php
// for modal create
Modal::begin([
'id' => 'modal',
'header' => '<h1 align="center">Ubah Data Donatur</h1>',
]);
Pjax::begin(['id'=>'pjax-modal', 'timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,]);
Pjax::end();
Modal::end();
?>
<?php
// for modal create
$this->registerJs('
$("#modal").on("shown.bs.modal", function (event) {
var button = $(event.relatedTarget)
var href = button.attr("href")
$.pjax.reload("#pjax-modal", {
"timeout":false,
"url":href,
"replace":false,
});
})
');
?>
Code in views/create.php
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;
use yii\bootstrap\Modal;
use yii\helpers\Url;
use yii\db\ActiveRecord;
/* #var $this yii\web\View */
/* #var $model app\models\Donatur */
?>
<h2 align="center">Form Donatur</h2>
<?php
echo "&nbsp";
echo "&nbsp";
?>
<?php $form = ActiveForm::begin([
'layout' => 'horizontal',
'enableAjaxValidation' => false,
'id' => 'create-form',
]); ?>
<?= $form->field($model, 'kode_donatur')->textInput(['readonly' => true, 'style'=>'width:100px']) ?>
<?= $form->field($model, 'nama_donatur')->textInput(['style'=>'width:350px']) ?>
<?= $form->field($model, 'alamat')->textArea(['rows' => 3, 'style'=>'width:350px']) ?>
<?= $form->field($model, 'telepon')->textInput(['style'=>'width:350px']) ?>
<div class="form-group">
<div class="col-sm-offset-4">
<?= Html::submitButton('Simpan', ['class'=> 'btn btn-primary']) ?>
<?php
echo "&nbsp";
echo "&nbsp";
echo Html::a('Keluar', ['index'],[
'class'=>'btn btn-success',
'onclick' =>'$("#modal").modal("hide");
return false;'
]);
?>
</div>
</div>
<?php ActiveForm::end();?>
The before I created form created with modal follow this link : click
I think problem with button handler.
Probably you forgot to add handler:
$(function(){
$('#modalButton').click(function(){ ... });
})

Codeigniter validate form is not working

I have the same implementation for my login for and is working, but on my contact form it is not, and I have no error message just re routed to the home page.
the weird thing is if in my controller i implement the index function like this:
public function index() {
$this->myprocess();
}
and my view using
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact',$attributes);
?>
instead of calling my function myprocess all the validations work but no use for a form with out my header footers etc.
bellow that is how i want my code to work i hope yall can help me.
my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class contact extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('contact_m');
}
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
$this->load->view('template', $data);
}
public function myprocess(){
$this->form_validation->set_rules('dfname', 'Name', 'required|trim|xss_clean|max_length[40]');
$this->form_validation->set_rules('dfemail', 'Email', 'required|trim|xss_clean|valid_email|max_length[50]|callback__verifyemail');
$this->form_validation->set_rules('dfmsg', 'dfmsg', 'trim|xss_clean');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('contact_v');
}
else
{
$form_data = array(
'dfname' => set_value('dfname'),
'dfemail' => set_value('dfemail'),
'dfmsg' => set_value('dfmsg')
);
if ($this->contact_m->SaveForm($form_data) == TRUE)
{
redirect('contact/success');
}
else
{
echo 'An error occurred saving your information. Please try again later';
}
}
}
function success()
{
echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';
}
public function verifyemail(){
$name = $this->input->post('dfName');
$pass = $this->input->post('dfemail');
if($this->contact_m->email_exist($name,$pass)){
if ($this->session->userdata('site_lang') == 'portuguese')
{
$this->form_validation->set_message('_verifyuser','Usuario Inexistente!');
}else{
$this->form_validation->set_message('_verifyuser','User Not Found!');
}
$this->index();
return false;
}else{
return true;
}
}
}
?>
my view:
<div class="container">
<div class="row">
<div class=" col-md-4 col-md-offset-4">
<?php echo br(2)?>
<div class="account-wall drop-shadow">
<?php
$title = $this->my_library->my_title($this->session->userdata('site_lang'),FORM_CONTACT);
echo '<h1 class="text-center login-title">'. $title. '</h1>';
echo br(1)
?>
<?php
$attributes = array('class' => 'form-contact', 'id' => 'myform2');
echo form_open('contact/myprocess',$attributes);
?>
<p>
<label for="dfname">Name</span></label>
<?php echo form_error('dfname'); ?>
<input id="dfname" type="text" class="form-control" placeholder="Name" name="dfname" maxlength="40" value="<?php echo set_value('dfname'); ?>" autofocus />
<?php echo br(1)?>
</p>
<p>
<label for="dfemail">Email</span></label>
<?php echo form_error('dfemail'); ?>
<input id="dfemail" type="text" class="form-control" placeholder="Email" name="dfemail" maxlength="50" value="<?php echo set_value('dfemail'); ?>" />
<?php echo br(1)?>
</p>
<p>
<label for="dfmsg">Message</label>
<?php echo form_error('dfmsg'); ?>
<?php echo form_textarea( array( 'name' => 'dfmsg', 'rows' => '4', 'cols' => '43', 'value' => set_value('dfmsg') ) )?>
<?php echo br(1)?>
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php form_close();?>
</div>
</div>
</div>
</div>
<?php echo br(5)?>
your callback function for validation need an underscore for prefix name :
public function _verifyemail()
and you need to call the process function :
public function index()
{
$data = array('title' => 'Contact', 'main_content' => 'contact_v');
if($this->input->post())
$this->myprocess();
$this->load->view('template', $data);
}
So after all this days and examining all my code and re-writing all of it i found the problem.
for some reason this line wasnt working : echo form_close(); so my first form was aways open messing up asll my validation after writing on all of then it starting working.

Input Form Using Codeigniter and Bootstrap 3

I'm using Codeigniter, styled with Bootstrap 3 to build a website.
I can't stylize the text-fields built by the PHP/Form Helper, as I'm not sure where to use the tags, every solution I've tried has resulted in either an extra text field, or just the addon appearing, or nothing at all.
Controller
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('name', 'email', 'password'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('admin/user');
}
// Load the view
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->user_m->delete($id);
redirect('admin/user');
}
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
// Set form
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
// Process form
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
// Load view
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout ()
{
$this->user_m->logout();
redirect('admin/user/login');
}
public function _unique_email ($str)
{
// Do NOT validate if email already exists
// UNLESS it's the email for the current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->user_m->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', '%s should be unique');
return FALSE;
}
return TRUE;
}
}
View
<div class="modal-body">
<?php echo validation_errors(); ?>
<?php echo form_open();?>
<div class="container">
<div class="modal-header">
<h3>Log in</h3>
<p>Please log in using your credentials</p>
</div>
<table class="table">
<tr>
<td>Email</td>
<td><?php echo form_input('email'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo form_password('password'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Log in', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<div class="modal-footer">
© <?php echo date('Y'); ?> <?php echo $meta_title; ?>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
Bootstrap
<form class="form-signin" role="form">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="form-control" placeholder="email" required autofocus value="<?php echo set_value('email') ?>">
<input type="password" class="form-control" placeholder="password" required value"<?php echo set_value('password') ?>">
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
You just pass everything as an array to form_input
<?php echo form_input(['name' => 'email', 'id' => 'email', 'class' => 'form-control', 'value' => set_value('email')]); ?>
Here's your entire form as presented,
<?php echo form_open('controller/method', ['class' => 'form-signin', 'role' => 'form']); ?>
<h2 class="form-signin-heading">Please sign in</h2>
<?php echo form_input(['name' => 'email', 'id' => 'email', 'class' => 'form-control', 'value' => set_value('email'), 'placeholder' => 'Email']); ?>
<?php echo form_password(['name' => 'password', 'id' => 'password', 'class' => 'form-control', 'placeholder' => 'Password']); ?>
<label class="checkbox">
<?php echo form_checkbox(['name' => 'remember_me', 'value' => 1]); ?>
</label>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<?php echo form_close(); ?>