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

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.

Related

Is there a way to call modeless form in pages using cakephp3

as what I read online it will only be available for like this
http://localhost/xxxxx/contact then the form will display
but I want it to display in many pages like contact us, or about us page
when i call this pages I want the form appear in the content?
Template
index.ctp
<?= $this->Form->create($contact); ?>
<?= $this->Form->input('name'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('body'); ?>
<?= $this->Form->button('Submit'); ?>
<?= $this->Form->end(); ?>
ContactController.php
<?php
// In a controller
namespace App\Controller;
use App\Controller\AppController;
use App\Form\ContactForm;
class ContactController extends AppController
{
public function index()
{
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$this->Flash->success('Your message has been sent; we\'ll get back to you soon!');
$this->request->data['name'] = null;
$this->request->data['email'] = null;
$this->request->data['body'] = null;
} else {
$this->Flash->error('There was a problem submitting your form.');
}
}
$this->set('contact', $contact);
}
}
?>
ContactForm.php
<?php
namespace App\Form;
use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;
use Cake\Mailer\Email;
class ContactForm extends Form
{
protected function _buildSchema(Schema $schema)
{
return $schema->addField('name', 'string')
->addField('email', ['type' => 'string'])
->addField('body', ['type' => 'text']);
}
protected function _buildValidator(Validator $validator)
{
return $validator->add('name', 'length', [
'rule' => ['minLength', 10],
'message' => 'Please enter your name'
])->add('email', 'format', [
'rule' => 'email',
'message' => 'Please enter a valid email address',
])->add('body', 'length', [
'rule' => ['minLength', 25],
'message' => 'Please enter your message text',
]);
}
protected function _execute(array $data)
{
// Send an email.
return true;
}
}
You can fixed it by moving the contact template form into the element so that it will be available in any pages.
inside element in the contact folder, form below must be present
<legend><?= __('Our Form') ?></legend>
<fieldset>
<?php
echo $this->Form->input('name');
echo $this->Form->input('email');
echo $this->Form->input('body');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end(); ?>
then in your pages
you can just call
<?php
echo $this->element('contact/index');
?>
assuming you created index.ctp inside contact folder in element
Hope it solved your problem.

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.

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

Yii2 saving form with multiple models

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.