yii2 append data through renderAjax missing in post data - php

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,
]);
}

Related

Saving data to database using a modal

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,
]);
}

binding values submitted from a View to a Controller

I am coding a form to get user input and then pass that information to a controller and execute a function based on that, at this point I can not pass the data to the controller using POST method, I get empty vars.
So the Controller function display the view form correctly, I can type on the textboxes, after press submit button I get a setFlash custom message that the parameters are empty. I am using a model class with just two parameters.
a) This is the model:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class SendmailForm extends Model
{
public $template;
public $emtransport;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['template', 'emtransport'], 'required'],
];
}
}
b) This is the view:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;
$this->title = 'Send Mail';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-contact">
<h1><?= Html::encode($this->title) ?></h1>
<?php if (Yii::$app->session->hasFlash('sminfo')): ?>
<div class="alert alert-success">
<?= Yii::$app->session->getFlash('sminfo');?>
</div>
<?php else: ?>
<p>
SendMail Exercise. Please choose needed options bellow:
</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'sendmail-form']); ?>
<?= $form->field($model, 'template')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'emtransport') ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'value'=>'one', 'name'=>'sendbtn']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<?php endif; ?>
</div>
And this is the controller's function:
public function actionSendmail(){
$model = new SendmailForm();
if ($model->load(Yii::$app->request->post())) {
$template = Yii::$app->request->post('template');
$emailTransport = Yii::$app->request->post("emtransport");
if($emailTransport=="local"){
for($i=0;$i<=2;$i++){
$xclient = 'client' . $i;
\app\models\User::findByUsername($xclient)->sendMail($template, 'Welcome To XYZ Services', ['accountInfo' => 'www.mysite.com']);
}//end of for loop
Yii::$app->session->setFlash("sminfo", "Emails sent successfully to the Clients");
return $this->refresh();
}//end of second if loop
else{
Yii::$app->session->setFlash("sminfo", "Params could not be verified!. Contact Tech Support");
return $this->refresh();
}
}//end of post if loop
return $this->render('sendmail', [
'model' => $model,
]);
}
The idea is to get the values from the view, at this moment I am getting empty values-
Two parts below:
$template = Yii::$app->request->post('template');
$emailTransport = Yii::$app->request->post("emtransport");
Change the following:
$template = $model->template;
$emailTransport = $model->emtransport;
After editing
public function actionSendmail(){
$model = new SendmailForm();
if ($model->load(Yii::$app->request->post())) {
$template = $model->template;
$emailTransport = $model->emtransport;
if($emailTransport=="local"){
for($i=0;$i<=2;$i++){
$xclient = 'client' . $i;
\app\models\User::findByUsername($xclient)->sendMail($template, 'Welcome To XYZ Services', ['accountInfo' => 'www.mysite.com']);
}//end of for loop
Yii::$app->session->setFlash("sminfo", "Emails sent successfully to the Clients");
return $this->refresh();
}//end of second if loop
else{
Yii::$app->session->setFlash("sminfo", "Params could not be verified!. Contact Tech Support");
return $this->refresh();
}
}//end of post if loop
return $this->render('sendmail', [
'model' => $model,
]);
}
I did some changes to the Controller and now it works, those are them:
//at the beginning of the Controller:
use app\models\SendmailForm;
//two lines changed in the function:
$model->template = $_POST['SendmailForm']['template'];
$model->emtransport = $_POST['SendmailForm']['emtransport'];
That's all I needed. Best regards

How to save data into a DB from a Modal popup in Yii2?

I have a plain view which is saving data correctly into a DB, however when I put that view into a Modal popup into another page it is not saving any data into the DB, the Modal is just displaying. What else need to be done in order to save the data into a DB from the popup? Thanks
This is the Controller:
public function actionEditMyPopup()
{
$model = new MyPopupForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->insertEditMyPopup();
return $this->renderAjax('edit-mypopup', ['model' => $model]);
} else {
return $this->renderAjax('edit-mypopup', ['model' => $model]);
}
}
This is the View of the popup:
<?php Pjax::begin(['enablePushState' => false]); ?>
<?php $form = ActiveForm::begin(['id' => 'edit-mypopup-form', 'options' => ['data-pjax' => true],]); ?>
<?= $form->field($model, 'attribute1') ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'edit-mypopup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
And the Model has the variables declaration and the function insertEditMyPopup() that insert data into the DB.
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class EditMyPopupForm extends Model
{
public $attribute1;
public function rules()
{
return [
[['attribute1'], 'required'],
];
}
public function insertEditMyPopup()
{
//attributes is the name of the table
$a = new attributes();
$a->att1 = $this->attribute1;
$a->save();
}//end function
}//end class
I have overcome the issue by adding the following code on the js file:
$('body').on("click", "form#edit-mypopup-form", function() {
var form = $(this);
if (form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(results){
$(form).find('.results').html(results);
}
});
return false;
});

How to display success message if users was added to the database in Yii2?

I know this is a dumb question, but I just started learning with Yii2. I haven't found any useful information here related to this, so. What I need to do is display a message if the user was added to the database successfuly. Could somoene help me to solve this? I've no idea where it has to be written: in a model, controller or view.
Here is my controller action:
public function actionCreate()
{
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
return $this->redirect(['create']);
}
return $this->render('create', [
'model' => $model,
]);
}
Here is my view:
<div class="employee-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'surname')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'employment_date')->textInput() ?>
<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>
Now what is happening is that the script doesn't allow to enter the date, which is later than today's date and also doesn't allow to enter a string into the date field. So to be clear, if the user has entered correct information, I need to add the message that would say "Users has been entered to the database successfully".
Thanks for any help!
Set flash message in your controller. like below.
Yii::$app->session->setFlash('flashMsg', 'flash Msg or any kind of content like variables');
and show this message in your view page. like below.
<?php if (Yii::$app->session->hasFlash('flashMsg')){ ?>
<div class="alert alert-success">
<!-- flash message -->
<?php Yii::$app->session->getFlash('flashMsg'); ?>
</div>
<?php } ?>
You can use the Yii::$app->session->setFlash method in your controller with no need to add anything in the view:
public function actionCreate()
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
Yii::$app->session->setFlash('success', 'User added');
return $this->redirect(['create']);
}
else {
Yii::$app->session->setFlash('error', 'Error adding user');
}
return $this->render('create', [
'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

Categories