Yii2 saving form with multiple models - forms

Hi I am very close to finish a project but got stuck saving a from with multiple models.
I have a grid that calls a controllers action that calls a form.
public function actionToday() {
$ID = $_GET["0"];
$modelCustomers = Customers::find()->where(['ID' => $ID])->one();;
$today = date("Y-m-d");
$beforeToday = 'DropinDate>'.$today;
$modelAttendance = Attendance::find()->where(['CustomersID' => $ID])->andwhere(['DropinDate' => $today])->one();
return $this->render('//attendance/_form-today-attendance', ['modelCustomers' => $modelCustomers, 'model' => $modelAttendance]);
}
In the form i have 3 main fields to update or in case is not record i need to create a new record.
This is the _form-today-attendance
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
?>
<?php $form = ActiveForm::begin(); ?>
<h3>Your Personal Details</h3>
<?= $form->field($modelCustomers, 'Name')->textInput(['readonly' => true]) ?>
<?= $form->field($model, 'DropinDate')->textInput(['readonly' => true]) ?>
<div class="attendance-form">
<?= $form->field($model, 'Dropin')->checkbox() ?>
<?= $form->field($model, 'Doctor')->checkbox() ?>
<?= $form->field($model, 'Lawyer')->checkbox() ?>
<?= $form->field($model, 'Observation')->textInput(['maxlength' => 250]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
When I debug i cant get anything happend in the Attendence model or the Customers model.
Any ideas?
Thanks a lot,
Eduardo

Try this function and check what you get.
public function actionToday()
{
$ID = $_GET["0"];
$modelCustomers = Customers::find()
->where(['ID' => $ID])
->one();;
$today = date("Y-m-d");
$beforeToday = 'DropinDate>' . $today;
$modelAttendance = Attendance::find()
->where(['CustomersID' => $ID])
->andwhere(['DropinDate' => $today])
->one();
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
//do something with $data
}
return $this->render('//attendance/_form-today-attendance', [
'modelCustomers' => $modelCustomers,
'model' => $modelAttendance]);
}
There will be something in array, you can assign it to model instances.

Related

Yii 2 Call to a member function saveAs() on string

new to Yii and I am getting this error on a Send Email page. The string in question is the path to the attachment and the attachment name and i am presuming that the saveAs function would expect a string. Any ideas what i am missing?
The form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\emails */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="emails-form">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'reciever_name')->textInput(['maxlength' => 50]) ?>
<?= $form->field($model, 'receiver_email')->textInput(['maxlength' => 200]) ?>
<?= $form->field($model, 'subject')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'attachment')->fileInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and the controller:
public function actionCreate()
{
$model = new emails();
if ($model->load(Yii::$app->request->post())) {
// upload the attachment
$model->attachment = UploadedFile::getInstance($model, 'attachment');
if($model->attachment)
{
parent::init();
$time = time();
//$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
//$model->attachment = 'attachments/'.$time.'.'.$model->attachment->extension;
}
if($model->attachment)
{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo ($model->receiver_email)
->setSubject ($model->subject)
->setHtmlBody ($model->content);
foreach ($model->attachment as $file) {
//$filename = 'attachments/'.$time.'.'.$model->attachment->extension;
$filename = 'attachments/file.jpg';
//var_dump($filename);die();
$file->saveAs($filename);
$value->attach('attachments/file.jpg');
//$value->attach('attachments/'.$time.'.'.$model->attachment->extension);
}
$value->send();
}else{
$value = Yii::$app->mailer->compose()
->setFrom(['my_email#gmail.com' => 'Paul'])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->send();
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
I have tried absolute paths as well as dymanic paths, but all has the same output, i am stuck
Save as() function require the actual path. So that is issue. Please make sure your path should be correct and accessible.

Yii2 DatePicker within Modal

when I use the kartik\date\DatePicker within Modal,but it's report error that like https://******.com/assets/d9620747/css/bootstrap-datepicker3.css.map Failed to load resource: the server responded with a status of 404 (Not Found).plz help me;
My Controller's code:
public function actionBook($id = null)
{
$ticket = $this->findModel($id);
$model = new TicketOrder();
if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
// userCreate scenario
$model->scenario = 'create';
} else {
return $this->renderAjax('book', [
'ticket' => $ticket,
'model' => $model,
]);
}
}
My View's code:
<?php
Modal::begin([
'id' => 'create-modal',
'header' => '<h4 class="modal-title">订票</h4>',
'size' => 'modal-lg',
// 'footer' => 'Close',
]);
Modal::end();
?>
<?php
$js = <<<JS
$(function(){
$(".modal-wraper").click(function(){
var id = $(this).attr('data-id');
var url = "/sights/product-ticket/book?id=" + id;
$.get(url,{},function(data){
$(".modal-body").html(data);
});
$('#create-modal').on('shown.bs.modal', function(){
$('[data-toggle="popover"]').popover();
});
$("#create-modal").modal('show');
});
});
JS;
$this->registerJs($js);
My ajaxRender view's code:
<?php
use kartik\form\ActiveForm;
use kartik\date\DatePicker;
?>
<h3>由于资源方过多,建议一个手机号只购买一张票。</h3>
<?php
$form = ActiveForm::begin([
'type' => ActiveForm::TYPE_HORIZONTAL,
]);
?>
<?= $form->field($model, 'fullname')->textInput() ?>
<?= $form->field($model, 'mobile')->textInput() ?>
<?= $form->field($model, 'plantime')->widget(DatePicker::className(), [
'type' => DatePicker::TYPE_COMPONENT_APPEND,
]) ?>
<?= $form->field($model, 'comment')->textarea() ?>
<div class="button-group">
<?= \yii\helpers\Html::a('关闭', ['#'], ['class' => "btn btn-primary", 'data-dismiss' => "modal"]) ?>
<?= \yii\helpers\Html::button('购买', ['class' => 'btn btn-success pull-right', 'type' => 'submit']) ?>
</div>
<?php
$form->end();
?>
Like this:
image
I got error when I click the DatePicker Button.
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (bootstrap-datepicker3.css.map, line 0)
This issue has been already resolved. See it on GitHub.
Upgrade datepicker to version 1.4.2.

yii2 loading pjax form dynamically

Problem: I want to update GridView in pjax style but it redirect to the form creation page.
What the code below does:
Having an index page with GridView to display data list and open a form in a modal window to create new record. The form code is added into the modal dynamically.
When click on "Create Country" button on index page, it calls country/create to get the HTML code of the form and insert it into the modal, then it shows the modal window.
When click on the "Create" button on the form, it submit the form to country/create. This will return the HTML code of the index page, and I want it to update the GridView part, but it does not.
The code:
Controller CountryController.php
class CountryController extends Controller
{
public function actionIndex()
{
return $this->renderIndex();
}
public function actionCreate()
{
$model = new Country();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->renderIndex();
} else {
return $this->renderAjax('_form', [
'model' => $model,
]);
}
}
private function renderIndex()
{
$searchModel = new CountrySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
View index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\web\View;
$this->title = Yii::t('app', 'Countries');
$this->params['breadcrumbs'][] = $this->title;
yii\bootstrap\Modal::begin(['id' => 'modal']);
yii\bootstrap\Modal::end();
?>
<div class="country-index">
<h1><?= Html::encode($this->title) ?></h1>
<div>Current Time: <?= date('Y/m/d H:i:s') ?></div>
<p><?= Html::a(Yii::t('app', 'Create Country'),
['create'],
['class' => 'btn btn-success show-modal']) ?>
</p>
<?php Pjax::begin(['id' => 'pjax-grid']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
$this->registerJs("$(function() {
$('.show-modal').click(function(e) {
e.preventDefault();
$('#modal').modal('show').find('.modal-body')
.load($(this).attr('href'));
});
});", View::POS_READY, '.show-modal');
?>
View _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\View;
?>
<?php
$this->registerJs(
'$("document").ready(function(){
$("#pjax-create").on("pjax:end", function() {
$.pjax.reload({container:"#pjax-grid"}); //Reload GridView
});
});'
, View::POS_READY, 'pjax-create-end');
?>
<div class="country-form">
<?php yii\widgets\Pjax::begin(['id' => 'pjax-create']) ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => TRUE]]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<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(); ?>
<?php yii\widgets\Pjax::end() ?>
</div>
Use Html::button instead Html::a and simple overwrite the content of the modal:
yii\bootstrap\Modal::begin(['id' => 'modal']);
echo '<div id="modal-content"></div>';
yii\bootstrap\Modal::end();
echo Html::button('Create Country', [
'onClick' => 'createCountry("' . Url::to([create]) . '")',
'class' => 'btn btn-primary'
]);
$script = <<< JS
function createCountry(url) {
$('#modal').modal('show').find('#modal-content').load(url);
}
JS
$this->registerJs($script, View::POS_END);

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

Yii2 Color Picker in Form

Is there any built in class or an extinction that makes the user pick color from something like this?
You can simply render a color input like this with out using any plugins.
<?= $form->field($model, 'color', [
'template' => "{input}"
])->input('color',['class'=>"input_class"]) ?>
You can use kartik\widgets\ColorInput widget. first install kartik\widgets\ColorInput from this link
e.g. (Updated)
use kartik\widgets\ColorInput; or kartik\color\ColorInput;(for previous ver.)
<?php $form = ActiveForm::begin([
'id' => 'form',
]); ?>
<?= $form->field($model, 'color_code')->widget(ColorInput::classname(), ['options' => ['placeholder' => 'Select Color...'],]); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-primary btn-create' : 'btn btn-info btn-create']) ?>
</div>
<?php ActiveForm::end(); ?>