I'm using wbraganca yii2-dynamicform and kartik yii2-widget-fileinput. The form works fine but when I'm trying the getinstance for upload the images always is null.
This is my controller.
public function addMultipleImage($model){
$modelsOptionValue = Model::createMultiple(OptionValue::classname());
Model::loadMultiple($modelsOptionValue, Yii::$app->request->post());
foreach ($modelsOptionValue as $index => $modelOptionValue) {
$modelOptionValue->sort_order = $index;
$file[$index]= UploadedFile::getInstanceByName("OptionValue[".$index."][upload_image]");
var_dump($file[$index]);
if($file[$index]){
$ext = end((explode(".", $file[$index]->name)));
// generate a unique file name
$modelOptionValue->img= Yii::$app->security->generateRandomString().".{$ext}";
$path[$index]= Yii::getAlias ('#web') ."/img/". $modelOptionValue->img;
}else{
return false;
}
}
View form
//_form.php
<?php $form = ActiveForm::begin( [
'enableClientValidation' => false,
'enableAjaxValidation' => true,
'validateOnChange' => true,
'validateOnBlur' => false,
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]);
?>
//_form_add_image.php
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.form-options-body',
'widgetItem' => '.form-options-item',
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.delete-item',
'model' => $modelsOptionValue[0],
'formId' => 'dynamic-form',
'formFields' => [
'upload_image'
],
]); ?>
<?= $form->field($modelOptionValue, "[{$index}]upload_image")->label(false)->widget(FileInput::classname(), [
'options' => [
'multiple' => false,
'accept' => 'image/*',
'class' => 'optionvalue-img'
],
'pluginOptions' => [
'previewFileType' => 'image',
'showCaption' => false,
'showUpload' => false,
'browseClass' => 'btn btn-default btn-sm',
'browseLabel' => ' Seleccionar Imagen',
'browseIcon' => '<i class="glyphicon glyphicon-picture"></i>',
'removeClass' => 'btn btn-danger btn-sm',
'removeLabel' => ' Borrar',
'removeIcon' => '<i class="fa fa-trash"></i>',
'previewSettings' => [
'image' => ['width' => '138px', 'height' => 'auto']
],
'initialPreview' => $initialPreview,
'layoutTemplates' => ['footer' => '']
]
]) ?>
and my model
public $upload_image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'option_value';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['upload_image'], 'file', 'extensions' => 'png, jpg', 'skipOnEmpty' => true],
[['id_montacarga', 'sort_order'], 'integer']
];
}
screenshot of yii2 log. updated
inspect element screenshot
Thanks!!!
Add 'enctype' => 'multipart/form-data' in ActiveForm.
<?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]); ?>
Set Ajax Validation to false if you don't want ajax validation.
Reference
Related
I'm trying to render a Nav bar (from _tabs.php) onto index.php (view) the controller that is being used is ImportController.php. the _tabs.php file uses the client_id which is basically the function to get the client ID so it can appropriately create the URL with an ID in it. The issue that I'm getting is Trying to get property 'id' of non-object
index.php (view)
<?php
use yii\bootstrap\Html;
use common\components\ActiveForm;
use common\models\User;
use common\models\Client;
$Client= null;
$this->title = 'Import Offline Data Capture data';
?>
<!-- capture partial Nav -->
<br>
<?php if(in_array(Yii::$app->user->identity->role, User::MHM_ROLES)): ?>
<?= $this->render('/client/_tabs', ['Client' => $Client]); ?>
<?php endif; ?>
<?php if(in_array(Yii::$app->user->identity->role, User::CLIENT_ROLES)): ?>
<?= $this->render('//client/partialNavs/appendNav', ['Client' => $Client]); ?>
<?php endif; ?>
<div class="page-header">
<h2>Import data</h2>
</div>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-body" id="survey-import-container">
<h4 class="text-info">Please select a file to import</h4>
<?php if(count($ImportForm->getErrors('dataErrors'))): ?>
<div class="alert alert-warning">
<p><strong>Sorry, we were unable to process your import. Please revise the following errors and try again:</strong><p><br />
<ul>
<?php foreach($ImportForm->getErrors('dataErrors') as $e): ?>
<li><?= $e; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<p>The file must follow the exported template, and must be a XLSX document with a maximum of 10,000 rows.</p>
<?php $form = ActiveForm::begin([
'id' => 'import-form',
'options' => [
'enctype' => 'multipart/form-data',
'class' => 'clearfix',
]
]) ?>
<?= $form->field($ImportForm, 'importFile')->fileInput() ?><hr />
<?= Html::submitButton('<span class="glyphicon glyphicon-import"></span> Import & Process Data', ['class' => 'btn btn-primary col-md-6', 'id' => 'import-data-btn']); ?>
<?= Html::a('<span class="glyphicon glyphicon-repeat"></span> Reset', ['import/index'], ['class' => 'btn btn-link col-md-6']); ?>
<?php ActiveForm::end() ?>
<div class="alert alert-danger" style="margin-top: 20px;">Please note: This application does not store any of your imported data. Keep your original spreadsheet to avoid losing data.</div>
</div>
</div>
</div>
</div>
ImportController.PHP
<?php
namespace admin\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use admin\components\Controller;
use admin\models\ImportForm;
use common\models\User;
use common\models\Client;
class ImportController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index'],
// All actions are access controlled.
'roles' => [
User::ROLE_MHM_ADMIN,
User::ROLE_MHM_USER,
User::ROLE_CLIENT_ADMIN,
User::ROLE_CLIENT_USER,
]
],
],
],
];
}
public function actionIndex($client_id = null)
{
// Get client
$Client = $this->getClient($client_id);
// Ensure client exists for logged in user
if(is_null($Client)) {
throw new BadRequestHttpException('This page does not exist.');
}
$ImportForm = new ImportForm;
// Form posted, validate
if(Yii::$app->request->isPost) {
$ImportForm->importFile = UploadedFile::getInstance($ImportForm, 'importFile');
// Process upload
$ImportForm->upload();
}
return $this->render('index', array(
'ImportForm' => $ImportForm,
));
}
public function actionRenderSuccess()
{
return $this->renderPartial('_success');
}
private function getClient($id, $restriction = null)
{
if(Yii::$app->user->identity->client_id)
{
$id = Yii::$app->user->identity->client_id;
}
$ClientQuery = Client::find()
->andWhere(['id' => $id]);
if ($restriction == 'patronbase') {
$ClientQuery->andWhere(['license_type' => Client::LICENSE_PATRONBASE]);
} else if ($restriction == 'live') {
$ClientQuery->andWhere(Client::LIVE_OR_UPGRADING_CONDITION);
}
$Client = $ClientQuery->one();
if(is_null($Client))
{
throw new NotFoundHttpException('');
}
return $Client;
}
}
_tabs.php
<?php
use yii\bootstrap\Html;
use common\models\Client;
use common\models\User;
use common\models\SurveyInstance;
use common\models\Consent;
use yii\bootstrap\Tabs;
use yii\bootstrap\Nav;
if (Yii::$app->user->isGuest) return;
$getRoute = function($route, $clientParamName, $otherParams = []) use ($Client)
{
$routeParams = [$route];
if (!isset(Yii::$app->user->identity->client_id)) {
$routeParams[$clientParamName] = $Client->id;
}
return array_merge($routeParams, $otherParams);
};
$route = Yii::$app->controller->module->requestedRoute;
$mhmOrClientAdmin = in_array(Yii::$app->user->identity->role, [User::ROLE_MHM_ADMIN, User::ROLE_MHM_USER, User::ROLE_CLIENT_ADMIN]);
$mhmUser = in_array(Yii::$app->user->identity->role, User::MHM_ROLES);
$urlsForConsentSurveyTypes = Consent::getUrlForSurveyTypes();
$items = [
[
'label' => 'Checkout / Enrich',
'url' => $getRoute('dashboard/mhm-rels-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/mhm-rels-dashboard',
'survey-instance/api-logs',
'client/activity',
'client/update',
'client/api-settings'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
'encode' => false,
'visible' => $Client->isFullOrUpgrading,
],
[
'label' => 'Checkout / Enrich',
'url' => $getRoute('dashboard/patronbase-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/mhm-rels-dashboard',
'dashboard/patronbase-dashboard',
'survey-instance/api-logs',
'client/activity',
'client/update',
'client/api-settings',
'client/patronbase-settings'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='cs-tag-tool-consent'),
'encode' => false,
'visible' => $Client->license_type === Client::LICENSE_PATRONBASE,
],
[
'label' => 'Capture',
'url' => $getRoute('dashboard/capture-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/capture-dashboard',
'client/survey-settings',
'consent/create',
'consent/update',
'question/index',
'client/legal',
'question/create',
'question/update'
]) || ($route =='consent/index' && Yii::$app->request->get('type')=='capture-consent'),
'encode' => false,
],
[
'label' => 'Append',
'url' => $getRoute('dashboard/append-dashboard', 'client_id'),
'active' => in_array($route, [
'dashboard/append-dashboard',
'client/append-settings',
'import/index'
]),
'encode' => false,
],
//Info
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Info',
'options' => ['class' => 'pull-right'],
'active' => in_array($route, [
'client/stats',
'client/survey-urls',
]),
'encode' => false,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-stats"></span> Stats',
'url' => $getRoute('client/stats', 'client_id'),
'active' => in_array($route, ['client/stats',]),
'encode' => false,
'visible' => $mhmOrClientAdmin,
],
[
'label' => '<span class="glyphicon glyphicon-file"></span> Guides',
'url' => '/guides/' . $Client->hash,
'encode' => false,
'linkOptions' => [ 'target' => '_blank'],
'visible' => $Client->isFullOrUpgrading,
],
[
'label' => '<span class="glyphicon glyphicon-link"></span> Survey URLs',
'url' => $mhmUser ? ['client/survey-urls', 'client_id' => $Client->id] : ['client/survey-urls'],
'encode' => false,
],
],
],
//Settings
[
'label' => '<span class="glyphicon glyphicon-cog"></span> Account settings',
'options' => ['class' => 'pull-right'],
'active' => in_array($route, [
'client/anonymisation',
'contact/index',
'contact/update',
'contact/create',
'contact/delete',
'user/index',
'user/create-update',
]),
'encode' => false,
'items' => [
[
'label' => '<span class="glyphicon glyphicon-erase"></span> Anonymisation',
'url' => $getRoute('client/anonymisation', 'id'),
'active' => in_array($route, ['client/anonymisation']),
'encode' => false,
],
[
'label' => '<span class="glyphicon glyphicon-envelope"></span> Email List',
'url' => $getRoute('contact/index', 'client_id'),
'active' => in_array($route, [
'contact/index',
'contact/update',
'contact/create',
'contact/delete',
]),
'encode' => false,
],
[
'label' => '<span class="glyphicon glyphicon-user"></span> Users <span class="badge">'.count($Client->clientUsers).'</span>',
'url' => $getRoute('user/index', 'client_id'),
'active' => in_array($route, [
'user/index',
'user/create-update',
]),
'encode' => false,
'visible' => $mhmOrClientAdmin,
],
],
],
];
echo Nav::widget([
'options' => [
'class' => 'nav nav-pills',
'id'=>'nav-bar',
],
'items' => $items,
]);
?>
<style>
#nav-bar {
background-color: aliceblue
}
</style>
Hope this answer will help:
return $this->render('index', array(
'ImportForm' => $ImportForm,
'Client' => $Client
));
Focus on your Index action on ImportController. I think you forgot to pass that $Client to index.php.
Also, remove $Client= null; in your view file (index.php) above $this->title;
<?php use kartik\file\FileInput;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'import-pdf',
'options' => ['enctype' => 'multipart/form-data'],
]); ?>
<?=
$form->field($model, 'file_name')->widget(FileInput::classname(), [
'options' => ['multiple' => false],
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
],
]);
?>
//file_name is the attribute I'm using it
public function rules()
{
return [
[['file_name'], 'required'],
[['status', 'total_pages', 'processed_pages', 'file_type'], 'safe'],
[['total_pages', 'processed_pages', 'file_type'], 'integer'],
[['file_name'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
[['status'], 'string', 'max' => 255],
];
}
File name cannot be blank message is coming while clicking browse button only, It should show the validation message after selecting the file only
https://i.stack.imgur.com/GuENh.png
Have you tried to assign to $file_name the uploadedFile instance before the validation?
$model->file_name = UploadedFile::getInstance($model, 'file_name');
or
$model->file_name = UploadedFile::getInstanceByName('nameOfTheField');
hi all i'm a noob of yii and i'm trying to get the kartiks to work, but I can't get them to load the dependency.I'm trying to make the kartik work but I can't get it to load the dependency, if I see the calls that are made through yii's built-in debugging the scream that is present in the 'URL' parameter is not really computed, I've also tried to write it fixed but it's not really thought.
If I do a simple echo, however, it comes back correct.
<?=$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...', 'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => new JsExpression("function (e) {
var id=e.params.data.id;
$.get('index.php?r=invoice/get-location-address', {id: id}, function(data) {
if (data !== null) {
document.getElementById('piva').value=data.PIVA;
document.getElementById('indi').value=data.Indirizzo;
} else {
//if data wasn't found the alert.
alert('We\'re sorry but we couldn\'t load the the location data!');
}
});
}")]
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'options' => ['placeholder' => 'Select ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => [Html::getInputId($model, 'name')], //['lvl-0'],
'url' => Url::to(['/contact/list']),
'loadingText' => 'caricamento dati ...',
]
]);
?>
in the controller
public function actionList() {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = [];
if (isset($_POST['depdrop_parents'])) {
$id = end($_POST['depdrop_parents']);
$list = Contact::find()->andWhere(['id_ana_ref' => $id])->asArray()->all();
var_dump($list);
$selected = null;
if ($id != null && count($list) > 0) {
$selected = '';
foreach ($list as $i => $account) {
$out[] = ['id' => $account['id_contact'], 'name' => $account['Name']];
if ($i == 0) {
$selected = $account['id_contact'];
}
}
// Shows how you can preselect a value
return ['output' => $out, 'selected' => $selected];
}
}
solved if you put any java on kartick they avoid standard code
solution
<?=
$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...' ,'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN','onclick'=>'magsearch()', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
// $url = \yii\helpers\Url::to(['index.php?r=contact/list']);
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'data' => $datac,
'options' => ['placeholder' => 'carico ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['lvl-0'],
'url' => Url::to(['/contact/list']),
// 'params' => ['lvl-0'],
'loadingText' => 'caricamento dati ...',
]
]);
?>
i have gridview table like this :
i want to merge store 1(example) with 4 row detail information. is it possible to do it with?
i have a code in gridview :
<?php Pjax::begin(['id' => 'pjax_filesetting','timeout'=>false]) ?>
<?php
$this->registerJs(
"
$('.btneditfile').click(function(){
var hqid = $(this).attr('data-hqid');
var storeid = $(this).attr('data-storeid');
var filename = $(this).attr('data-filename');
location.href = '/pos/editfilesetting?hqid='+hqid+'&storeid='+storeid+'&filename='+filename;
return false;
});
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'options' => ['class' => 'grid-view active-table'],
'columns' =>
[
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Store Name',
'attribute' => 'store_name',
'encodeLabel' => false,
],
[
'label' => 'Filename',
'attribute' => 'filename',
'encodeLabel' => false,
],
[
'label' => 'Datecheck',
'attribute' => 'datecheck',
'encodeLabel' => false,
'value' => function($model){
$datecheck = $model["datecheck"];
if($datecheck)
{
return $model["datecheck"] = "Check";
}
else
{
return $model["datecheck"] = "Not Check";
}
}
],
[
'label' => 'Timecheck',
'attribute' => 'timecheck',
'encodeLabel' => false,
'value' => function($model){
$timecheck = $model["timecheck"];
if($timecheck)
{
return $model["timecheck"] = "Check";
}
else
{
return $model["timecheck"] = "Not Check";
}
}
],
[
'label' => 'Maintenance code',
'attribute' => 'maincode',
'encodeLabel' => false,
],
[
'label' => 'Final Filename',
'attribute' => 'usedfilename',
'encodeLabel' => false,
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '<div align="center">{update} {delete}</div>',
'buttons' => [
'update' => function ($url, $model) use ($controller) {
return Html::button(
'<span class="glyphicon glyphicon-pencil"></span>',
[
'class' => 'btn btn-primary btn-xs btneditfile',
'title' => Yii::t( $controller->transmodule, 'Edit' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'id' => 'editfile',
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
'delete' => function ($url, $model)use ($controller){
return Html::button(
'<span class="glyphicon glyphicon-trash"></span>',
[
'class' => 'btn btn-danger btn-xs btndeletefile',
'title' => Yii::t( $controller->transmodule, 'Delete' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
],
]
],
]) ?>
<?php Pjax::end() ?>
what must i do to merge it?
what i need is if the store name is same, merge it column .
Is the store and other details in one table or separate table? If it is in separate tables, the $dataProvider should query from the store table. In the store model create a hasMany relation to the other table which contain the details. So in the view, in the gridview column function you can loop through those values and display it in the same row.
I am new in yii2, Right now i am creating sample crud appliacation. I used pjax for gridview, It is working fine for me, My problem is when i update my row at that time pjax also calling now i want to disable this pjax for update button. How can i resolve this issue ? Here is my code
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PostSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Posts';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Post', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php \yii\widgets\Pjax::begin(
['id' => 'StickerList', 'timeout' => false, 'enablePushState' => false, 'clientOptions' => ['method' => 'GET']]
); ?>
<?= GridView::widget([
'dataProvider' => $model->search(),
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'PostType',
'filter'=>Html::activeDropDownList($model, 'PostType',array(""=>"All","1"=>"Status","2"=>"Images","3"=>"Video"),['class'=>'form-control','prompt' => 'Select Post Type']),
],
'PostTitle',
[
'header' => 'Artist',
'attribute' => 'ArtistName',
],
[
'header' => 'Date Posted',
'attribute' => 'DatePosted',
'filter' => false,
],
[
'header' => '# Likes',
'attribute' => 'TotalLikes',
'filter' => false,
],
[
'header' => '# Comments',
'attribute' => 'TotalComments',
'filter' => false,
],
[
'header' => 'Exclusive',
'attribute' => 'IsExclusive',
'filter'=>Html::activeDropDownList($model, 'IsExclusive',array(""=>"All","0"=>"Normal","1"=>"Exclusive"),['class'=>'form-control','prompt' => 'Select Exclusive']),
],
[
'header' => 'Status',
'attribute' => 'Status',
'filter'=>Html::activeDropDownList($model, 'Status',array(""=>"All","1"=>"Active","2"=>"Inactive"),['class'=>'form-control','prompt' => 'Select Status']),
],
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url);
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>
You should need to add [ 'data-pjax' => false ] or [ 'data-pjax' => '0' ] in anchor tag options of update button.
For example,
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url, ['data-pjax' => '0']);
},
],
]