The upload variable is empty in yii2 - yii2

i want add uploadFile to: https://github.com/thyseus/yii2-message
i added public $file2 in Message.php in model
and this is my rules in model:
public function rules()
{
return [
[['title'], 'required'],
[['file2'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
[['title', 'message', 'context'], 'string'],
[['title'], 'string', 'max' => 255],
[['to'], IgnoreListValidator::class],
[['to'], 'exist',
'targetClass' => Yii::$app->getModule('message')->userModelClass,
'targetAttribute' => 'id',
'message' => Yii::t('app', 'Recipient has not been found'),
],
[['to'], 'required', 'when' => function ($model)
{
return $model->status != Message::STATUS_SIGNATURE && $model->status != Message::STATUS_DRAFT;
}],
];
}
and this is my view:
<?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
<?php
echo $form->field($model, 'file2')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]);
// With model & without ActiveForm
echo '<label class="control-label">Add Attachments</label>';
echo FileInput::widget([
'model' => $model,
'attribute' => 'file2',
'options' => ['multiple' => true]
]);
?>
and this is my sendMessage Function
$model = new Message();
$model->attributes = $attributes;
var_dump($attributes);
die;
why after upload file my result is this?
array(4) { ["to"]=> array(1) { [0]=> string(2) "65" } ["title"]=> string(3) "asd" ["message"]=> string(30) "asd . " ["file2"]=> string(0) "" }
file2 is empty !

When setting up the form, you need to mention as multipart/form-data. check below example.
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'file2')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>

Related

Hide row in yii2 gridview depending on actioncolumn

I have a gridview in which I have custom actioncolumn according to user authorization and other conditions. Due to this conditions, in few rows, there are no action item button for few rows. I want to hide these rows.
I can hide the row on condition by rowoption. But I want to know how can I hide it according to the action item button.
Following is the index view page -
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use frontend\modules\workpermit\models\Workpermit;
use frontend\modules\workpermit\models\Extension;
use frontend\modules\workpermit\models\WpindexSearch;
use frontend\modules\workpermit\models\Aclpath;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\workpermit\models\WorkpermitSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'All Permits';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="workpermit-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Home', ['/site/index'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Refresh', ['/workpermit/workpermit/awsup'], ['class' => 'btn btn-primary']) ?>
</p>
<?php Pjax::begin(['id' => 'allpermitview']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'rowOptions' => function($model){
if($model->wp_type == 'Excavation Permit'){
return ['class' => 'hide'];
}
},
'options' => [
'style'=>'overflow: auto; word-wrap: break-word;'
],
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function($model, $key, $index, $column){
return GridView::ROW_COLLAPSED;
},
'detail' => function($model, $key, $index, $column){
$model = Workpermit::find()->where(['wp_no' => $model->wp_no])->one();
$searchModel = new WpindexSearch();
$aclfileuploadpaths = Aclpath::find()->select('aclp_path')->where(['aclp_wpno'=>$model->wp_no])->column();
// $searchModel->wp_no = $model->wp_no;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$id = $model->wp_no;
if($model->wp_type == 'Safe Work Permit'){
return Yii::$app->controller->renderPartial('_approvalstatussafe', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Hot Work Permit'){
return Yii::$app->controller->renderPartial('_approvalstatushot', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Excavation Permit'){
return Yii::$app->controller->renderPartial('_approvalstatusexcav', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
elseif($model->wp_type == 'Confined Space Permit'){
return Yii::$app->controller->renderPartial('_approvalstatusconfined', [
'id' => $id,
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'from_date' => $from_date, 'to_date'=>$to_date
]);
}
},
],
'wp_no',
[
'label' => 'WP Type',
'attribute' => 'permittyp',
'value' => 'permittype.wpt_short',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_type', 'wp_type'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Type'],
],
[
'label' => 'Status',
//'attribute'=>'status',
'attribute'=>'wp_status',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::Find()->asArray()->all(), 'wp_status', 'wp_status'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Permit Status'],
'contentOptions' => function($model, $key, $index, $column){
if($model->wp_status == 'Available'){
return['style' => 'background-color:red'];
}elseif($model->wp_status == 'Approved'){
return['style' => 'background-color:green'];
}elseif($model->wp_status == 'Work in Progress'){
return['style' => 'background-color:yellow'];
}elseif($model->wp_status == 'Completed'){
return['style' => 'background-color:blue'];
}
}
],
'wp_date',
//'wp_time',
'wp_validto',
[
'attribute'=>'wp_plant',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_plant', 'wp_plant'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Plant'],
],
[
'attribute'=>'wp_area',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Workpermit::find()->asArray()->all(), 'wp_area', 'wp_area'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Area'],
],
//'wp_area',
'wp_jobdesc',
[
'label' => 'View',
'content' => function ($model, $key, $index, $column) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['viewall', 'id' => $model->wp_no])
. ' ' .Html::a('<span class="glyphicon glyphicon-print"></span>', ['/workpermit/workpermit/printpermit', 'id' => $model->wp_no]);
}
],
[ 'label' => 'Action',
'content' => function ($model, $key, $index, $column) {
//The Supervisor Conditions//
if ($model->wp_status == 'Assigned' && Yii::$app->user->can('s_jsapproval')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateapproval', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Safe Work Permit' && $model->wp_apoapproval == 'Approved' && $model->wp_spsapproval == 'Approved' && $model->wp_officerapproval == 'Approved' && Yii::$app->user->can('s_jsapproval') && $model->wp_jc != 'Completed' && ($model->wp_status == 'Approved' || $model->wp_status == 'Work in Progress' || $model->wp_status == 'Assigned')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Hot Work Permit' && $model->wp_apoapproval == 'Approved' && $model->wp_spsapproval == 'Approved' && $model->wp_officerapproval == 'Approved' && $model->wp_emsuper == 'Approved' && $model->wp_plsuper == 'Approved' && Yii::$app->user->can('s_assignwp') && ($model->wp_status == 'Approved' || $model->wp_status == 'Work in Progress')) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
elseif ($model->wp_type == 'Confined Space Permit' && ($model->wp_status == 'Assigned' || $model->wp_status == 'Work in Progress' || $model->wp_status == 'Approved') && Yii::$app->user->can('s_assignwp')){
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['updateassignwp', 'id' => $model->wp_no]);
}
}
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
/* start getting the another permit Type */
$script = <<< JS
$('#workpermit-wp_spost13').on('click',function(e){
$.pjax.reload({container: "#allpermitview"});
});
JS;
$this->registerJs($script);
/* end getting the another permit Type */
?>
A couple of options for you:
Add a Where Condition to you Search Query
Note: You could also apply optional filters in your search model.
class SomeController extends Controller
{
public function actionIndex()
{
$this->layout = "#app/views/layouts/main-app";
$searchModel = new WorkpermitSearch ();
$queryParams = Yii::$app->request->queryParams;
$dataProvider = $searchModel->search($queryParams);
$dataProvider->query->andWhere(['or',
['wp_type' => 'Safe Work Permit')],
['wp_type'=> 'Hot Work Permit'],
])
->orderBy(['wp_type' => SORT_DESC ]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Apply a Hide Class in Gridview at rowOptions
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'emptyCell'=>'-',
//'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => ''], //Hide "not set" fields.
//'tableOptions' => ['class' => 'table'],
//'options' => ['style' => 'font-size: 1.2em;'],
'rowOptions' => function($model, $key, $index, $grid){
if ($model->wp_type == 'Safe Work Permit'){
return ['style' => 'visibility:collapse;'];
} else {
return ['style' => 'visibility:visible;'];
}
},
...

Yii2 How to save same file name but different file or content?

How to save same name but different content for example, samplename.docx. Now i want to save it again but the result the same. When i create a new report and use the name samplename it will overwrite the other same name. So in the uploads folder the samplename.docx is only one. But in the dgView is more than one.
This is my controller:
public function actionCreate()
{
$model = new reportDetails();
if ($model->load(Yii::$app->request->post()))
{
$project =$model->doc_name;
$model->upload_file= UploadedFile::getInstance($model,'doc_file');
$model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
$model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
$model->doc_name=$project.'.'.$model->upload_file->extension;
$model->save();
Yii::$app->getSession()->setFlash('success','Data saved!');
return $this->redirect(['view','id'=> $model->report_id]);
}
else {
return $this ->render('create', [
'model'=>$model,
]);
}
}
This is my model:
public $upload_file;
public function rules()
{
return [
[['reference_no', 'subject', 'doc_for', 'doc_from', 'doc_date', 'doc_file', 'doc_name', 'drawer_id'], 'required'],
[['doc_date'], 'safe'],
[['drawer_id'], 'integer'],
[['reference_no', 'doc_for', 'doc_from'], 'string', 'max' => 200],
[['subject'], 'string', 'max' => 255],
[['doc_file', 'doc_name'], 'string', 'max' => 50],
[['user_id'],'string'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'report_id' => 'Report ID',
'reference_no' => 'Reference No:',
'subject' => 'Subject:',
'doc_for' => 'For:',
'doc_from' => 'From:',
'doc_date' => 'Document Entry Date:',
'doc_file' => 'Document File:',
'doc_name' => 'Document Name:',
'drawer_id' => 'Drawer ID:',
'user_id' => 'Encoder Name:',
];
}
And this is my form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= Html::button('<i class="fa fa-plus"></i> Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
</br>
</br>
<?php Pjax::begin(['id' => 'for_from']) ?>
<div class="col-sm-6">
<?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Name::find()->asArray()->all(),
'name_id',
function($model, $defaultValue){
return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
}),
'language' => 'en',
'options' => ['placeholder' => 'Choose a person ...'],
'pluginOptions' => [
'allowClear' => true,
'width' => 500,
],
]); ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Name::find()->asArray()->all(),
'name_id',
function($model, $defaultValue){
return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
}),
'language' => 'en',
'options' => ['placeholder' => 'Choose a person ...'],
'pluginOptions' => [
'allowClear' => true,
'width' => 500,
],
]); ?>
<?php Pjax::end(); ?>
</div>
</br>
</br></br></br>
<div class="broder" style=" border-radius: 5px; padding: 12px; ">
</div>
<div class="col-sm-6">
<?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
<?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
<br>
<br>
<?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
<?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
<?= $form->field($model, 'doc_date')->widget(
DatePicker::className(), [
'inline' => false,
'options' => ['placeholder' => 'Choose a Entry Date ...'],
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-sm-6" style="padding-top: 14px; ">
</br>
</br>
</br></br>
<?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
<?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
<?= $form->field($model, 'doc_file')-> widget(
FileInput::classname(),[
'name' => 'doc_file',
'options' => ['accept' => '.docx','.doc','.docs'],
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false
]
]);
?>
use
if(file_exists('...')){
// upload file with , new file name
}
else{
// upload file
}
Try this one
if (file_exists($fileFullPath)) {
unlink ($fileFullPath);
echo "delete existing file creating new <br />";
}else{
echo "file not exists creating new <br />";
}

How display kartik\Select2 in modal window use renderAjax

I use http://demos.krajee.com/widget-details/select2#usage-tags
controller
public function actionTagsForm()
{
$method = Yii::$app->request->isAjax ? 'renderAjax' : 'render';
$model = new UserTagsForm();
return $this->$method('tagsForm', ['model' => $model]);
}
views/layouts/main.php has code modal window
<?php
yii\bootstrap\Modal::begin([
'header' => '<div id="modalHeader"></div>',
'id' => 'modal',
'size' => 'modal-lg',
'options' => [
'tabindex' => false
],
]);
echo "<div id='modalContent'></div>";
yii\bootstrap\Modal::end();
?>
view
$data = [
"red" => "red",
"green" => "green",
"blue" => "blue",
"orange" => "orange",
"white" => "white",
"black" => "black",
"purple" => "purple",
"cyan" => "cyan",
"teal" => "teal"
]; ?>
<div class="image-tags-index">
<?php $form = ActiveForm::begin();?>
<?php echo $form->field($model, 'image_tags')->widget( Select2::classname(),[
'data' => $data,
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
])->label('Tag Multiple');
?>
</div>
error
VM314:2 Uncaught ReferenceError: select2_3f25e3ac is not defined
at eval (eval at globalEval (jquery.js:343), :2:56)
at eval ()
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at jQuery.fn.init. (jquery.js:5525)
at access (jquery.js:3614)
at jQuery.fn.init.html (jquery.js:5492)
at Object. (jquery.js:9436)
at fire (jquery.js:3187)
This problem has been solved in the https://github.com/kartik-v/yii2-widget-select2/issues/211

Yii2 captcha image is not displaying

I want to add Captcha verification on login page. But there is an error, captcha image is not showing and when I try to view the captcha image http://xxx.yii2/site/captcha?v=5806eb0c3aa05 , below error display
The image “http://xxx.yii2/site/captcha?v=5806ce094fa84” cannot be displayed because it contains errors.
Below is my SiteController
class SiteController extends Controller {
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout','resetPassword'],
'rules' => [
[
'actions' => ['logout','resetpassword'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
LoginForm controller
class LoginForm extends Model {
public $username;
public $password;
public $rememberMe = true;
public $verifyCode;
private $_user = false;
const ERROR_NONE=0;
const ERROR_USERNAME_INVALID=1;
const ERROR_USERNAME_LOCKED = 3;
const ERROR_USERNAME_INACTIVE = 4;
const ERROR_PASSWORD_INVALID=2;
public $role_id;
public $salt;
public $_id;
private $_identity;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['username', 'password'], 'required'],
['rememberMe', 'boolean'],
['username','validateMember'],
['password', 'validatePassword'],
['verifyCode', 'captcha'],
];
}
Login form view
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className()) ?>
<?= $form->field($model, 'rememberMe')->checkbox([
'template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>",
]) ?>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('<i class="fa fa-sign-in fa-fw"></i> Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
Check this.
Note that CaptchaAction requires either GD2 extension or ImageMagick PHP extension.
See: Class yii\captcha\CaptchaAction
Another possible reason of the problem is wrong action specified. To resolve it you need to specify if manually both in model and widget.
Model:
['verifyCode', 'captcha', 'captchaAction' => 'site/captcha']
Widget:
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'captchaAction' => 'site/captcha'
]) ?>

Filter gridview in form in Yii2

I want to use a gridview in a form. The idea is to insert multiple selected rows from the gridview into the table. I've managed to get the gridview in the form. But when I'm filtering it it is running the insert command in stead of filtering.
Also, please let me know if there is any better way to do this.
Code of my _form
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\grid\GridView;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
/* #var $this yii\web\View */
/* #var $model frontend\models\Rawmaterial */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="rawmaterial-form">
<?php $form = ActiveForm::begin(); ?>
<div class="form-group">
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'usedate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-9 col-sm-9 col-lg-9">
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Rmtemplate::find()->select('productname')->distinct()->orderBy(['productname' => SORT_ASC,])->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Charge...', 'id' => 'productid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<?= GridView::widget([
'dataProvider' => $dataProvider2,
'filterModel' => $searchModel2,
'columns' => [
['class' => 'kartik\grid\CheckboxColumn'],
//'id',
//'productname',
[
'attribute'=>'productname',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Charge Name'],
],
'rmname',
'qty',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<?= $form->field($model, 'rmname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'useqty')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'unitcost')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'chargenumber')->textInput()->hiddenInput()->label(false) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the chargeno */
$script = <<<EOD
$(window).load(function(){
$.get('index.php?r=rmprod/rawmaterial/get-for-chargeno',{ orderid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#rawmaterial-chargenumber').attr('value',data.chargeno);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the chargeno */
?>
Code of Controller Action
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
Code of create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model frontend\models\Rawmaterial */
$this->title = 'New Charge';
$this->params['breadcrumbs'][] = ['label' => 'Rawmaterials', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="rawmaterial-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]) ?>
</div>
The error -
Update:
On ScaiseEdge's answer I've updated the _form and the Controller action looks like below.
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if ($_POST('submit') == 'create_update' ) {
// then perform the insert
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
} else {
// no insert but render for filter ..
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
Error:
Update 2
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if (!$request->isAjax) {
if ($_POST('submit') == 'create_update' ) {
// then perform the insert
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
} else {
// no insert but render for filter ..
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
Error
Update 3
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if (isset($_POST('submit'))) {
if ($_POST('submit') == 'create_update' ) {
// then perform the insert
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
} else {
// no insert but render for filter ..
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
Error
Update 4
public function actionCreate()
{
$model = new Rawmaterial();
$searchModel2 = new RmtemplateSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
if (isset($_POST['submit'])) {
if ($_POST('submit') == 'create_update' ) {
// then perform the insert
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
} else {
// no insert but render for filter ..
return $this->render('create', [
'model' => $model,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
}
This could be related to the fact the filter value is submitted for perform the search.
You could override this behavior adding a value to the submit button
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update',
['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary',
'name' => 'submit', 'value' => 'create_update']) ?>
and in the controller/action (insert and update) check the content of the submit button
if (isset($_POST['submit'])) {
if ($_POST['submit'] == 'create_update' ) {
// then perform the insert
} else {
// no insert but render for filter ..
}