I have one problem in yii2 when I use
$model = Client::find()->where('id=1')->one();
UploadedFile::getInstance($model, 'logo');
then this gitme NULL value. Why am I getting NULL if I print $_FILES and them I see the array values.
I have use the simple upload file in yii2
My view :
$form = ActiveForm::begin(['action' => ['center/updatelogo'], 'layout' => 'horizontal', 'options' => ['enctype' => 'multipart/form-data']]);
echo $form->field($model, 'logo')->widget(FileInput::classname(), [
'options' => ['accept' => $model->logo, 'class' => 'form-control'],
'pluginOptions' => [
'allowedFileExtensions' => ['png', 'jpg'],
'maxFileSize' => 25000,
],
]);
My controller:
$model = Client::find()->where('id=1')->one();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'logo');
if ($model->validate()) {
$model->file->saveAs('logos/' . $model->file->baseName . '.' . $model->file->extension);
}
}
var_dump($file);die();
I need upload one file to mi server and put the logo, what happened?
my $_POST and my $_FILES :
array(2) {
["_csrf"]=>
string(88) "WF67odQ_DUylcUprRN9FssjEdq5nBn2ARrjjql_D8af6Y1am1ID7AEG5KV2iWNL-7QeEoeGF_UJQYxnH6JgS1A=="
["Center"]=>
array(1) {
["logo"]=>
string(0) ""
}
}
array(1) {
["Center"]=>
array(5) {
["name"]=>
array(1) {
["logo"]=>
string(19) "Libre Albedrío.jpg"
}
["type"]=>
array(1) {
["logo"]=>
string(10) "image/jpeg"
}
["tmp_name"]=>
array(1) {
["logo"]=>
string(14) "/tmp/phpYijyXv"
}
["error"]=>
array(1) {
["logo"]=>
int(0)
}
["size"]=>
array(1) {
["logo"]=>
int(19900)
}
}
}
Related
I have developed application in yii2 and for filter in grid view i had used Kartik date-range picker extension.
I have faced following problem.
When i select different date for start and end date then it will worked.
e.g start date 5 and end date 10
When i select next day same date for start and end date then it will worked.
e.g start date 6 and end date 6
When i select today's date for start and end date then it will not worked.
e.g start date 5 and end date 5
Sample code.
<?php
$gridColumns = [
[
'class' => 'kartik\grid\SerialColumn'
],
[
'label' => Yii::t('app', "Created At"),
'attribute' => 'created_at',
'value' => function ($model) {
if (extension_loaded('intl')) {
return $model->created_at;
} else {
return $model->created_at;
}
},
'filter' => DateRangePicker::widget(
[
'model' => $searchModel,
'attribute' => 'created_at',
'convertFormat' => true,
'presetDropdown' => false,
'pluginOptions' => [
'locale' => [
'format' => 'Y-m-d'
]
]
]
)
],
[
'attribute' => 'branch_id',
'value' => 'branch.name',
'filter' => Html::activeDropDownList(
$searchModel,
'branch_id',
ArrayHelper::map(Branch::find()->asArray()->all(), 'id', 'name'),
['class' => 'form-control', 'prompt' => 'Select Branch']
)
],
[
'attribute' => 'user_id',
'value' => 'user.firstname',
'filter' => Html::activeDropDownList(
$searchModel,
'user_id',
ArrayHelper::map(User::find()->asArray()->all(), 'id', 'firstname'),
['class' => 'form-control', 'prompt' => 'Select User']
)
],
[
'attribute' => 'order_status',
'format' => 'html',
'filter' => ["0" => "Completed", "1" => "Refund", "2" => "Cancel"],
'value' => function ($model) {
if ($model->order_status == '1') {
return '<span class="label bg-red">Refund</span>';
} else if ($model->order_status == '2') {
return '<span class="label bg-yellow">Cancel</span>';
} else {
return '<span class="label bg-blue">Completed</span>';
}
}
],
[
'attribute' => 'created_from',
'format' => 'html',
'value' => function ($model) {
if ($model->created_from == '1') {
return '<span class="">WEB<small>';
} else if ($model->created_from == '2') {
return '<span class="">IOS<small>';
} else if ($model->created_from == '3') { //MARKAS
return '<span class="">ANDROID<small>';
}
}
],
[
'attribute' => 'pax',
'format' => 'html',
'value' => function ($model) {
$setting = common\constants\EstablishmentConfiguration::activeSetting();
$type = '';
$paxFlag = '0';
if (!empty($setting)) {
$type = $setting->establishment_type;
$paxFlag = $setting->enable_pax;
}
if ($type == 'restaurant' && $paxFlag == '1') {
return $model->pax;
} else {
return '--';
}
}
],
//'pax',
'sub_total',
'discount',
'tax',
'grand_total',
[
'class' => 'yii\grid\ActionColumn',
'header' => Yii::t('app', 'Action'),
'template' => '{view} {movetofack}',
'contentOptions' => ['style' => 'width:10%'],
'buttons' => [
'view' => function ($url, $model) {
return Html::a(
'<span class="glyphicon glyphicon-eye-open"></span>',
['view', 'id' => $model->id],
[
'class' => 'btn btn-xs btn-warning',
'title' => 'View',
'data-skin' => 'skin-warning'
]
);
},
'movetofack' => function ($url, $model) {
return Html::a(
'<span class=" fa fa-trash"></span>',
[
'movettotrash', 'id' => $model->id
],
[
'class' => 'btn btn-xs btn-warning',
'title' => 'Fack Record',
'data-skin' => 'skin-warning',
'data' => [
'confirm' => Yii::t('app/msg', 'Are you sure this is fake record? would you like to move to trash this order?'),
'method' => 'post'
]
]
);
}
]
]
];
I use Yii2 and widget Select2. I want onkeyup to search products from table "Products" with options for multiple select, because i must save result in second table "rel_products". I do know why it return error : "Illegal offset type"
Here is model:
public $products = array(); =>because i write result in second table
here is view:
$url = \yii\helpers\Url::to(['/product/prodlist']);
echo $form->field($model, 'products')->widget(Select2::classname(), [
'initValueText' => 'Search for a city ...', // set the initial display text
'model' => $model,
'attribute' => 'products',
'theme' => 'bootstrap',
'options' => ['placeholder' => 'Search for a city ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(product) { return product.text; }'),
'templateSelection' => new JsExpression('function (product) { return product.text; }'),
],
]);
Here is Controller:
public function actionProdlist($q = null, $id = null) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select()
->from('product')
->joinWith('translation')
->where(['like', 'title', $q])
->limit(20);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Product::find($id)->title];
}
return $out;
}
change in model:
public $products; =>because i write result in second table
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() ?>
Following code will show empty array for chekckBoxColumns respectively NULL in Controller of yii framework.
Any ideas, what I do wrong?
Here is code of GridView
<?=
Html::beginForm(['/mail/mail-eingang/deleteallmails'], 'post', ['name' => 'document']);
?>
<p>
<?= Html::submitButton('Delete', ['name' => 'button_checkBoxes', 'title' => 'Löscht alle ausgewählten Mails']); ?>
</p>
.
.
$gridColumn = [
.
.
[
'class' => '\kartik\grid\CheckboxColumn', 'checkboxOptions' => function($model) {
return ['value' => $model->id];
},
],
];
?> <?=
Html::endForm();
Here is Controller
public function actionDeleteallmails() {
$checkbox = (array) Yii::$app->request->post('selection');
print_r("var_dump of post:<br>");
var_dump(Yii::$app->request->post());
print_r("<br><br>var_dump of POST[button_checkBoxes]:<br>");
var_dump($_POST['button_checkBoxes']);
print_r("<br><br>var_dump of post(selection):<br>");
var_dump(Yii::$app->request->post('selection'));
print_r("<br><br>var_dump of checkbox:<br>");
var_dump($checkbox);
die();
}
Controller will give me following result:
var_dump of post:
array(3) { ["_csrf-frontend"]=> string(88) "aOy2kVhHjxM_Q40lq4Cfs-izrPeqhVDXxwcjO-HAxmAOuc7LOSzKf1EOoGfo4ffWsNHnws2yIYb1U2JQq_miVw==" ["button_checkBoxes"]=> string(0) "" ["MailEingangSearch"]=> array(5) { ["id"]=> string(0) "" ["mail_adresse_absender"]=> string(0) "" ["betreff"]=> string(0) "" ["bodytext"]=> string(0) "" ["gelesen"]=> string(0) "" } }
var_dump of POST[button_checkBoxes]:
string(0) ""
var_dump of post(selection):
NULL
var_dump of checkbox:
array(0) { }
How can put an ActiveForm in a gridview column? The following is the code I made: I tried to render the page such that it includes the active form which I need.
'columns' => [
[ 'format' => 'html',
'value'=> function($data) { return Html::img($data->imageurl) . " <p class='feedback-username'>" . $data->username . "</p>"; },
'contentOptions'=>['style'=>'width: 30px; height: 30px'],
],
[ 'format' => 'raw',
'value' => function($model) { return "<p class='feedback'>". $model->KOMENTAR ."</p><br><p class='feedback-date'>". $model->TANGGAL ."</p><hr><div id='replay-". $model->ID_KOMENTAR."'><ul></ul></div>";},
],
[ 'format' => 'raw',
'contentOptions'=>['style'=>'width: 5px;'],
'value' => function($model) {
if($model->id == Yii::$app->user->identity->id) {
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',null,['id'=> 'replay-to-'. $model->ID_KOMENTAR ]).' '.
Html::a('<i class="glyphicon glyphicon-pencil"></i>', ['update', 'id' => $model->id]).' '.
Html::a('<i class="glyphicon glyphicon-trash"></i>', ['delete', 'id' => $model->id], ['data' => ['confirm' => 'Do you really want to delete this element?','method' => 'post']]);
}
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',['feedback', 'id' => $model->id],['id'=> 'replay-to-'. $model->ID_KOMENTAR ]);
},
],
[
'content' => $this->render('feedback_test'),
],
But I got this error:
PHP Warning – yii\base\ErrorException
call_user_func() expects parameter 1 to be a valid callback, function '
<div class="feedback-form">
<p>test</p>
</div>' not found or invalid function name
How do I include the active form in the grid view's column?
Try this.
[
'content' => function($model, $key, $index, $column) {
echo $this->render('feedback_test');
OR
echo $this->render('feedback_test', ['model' => $model]);
},
],
The above answer outputted the form above my grid. I wanted the form in one of my columns for every row of data. I ended up customizing an ActionColumn like this:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{map}',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'map' => function ($model) use ($m, $r) {
return $this->render('_form', ['model' => $m, 'req' => $model, 'ref' => $r]);
},
],
'urlCreator' => function ($action, $model) {
if ($action === 'map') {
return $model;
}
},
]