Saving data to database using a modal - php

I have a problem.
I need to open a modal to insert data in a table in the form of another table.
I can open a modal using Ajax with the view of the create view using the actionCreate from the controller, but when i clic save in the modal, the controller redirect me to the action view by default, and if i chage that, it open the full view in the current tab.
The problem was temporary resolved by making a redirect to the view that the modal should be in the if condition, but when i test to insert invalid data, the view render full-windowed with the message errors (in ajax render).
Also, the data always is save.
I know there's a way to render it in the modal without change view, but i'm new and not have any experience working with modals.
Need your help please.
There's my view file:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use yii\bootstrap\Modal;
use yii\helpers\Url;
use app\models\Catalogo;
/* #var $this yii\web\View */
/* #var $model app\models\Articulo */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="articulo-form">
<?php $form = ActiveForm::begin(['id'=>'articuloCreate']); ?>
<?= $form->field($model, 'ID_CATALOGO')->dropDownList(
ArrayHelper::map(Catalogo::find()->all(),'ID_CATALOGO','NOMBRE_CATALOGO'),
[
'style'=>'width:500px',
'prompt'=>'Seleccionar catálogo',
]); ?>
<?= Html::button('Agregar catálogo', [
'value' => Url::to(['catalogo/create']),
'class' => 'btn btn-primary',
'id' => 'BtnModalCatalogo',
'data-toggle'=> 'modal',
'data-target'=> '#catalogo',
]) ?>
<?php ActiveForm::end(); ?>
The modal in the same view:
<?php
Modal::begin([
'header' => 'Crear catálogo',
'id' => 'catalogo',
'size' => 'modal-md',
]);
echo "<div id='modalContent'>BtnModalCatalogo</div>";
Modal::end();
?>
There's more code, but i think is pointless putting it.
This is my JS:
$('#BtnModalCatalogo').click(function(e){
e.preventDefault();
$('#catalogo').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
return false;
});
And this is the action create in the controller:
public function actionCreate()
{
$model = new Catalogo();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->ID_CATALOGO]);
}
if(Yii::$app->request->isAjax){
return $this->renderAjax('create', [
'model' => $model,
]);
}
return $this->render('create', [
'model' => $model,
]);
}
Just in case, this is the action view:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
First of all, thanks.
At the beggining, i expectet that the controller should load any other views in the modal, but not was like that.

This action only responds when the action is called via ajax and will only redirect if the model is saved.
public function actionCreate()
{
$model = new Catalogo();
if ($model->load(Yii::$app->request->post())) {
if($model->save()) return $this->redirect(['view', 'id' => $model->ID_CATALOGO]);
}
return $this->renderAjax('create', [
'model' => $model,
]);
}

Related

Value not updated in databases after validation and save success

Hi everyone i'm having trouble with my software developed with yii2.
I Have a model called Anagrafica and with its primary key id. With this model everything works.
I also have a model called AnagraficaOpzioniCarriera which extend the first one.
I have a view anagrafica/index that show a Kartik grid with the data of people enrolled that you can find in anagrafica. Admin user can update the data of an Anagrafica model by clicking on an the attribute "cognome" that render to anagrafica/update.
this is the command that call the controller AnagraficaController to reach anagrafica/update
'cognome'=>Grid::Labels('cognome',['anagrafica/update'],\app\helpers\Permits::allow('anagrafica','update'),'id','btn','info','10%'),
This is AnagraficaController
public function actionUpdate($id,$error=0,$message='')
{
$id = (int)$id;
$model = Anagrafica::findOne(['id' => $id]);
$model->scenario = 'update';
if ($model->load(Yii::$app->request->post())) {
if($model->validate()){
}
if($model->save(false)){
return $this->redirect(['anagrafica/update','id'=>$model->id]);
}
}
}
return $this->render('update', ['model' => $model, 'extended'=>true]);
}
i removed some portions of code to semplify it, but this is the core.
One time the view anagrafica/update is reached in this page i have an ActiveForm to modify data of the model and i have a render to a grid that show the attributes contained in AnagraficaOpzioniCarriera about the $model that i'm updating.
<?= $this->render('_opzioni_carriera',['parent'=>$model]); ?>
anagrafica/_opzioni_carriera view contain a Kartik grid that shows the column in the model AnagraficaOpzioniCarriera
<?php
use kartik\grid\GridView;
use kartik\select2\Select2;
use kartik\widgets\ActiveForm;
use kartik\editable\Editable;
use kartik\widgets\SwitchInput;
use yii\helpers\ArrayHelper;
use app\helpers\Autoconfigurazione;
use app\models\AnagraficaOpzioniCarriera;
use app\helpers\Grid;
use yii\helpers\Html;
use app\helpers\UserInfo;
/* #var $this yii\web\View */
/* #var $model app\models\AnagraficaOpzioniCarriera*/
$model = new AnagraficaOpzioniCarriera(['scenario'=>'search']);
?>
<div class="">
<?php
echo GridView::widget([
'options'=>[
'id'=>'opzioni_carriera',
],
'dataProvider'=> $model->search($parent->id,Yii::$app->request->queryParams),
'showPageSummary'=>false,
'headerRowOptions'=>['class'=>'kartik-sheet-style'],
'pjax'=>true, // pjax is set to always true for this demo
'pjaxSettings'=>[
'neverTimeout'=>true,
],
'toolbar'=> [
[
'content'=>''
],
],
'panel'=>[
'heading'=>false,
'footer'=>false,
'after'=>false,
],
'columns' => Grid::gridColumns([
'model'=>$model,
'checkbox'=>false,
'remove'=>Grid::gridRemove($model),
'extraOptions' =>[
'cashback' =>Grid::YNColumn('cashback',['anagrafica-opzioni-carriera/update', 'id' => $parent->id],'left',true,'5%'),
'compensa'=>Grid::YNColumn('compensa',['anagrafica-opzioni-carriera/update', 'id' => $parent->id],'left',true,'5%'),
'associazione'=>Grid::YNColumn('associazione',['anagrafica-opzioni-carriera/update', 'id' => $parent->id],'left',true,'5%'),
'formazione'=>Grid::YNColumn('formazione',['anagrafica-opzioni-carriera/update', 'id' => $parent->id],'left',true,'5%'),
],
]);
?>
</div>
cashback, compensa etc.. are the attributes in the model AnagraficaOpzioniCarriera.
Here when i try to update this attributes everything looks fine, the function model->validate() and model->load returns true value, but at the end of the process doesn't works.
Honestly i don't know what i have to return from the function of the controller.
public function actionUpdate($id)
{
$model = AnagraficaOpzioniCarriera::findOne(['id_anagrafica' => $id]);
if (!$model) {
// Se l'anagrafica opzioni carriera non esiste, genera un'eccezione 404
throw new \yii\web\NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
$model->scenario = 'update';
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if(Yii::$app->request->post('cashback') != null) $model->cashback = Yii::$app->request->post('cashback');
if(Yii::$app->request->post('compensa') != null) $model->cashback = Yii::$app->request->post('compensa');
if(Yii::$app->request->post('associazione') != null) $model->cashback = Yii::$app->request->post('associazione');
if(Yii::$app->request->post('formazione') != null) $model->cashback = Yii::$app->request->post('formazione');
if ($model->save()) {
return Json::encode(["success" => true, 'message' => 'Dati aggiornati']);
}
}
// Mostra il form di modifica
return $this->render('_opzioni_carriera', [
'parent' => $model,
]);
}
anyone can help me? i hope i explained my problem in a good form, but my english is not the best, i know. Anyway thanks in aadvance to everyone who want to try to help me, if you need anything other you can easily ask.
I tried every everything, also a logger but nothing worked
Like someone suggest these are the rules of the model AnagraficaOpzioni, but like i said prevously model->validate() works, for this reason i think the problem is not over there
public function rules()
{
return [
[['id_anagrafica'], 'required'],
[['id_anagrafica'], 'integer'],
[['cashback', 'compensa', 'associazione', 'formazione'], 'required', 'on'=>['update']],
[['cashback', 'compensa', 'associazione', 'formazione'], 'integer'],
[['id_anagrafica', 'cashback', 'compensa', 'associazione', 'formazione',], 'safe', 'on'=>['search']],
];
}

Yii2 rendering view doesn't work correctly

I have 3 tables:
Order
Ordered_number
Number
Ordered_number connects the other two - it has order_id and number_id columns.
In my Index Action, I want to render view named "call", where I have a form with choosing one order. When I submit which order I want, I want to go to actionCall and send there numbers connected with this order. Something isn't correct and I think I may be doing something wrong.
public function actionIndex()
{
$model = new \common\models\Order();
if ($model->load(Yii::$app->request->post())){
$numery = \common\models\Number::find()
->joinWith('ordered_number')
->where(['ordered_number.order_id' => $model->id]);
return $this->redirect(['/call', 'numery' => $numery]);
} else {
$this->render('call', ['model' => $model]);
}
}
When I open my actionIndex it displays a blank page instead of rendering a view that I want.
My "call" view:
<?php
use common\models\Customer;
use common\models\Order;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\View;
use yii\widgets\ActiveForm;
/* #var $this View */
/* #var $form ActiveForm */
/* #var $model Order */
var_dump($this);
die();
echo "<h1>Dodaj numery do przedzwonienia</h1>";
echo "Wybierz zamówienie, którego numery chcesz przedzwonić: ";
$form = ActiveForm::begin();
$form->field($model, 'id')->dropDownList(ArrayHelper::map(Customer::find()->all(), 'id', 'id'));
Html::submitButton("Przedzwoń", ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']);
ActiveForm::end();
I added var_dump in my view, and it displays it, but without var_dump and die() command, there is simply blank page without text I want to be next.
Missing return statement in else
return $this->render('call', ['model' => $model]);

yii2 append data through renderAjax missing in post data

I have two model A and B , In Model A form append Model B from dynamically,but when am click create button ,I am not getting model B data in POST.where I am doing wrong please help..
Model A Form(view)
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
use yii\web\View;
$script = <<< JS
$.ajax({
type :'POST',
data: {total_form:1},
cache : true,
url : '/stag_str/web/index.php/activities/create',
success : function(data) {
$('.p_scents').append(data);
},
});
JS;
$this->registerJs($script);
?>
<div class="currency-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'currency_name')->textInput(['maxlength' => true,'style'=>'width:150px']) ?>
<div class="p_scents"></div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Model A controller
public function actionCreate(){
$model = new Currency();
if ($model->load(Yii::$app->request->post())) {
print_r($_POST);exit;
return $this->redirect(['view', 'id' => $model->currency_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Model B Form which I am rendering through Ajax call
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Activities */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="activities-form">
<?php $form = ActiveForm::begin(['id' => 'activity' ]); ?>
<?= $form->field($model, 'activity_name')->textInput(['maxlength' => true]) ?>
<?php ActiveForm::end(); ?>
</div>
Model B action using renderAjax
public function actionCreate()
{
$model = new Activities();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->activity_id]);
} elseif ( Yii::$app->request->isAjax ){
return $this->renderAjax('_form', [
'model' => $model,
]);
}
}
I am not getting Model B form data while saving Model form A..
Ideally, when you are dealing with AJAX Calls from View. you Must provide an ID to your form as below;
$form = ActiveForm::begin([ 'id' => 'activity-form' ]);
when you handle any kind of request inside the Controllers, you must first check the type of request when you re-render your form as below
elseif ( Yii::$app->request->isAjax ){
return $this->renderAjax('_form', [
'model' => $model,
]);
}

yii2 load a view that content a form into modal

I'm loading a view which is the result of a controller action:
public function actionCreate()
{
$modelCreate = new CreateForm();
$user = User::findOne(Yii::$app->user->id);
$postes = $this->postes($user);
if (Yii::$app->request->isAjax && $modelCreate->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($modelCreate);
}
if ($modelCreate->load(Yii::$app->request->post()) && Yii::$app->request->isPost){
$modelCreate->photo = UploadedFile::getInstance($modelCreate, 'photo');
if ($modelCreate->create()){
return $this->redirect(['site/view-accounts']);
}
}
return $this->renderAjax('create-account', ['modelCreate' => $modelCreate, 'postes' => $postes]);
}
Here's my script that loads the view:
$(function(){
$('#createModal').click(function(){
$('#newAccountModal').modal('show')
.find('#modalContentCreate')
.load($(this).attr('value'));
});
});
Here's the code of my modal:
<?php
Modal::begin([
'id' => 'newAccountModal',
'header' => '<h4>create account</h4>',
]);
?>
<div id ="modalContentCreate">
</div>
<?php Modal::end();?>
But it insert the all scripts after the form tag and then triggers an error: the xmlHttpRequest object is deprecated...
And the other script of form validation is not inserted at the end of body of main page.
How can I do trigger validation of my form and remove this error message?
to load content into a form, i would suggest using Pjax as the modal's content, like:
<?php
Modal::begin([
'id' => 'newAccountModal',
'header' => '<h4>create account</h4>',
]);
?>
<div id ="modalContentCreate">
<? \yii\widgets\Pjax::begin(['id' => 'pjax1', 'linkSelector' => 'a.my-pjax']) ?>
<?= $this->render('_form', ['model' => $model]) ?>
<? \yii\widgets\Pjax::end() ?>
</div>
<?php Modal::end();?>
the contained form must set the data-pjax option.
note the linkSelector for the Pjax widget. you can replace the modal's content with a link:
<?= \yii\helpers\Html::a('create account', ['account/create'], ['class' => 'my-pjax']) ?>
your controller action 'account/create' should handle your post and validation and return the
_form.php (view)
<? $form = \yii\widgets\ActiveForm::begin(['options' => ['data-pjax' => 1], 'action' => ['account/create']]) ?>
<?= $form->errorSummary($model) ?>
<?= $form->field($model, 'title') ?>
<?= \yii\helpers\Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<? \yii\widgets\ActiveForm::end() ?>
controller create action:
public function actionCreate()
{
$model = new \common\models\Account;
if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post()) && $model->validate()) {
// $model->save()
return $this->renderAjax('_view', ['model' => $model]);
}
return $this->renderAjax('_form', ['model' => $model]);
}
read the doc: http://www.yiiframework.com/doc-2.0/guide-input-forms.html#working-with-pjax

I already asked , but how to access view page without id value in the url

my view.php
<?php
echo
Html::beginForm(['contactpersons/update'], 'post',['id' => 'update-form']) .
'<input type="hidden" name="id" value="'.$model->id.'">
<a href="javascript:{}" onclick="document.getElementById(\'update-form\').submit();
return false;">Update</a>'.
Html::endForm();
?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
])
?>
my controller is
public function actionView($id)
{
$model = $this->findModel($id);
return $this->render('view', ['model' => $model]);
}
How to modify this for getting my view page without id value in the url.
Thanks in advance.
You could change it like this
public function actionView($id = null) {
$model = null;
if ($id !== null) {
$model = $this->findModel($id);
}
return $this->render('view', ['model' => $model]);
}
However in your view you execute the following code: $model->id
this won't work when the model isn't set yo anything. So you could create a new model ($model = new ModelClass()) when the $id is null.
Sidenote: this doesn't look like an view action but more like an edit action, so maybe change your action to actionEdit().
You can send data to your browser by two methods - POST and GET. So, if you want to hide id parameter, then you need to send your id as POST parameter, which is bad solution - it's hard to implement, because POST is usally sends when you submit a form.

Categories