CodeIgniter Omnipay Przelewy24: Message: The email parameter is required - codeigniter-3

I try enable payment gateway Przelewy24 with Omnipay library for Codeigniter 3.
For this I install via composer both libraries.
Library:
https://github.com/mysiar-org/omnipay-przelewy24v1
and
https://github.com/thephpleague/omnipay
Then I create controller
Cart_contoller.php I add function
use Omnipay\Omnipay;
/**
* Payment with Przelewy24
*/
public function przelewy24_payment_post()
{
$przelewy24 = get_payment_gateway('przelewy24');
if (empty($przelewy24)) {
$this->session->set_flashdata('error', "Payment method not found!");
echo json_encode([
'result' => 0
]);
exit();
}
/** #var \Omnipay\Przelewy24\Gateway $gateway */
$gateway = Omnipay::create('Przelewy24');
$gateway->initialize([
'merchantId' => 'xxxx',
'posId' => 'xxxx',
'crc' => 'xxxxxxxxxxxx',
'testMode' => true,
]);
$params = array(
'sessionId' => 2327398739,
'amount' => 12.34,
'currency' => 'PLN',
'description' => 'Payment test',
'returnUrl' => 'www.xxxxxx',
'notifyUrl' => 'www.xxxxxxxxxxx',
'card' => array(
'email' => 'info#example.com',
'name' => 'My name',
'country' => 'PL',
),
);
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
$response->redirect();
} else {
echo 'Failed';
}
}
in view page I add:
<?php echo form_open('cart_controller/przelewy24_payment_post'); ?>
<div class="payment-icons-container">
<label class="payment-icons">
<?php $logos = #explode(',', $payment_gateway->logos);
if (!empty($logos) && item_count($logos) > 0):
foreach ($logos as $logo): ?>
<img src="<?php echo base_url(); ?>assets/img/payment/<?= html_escape(trim($logo)); ?>.svg" alt="<?= html_escape(trim($logo)); ?>">
<?php endforeach;
endif; ?>
</label>
</div>
<button id="submit" class="btn btn-primary" id="card-button">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
<?= trans("pay"); ?> <?= price_formatted($total_amount, $currency); ?>
</button>
<?php echo form_close(); ?><!-- form end -->
On button submit I get:
Type: Omnipay\Common\Exception\InvalidRequestException
Message: The email parameter is required
What I do wrong? Can anyone help me with this code how to correct integrate this gateway?

Related

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(){ ... });
})

Create form input using modal in yii2 is strange

I've tried for create form input using modal. When I implementation in browser is successfully. But when I testing for validation in the textfield, insted form input with using modal redirect to other page. For details, you can see this below.
When I implementation.
Testing validation redirect to other page.
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 create.php in view
<?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 $form = ActiveForm::begin(['layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}",
'horizontalCssClasses' => [
'label' => 'col-sm-4',
'offset' => 'col-sm-offset-4',
'wrapper' => 'col-sm-8',
'error' => '',
'hint' => '',
'button' => 'col-sm-4'
],
],
]); ?>
<?= $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:300px']) ?>
<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' =>'$("#donaturModal").modal("hide");
return false;'
]);
?>
</div>
</div>
<?php ActiveForm::end();?>
Code index.php in view
<?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
Modal::begin(['id' => 'donaturModal',]);
Pjax::begin(['id'=>'pjax-modal', 'timeout'=>false,
'enablePushState'=>false,
'enableReplaceState'=>false,]);
Pjax::end();
Modal::end();
?>
<?php
$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
Modal::begin([
'header' => '<h1 align="center">Tambah Donatur</h1>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'><div>";
Modal::end()
?>
Code AppAsset.php
<?php
/**
* #link http://www.yiiframework.com/
* #copyright Copyright (c) 2008 Yii Software LLC
* #license http://www.yiiframework.com/license/
*/
namespace app\assets;
use yii\web\AssetBundle;
/**
* #author Qiang Xue <qiang.xue#gmail.com>
* #since 2.0
*/
class AppAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
];
public $js = [
'js/main.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
Code main.js in folder web/js
$(function(){
//ambil form untuk tambah data
$("#modalButton").click(function(){
$("#modal").modal('show')
.find("#modalContent")
.load($(this).attr('value'));
});
});
EnableAjaxValidation of form :
<?php $form = ActiveForm::begin([
'layout' => 'horizontal',
'enableAjaxValidation' => true,
'id' => 'create-form',
...
]);
Controller
public function actionCreate()
{
$model = new Donatur();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if($model->save()) {
Yii::$app->session->setFlash('success', 'Data berhasil disimpan!');
}
else {
Yii::$app->session->setFlash('error', 'error message!');
}
return $this->redirect(['index']);
} else {
if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', ['model' => $model]);
}
else{
return $this->render('create', ['model' => $model]);
}
}
}

How to add Bootstrap Modal in Yii2?

<div class="create-job-form">
<?php
Modal::begin([
'header' => '<h4>Job Created</h4>',
'id' => 'jobPop',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<table width="5">
<?php $form = ActiveForm::begin(); ?>
<fieldset>
<legend>Order Details</legend>
<td>
<tr> <?= Html::activeHiddenInput($model, 'job_code', ['value' => rand(1, 10000)]) ?> </tr>
</td>
<td>
<tr><?= $form->field($model, 'job_description')->textInput(['maxlength' => true]) ?></tr>
</td>
<td>
<tr>
<?= $form->field($model, 'approved_date')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => true,
// modify template for custom rendering
'template' => '{input}',
'clientOptions' => [
'autoclose' => false,
'format' => 'dd-M-yyyy'
]
]); ?>
</tr>
</td>
<td>
<tr><?= $form->field($model, 'estimated_time')->dropDownList(['24hrs' => '24 Hours', '48hrs' => '48 Hours', '2-3d' => '2-3 Days', '3-4d' => '3-4 Days', '4-5d' => '4-5 Days', '5-6d' => '5-6 Days'], ['prompt' => 'Select Time']) ?></tr>
</td>
</fieldset>
</table>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary', 'id' => 'jobPop']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$(function() {
$('#jobPop').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
JS;
$this->registerJs($script);
?>
This is my form, I'm trying to get Modal when click on create button, so that View will be on Modal. what i'm doing wrong?
I need on form submit Modal should pop up and ask user Job has created do you want to send this information to client if user click yes then sms and email with above details should be send to client if user says no it should return to edit mode and the created job code should be flushed
How to achieve this in Yii2?
Ideal Situation:
have the modal in your layout file.
yii\bootstrap\Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
'closeButton' => [
'id'=>'close-button',
'class'=>'close',
'data-dismiss' =>'modal',
],
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => false, 'keyboard' => true]
]);
echo "<div id='modalContent'><div style='text-align:center'>"
. Html::img('#web/img/radio.gif')
. "</div></div>";
yii\bootstrap\Modal::end();
Add have a js file - with js code to load modal -
$(function() {
$(document).on('click', '.showModalButton', function() {
if ($('#modal').hasClass('in')) {
$('#modal').find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
} else {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
}
});
});
Include the js file in your application. assets/AppAsset.php :
public $js = ['js/ajax-modal-popup.js'];
Add the the css class: 'showModalButton' to all buttons that content in the modal.
...
'class'=>'btn showModalButton',
...
Modify you controller action to render content via ajax if request was done via ajax:
if(Yii::$app->request->isAjax) {
return $this->renderAjax('your-view-file', [
'model' => $model,
]);
}
Change Modal id from jobPop to modal.
e.g.
<?php
Modal::begin([
'header'=>'<h4>Job Created</h4>',
'id'=>'modal',
'size'=>'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
Bootsrap 4: https://www.yiiframework.com/extension/yiisoft/yii2-bootstrap4/doc/api/2.0/yii-bootstrap4-modal
Modal::begin([
'title' => 'Hello world',
'toggleButton' => ['label' => 'click me'],
]);
echo 'Say hello...';
Modal::end();

How do I use ViewScripts on Zend_Form File Elements?

I am using this ViewScript for my standard form elements:
<div class="field" id="field_<?php echo $this->element->getId(); ?>">
<?php if (0 < strlen($this->element->getLabel())) : ?>
<?php echo $this->formLabel($this->element->getName(), $this->element->getLabel());?>
<?php endif; ?>
<span class="value"><?php echo $this->{$this->element->helper}(
$this->element->getName(),
$this->element->getValue(),
$this->element->getAttribs()
) ?></span>
<?php if (0 < $this->element->getMessages()->length) : ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
<?php if (0 < strlen($this->element->getDescription())) : ?>
<span class="hint"><?php echo $this->element->getDescription(); ?></span>
<?php endif; ?>
</div>
Trying to use that ViewScript alone results in an error:
Exception caught by form: No file
decorator found... unable to render
file element
Looking at this FAQ revealed part of my problem, and I updated my form element decorators like this:
'decorators' => array(
array('File'),
array('ViewScript', array('viewScript' => 'form/field.phtml'))
)
Now it's rendering the file element twice, once within my view script, and extra elements with the file element outside my view script:
<input type="hidden" name="MAX_FILE_SIZE" value="8388608" id="MAX_FILE_SIZE" />
<input type="hidden" name="UPLOAD_IDENTIFIER" value="4b5f7335a55ee" id="progress_key" />
<input type="file" name="upload_file" id="upload_file" />
<div class="field" id="field_upload_file">
<label for="upload_file">Upload File</label>
<span class="value"><input type="file" name="upload_file" id="upload_file" /></span>
</div>
Any ideas on how to handle this properly with a ViewScript?
UPDATE: Based on Shaun's solution, here's my final code:
Form Element:
$this->addElement('file', 'upload_file', array(
'disableLoadDefaultDecorators' => true,
'decorators' => array('File', array('ViewScript', array(
'viewScript' => '_form/file.phtml',
'placement' => false,
))),
'label' => 'Upload',
'required' => false,
'filters' => array(),
'validators' => array(array('Count', false, 1),),
));
View Script:
<?php
$class .= 'field ' . strtolower(end(explode('_',$this->element->getType())));
if ($this->element->isRequired()) {
$class .= ' required';
}
if ($this->element->hasErrors()) {
$class .= ' errors';
}
?>
<div class="<?php echo $class; ?>" id="field_<?php echo $this->element->getId(); ?>">
<?php if (0 < strlen($this->element->getLabel())): ?>
<?php echo $this->formLabel($this->element->getFullyQualifiedName(), $this->element->getLabel());?>
<?php endif; ?>
<span class="value"><?php echo $this->content; ?></span>
<?php if ($this->element->hasErrors()): ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
<?php if (0 < strlen($this->element->getDescription())): ?>
<p class="hint"><?php echo $this->element->getDescription(); ?></p>
<?php endif; ?>
</div>
The answer is relatively simple as it happens. All you need do is specify the File decorator first, create a specific view script for the file input and specify false for the placement in the viewScript decorator arguments, this will effectively inject the output from the File decorator into the viewScript decorator e.g.
$element->setDecorators(array('File', array('ViewScript', array('viewScript' => 'decorators/file.phtml', 'placement' => false))));
Then in the new file element view script you simply echo $this->content in the script where you'd like the file input markup to be placed. Here's an example from a recent project, so ignore the markup if it looks a little odd, hopefully it will illustrate the point.
<label for="<?php echo $this->element->getName(); ?>" class="element <?php if ($this->element->hasErrors()): ?> error<?php endif; ?>" id="label_<?php echo $this->element->getName(); ?>">
<span><?php echo $this->element->getLabel(); ?></span>
<?php echo $this->content; ?>
<?php if ($this->element->hasErrors()): ?>
<span class="error">
<?php echo $this->formErrors($this->element->getMessages()); ?>
</span>
<?php endif; ?>
</label>
When rendered you will see this html for the element
<label for="photo" class="element" id="label_photo">
<span>Photo</span>
<input type="hidden" name="MAX_FILE_SIZE" value="6291456" id="MAX_FILE_SIZE">
<input type="file" name="photo" id="photo">
</label>
This is not a simple or ideal solution because it requires an extension of the File decorator... but it's rather frustrating that they didn't make the effort to separate the hidden element generation logic from the file input generation logic. I'm not sure if the file view helper handles the issue of an element being an array (that seems to be the reason they did it this way.)
Extension of File Decorator:
(the commented out part is what causes the extra input to be generated.)
<?php
class Sys_Form_Decorator_File extends Zend_Form_Decorator_File {
public function render($content) {
$element = $this->getElement();
if (!$element instanceof Zend_Form_Element) {return $content;}
$view = $element->getView();
if (!$view instanceof Zend_View_Interface) {return $content;}
$name = $element->getName();
$attribs = $this->getAttribs();
if (!array_key_exists('id', $attribs)) {$attribs['id'] = $name;}
$separator = $this->getSeparator();
$placement = $this->getPlacement();
$markup = array();
$size = $element->getMaxFileSize();
if ($size > 0) {
$element->setMaxFileSize(0);
$markup[] = $view->formHidden('MAX_FILE_SIZE', $size);
}
if (Zend_File_Transfer_Adapter_Http::isApcAvailable()) {
$apcAttribs = array('id' => 'progress_key');
$markup[] = $view->formHidden('APC_UPLOAD_PROGRESS', uniqid(), $apcAttribs);
}
else if (Zend_File_Transfer_Adapter_Http::isUploadProgressAvailable()) {
$uploadIdAttribs = array('id' => 'progress_key');
$markup[] = $view->formHidden('UPLOAD_IDENTIFIER', uniqid(), $uploadIdAttribs);
}
/*
if ($element->isArray()) {
$name .= "[]";
$count = $element->getMultiFile();
for ($i = 0; $i < $count; ++$i) {
$htmlAttribs = $attribs;
$htmlAttribs['id'] .= '-' . $i;
$markup[] = $view->formFile($name, $htmlAttribs);
}
}
else {$markup[] = $view->formFile($name, $attribs);}
*/
$markup = implode($separator, $markup);
switch ($placement) {
case self::PREPEND: return $markup . $separator . $content;
case self::APPEND:
default: return $content . $separator . $markup;
}
}
}
?>
Form setup in controller action:
$form = new Zend_Form();
$form->addElement(new Zend_Form_Element_File('file'));
$form->file->setLabel('File');
$form->file->setDescription('Description goes here.');
$decorators = array();
$decorators[] = array('File' => new Sys_Form_Decorator_File());
$decorators[] = array('ViewScript', array('viewScript' => '_formElementFile.phtml'));
$form->file->setDecorators($decorators);
$this->view->form = $form;
In action view:
<?php echo $this->form; ?>
In element script:
<div class="field" id="field_<?php echo $this->element->getId(); ?>">
<?php if (0 < strlen($this->element->getLabel())) : ?>
<?php echo $this->formLabel($this->element->getName(), $this->element->getLabel());?>
<?php endif; ?>
<span class="value">
<?php
echo $this->{$this->element->helper}(
$this->element->getName(),
$this->element->getValue(),
$this->element->getAttribs()
);
?>
</span>
<?php if (0 < $this->element->getMessages()->length) : ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
<?php if (0 < strlen($this->element->getDescription())) : ?>
<span class="hint"><?php echo $this->element->getDescription(); ?></span>
<?php endif; ?>
</div>
Output should be:
<form enctype="multipart/form-data" action="" method="post">
<dl class="zend_form">
<input type="hidden" name="MAX_FILE_SIZE" value="134217728" id="MAX_FILE_SIZE" />
<div class="field" id="field_file">
<label for="file">File</label>
<span class="value"><input type="file" name="file" id="file" /></span>
<span class="hint">Description goes here.</span>
</div>
</dl>
</form>
A problem with this solution is that the hidden elements don't render within the viewscript; this might be a problem if you're using the div as a selector in a client-side script...
What I've realized is, a custom decorator class will handle most fields except File fields.
Make sure your class implements the interface like so:
class CC_Form_Decorator_Pattern
extends Zend_Form_Decorator_Abstract
implements Zend_Form_Decorator_Marker_File_Interface
This worked for me.
This helped me fix my problem. I adjusted the code to wrap the file element inside a table. To make it work, simply remove the label from the viewdecorator and add the file element as follows:
$form->addElement('file', 'upload_file', array(
'disableLoadDefaultDecorators' => true,
'decorators' => array(
'Label',
array(array('labelTd' => 'HtmlTag'), array('tag' => 'td', 'class' => 'labelElement')),
array(array('elemTdOpen' => 'HtmlTag'), array('tag' => 'td', 'class' => 'dataElement','openOnly' => true, 'placement' => 'append')),
'File',
array('ViewScript', array(
'viewScript' => 'decorators/file.phtml',
'placement' => false,
)),
array(array('elemTdClose' => 'HtmlTag'), array('tag' => 'td', 'closeOnly' => true, 'placement' => 'append')),
array(array('row' => 'HtmlTag'), array('tag' => 'tr'))
),
'label' => 'Upload',
'required' => false,
'filters' => array(),
'validators' => array(array('Count', false, 1), ),
));
I've found a work-around that avoids the ViewScript altogether.
First, the element definition:
$this->addElement('file', 'upload_file', array(
'disableLoadDefaultDecorators' => true,
'decorators' => array(
'File',
array(array('Value'=>'HtmlTag'), array('tag'=>'span','class'=>'value')),
'Errors',
'Description',
'Label',
array(array('Field'=>'HtmlTag'), array('tag'=>'div','class'=>'field file')),
),
'label' => 'Upload File',
'required' => false,
'filters' => array('StringTrim'),
'validators' => array(),
));
Second, after the form class has been instantiated, I mimic the behavior of my ViewScript:
$field = $form->getElement('upload_file');
$decorator = $field->getDecorator('Field');
$options = $decorator->getOptions();
$options['id'] = 'field_' . $field->getId();
if ($field->hasErrors()) {
$options['class'] .= ' errors';
}
$decorator->setOptions($options);
I guess that I should look into class-based decorators. Maybe there's more flexibility there?
The easiest thing to do is to add no markup at all to the output in your custom File Decorator:
class Custom_Form_Decorator_File extends Zend_Form_Decorator_File {
public function render($content) {
return $content;
}
}
now you can do whatever you want in your viewscript for this file element (output the file input field and all hidden fields you need on your own).
Just in case you have followed #Shaun's answer and you are still getting the error: make sure that you've disabled default decorators for the element in question (take look at line 2):
$this->addElement('file', 'upload_file', array(
'disableLoadDefaultDecorators' => true,
'decorators' => array('File', array('ViewScript', array(
'viewScript' => '_form/file.phtml',
'placement' => false,
))),
'label' => 'Upload',
'required' => false,
'filters' => array(),
'validators' => array(array('Count', false, 1),),
));