Handle Image update in yii2 - yii2

Hi everyone i am using FileInput kartik widget in yii2 project and uploading and saving works fine but i am having problem while updating the images
I can get the images path on the update form and create and array and display in as initialpreview in the widget but the problem is that my files field is required field so even there are some values in initialpreview the form gives error to upload image as its required field. So what should i do here?
I only want to give preview of their uploaded pics to the user but if they dont make any changes than i dont want to update anything for images
Following is my view code and model code
return [
[[ 'price', 'created_date', 'created_by', 'updated_date', 'updated_by','file','address'], 'required'],
[['price'], 'number'],
[['address'], 'string', 'max' => 255],
[['file'], 'file', 'extensions'=>'jpg, gif, png', 'maxFiles' => 4],
];
<?php
$initalpreview = array();
foreach($model->adsImages as $images) {
$initalpreview[] = Html::img('/upload/'.$images->image, ['class'=>'file-preview-image']);
}
?>
<?=$form->field($model, 'file[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*',
'multiple'=>true],
'pluginOptions' => [
'maxFileCount' => 5,
'initialPreview'=> $initalpreview,
'showUpload' => false,
]
]); ?>
So what should i do here?
Thank you

try this
In Model create a scenario named 'update' and mention the fields that are required when update action works
return [
[['price', 'created_date', 'created_by','updated_date','updated_by','address'], 'required', 'on' => 'update'],
];
Now inside controller action update call the scenario
public function actionUpdate(){
//Model Declaration
$model->scenario = 'update';
// update code
}

Related

Why my listview not found any record in yii2?

I have a dataprovider to search a world but my listview does not display any record? How can i send this query object to listview?
every thing in my webpage is worked very good but at the output my list view show "not found any result" this mean my list view code is no have problem . problem is in my dataprovider and this query beacuse i customize that
my controller:
$query = new Query();
$dataProvidersearch=new ActiveDataProvider([
'query'=>$query->from('tbl_post')->Where(['like', 'title', $search])-
>andWhere(['like', 'en_title', $search])->andWhere(['like', 'content', $search])->andWhere(['like', 'en_content', $search]),
]);
this is my list view in my view:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
]);
I'm not sure you have enough code here for someone to help. Even something simple like a listview could consist of a view, a controller, and two model files and your code could be failing at any of these points. You may have simply forgot to include the listview library at the top of your view, but we can't see that in your current example.
What I would recommend is using Gii to generate a listview. It is simple to do and once you have it created, you can study the code to see where you went wrong. You can see how to get started generating code with Gii here: http://www.yiiframework.com/doc-2.0/guide-start-gii.html
ANSWER FROM COMMENTS: Replace andWhere with orWhere, no results are found because no record can match 'title' and 'en_title' and 'content' and 'en_content'.
You are submitting $posts as 'dataProvider' while it should be dataProvidersearch
Instead of:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$posts,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];
Should be:
$posts = $model->getModels();
echo ListView::widget([
'dataProvider'=>$dataProvidersearch,
'itemView'=>'search',
'summary' => '',
'itemOptions' => [
'tag' => false
],
];

Yii2-admin RBAC: Get roles from database and display as Dropdownlist on Signup/User registration

I am looking for a way to enable an administrator to assign users roles after registering them from the backend. I have configured yii2-admin in yii2 advanced and I have roles already set in the database table.
However I want to get the roles on the user registration form as a dropdown list and the administrator should be able to select a role and assign to the user. The roles on the dropdown list should be those lower than that of the admin or equivalent to his...i.e if there is a sysadmin role that is superuser, the admin should not be able to get the role as one of the options since assigning that role means the user will be higher than his role.
I have searched online but only gotten the code for Yii 1.1 which I tried to customize but does not work at all. The code is provided below:
Dropdown list on the form:
<?php
if (Yii::app()->user->isSuperuser) {
$all_roles=new RAuthItemDataProvider('roles', array(
'type'=>2,
));
$data=$all_roles->fetchData();
?>
<div>
<label for="type_id">Type</label>
<?php echo CHtml::dropDownList("Type",'',CHtml::listData($data,'name','name'));? >
</div>
<?php
}
?>
And the controller code is:
if(Yii::app()->user->isSuperuser)
$type=$_POST['Type'];
else
$type='User';
$authorizer = Yii::app()->getModule("rights")->authorizer;
$authorizer->authManager->assign($type, $model->id);
Anyone with an idea of how to transform this to Yii2 ? Please assist; I have been stuck on this problem for some time.
Thank you.
Here is an idea on how to proceed with this. Having set up yii2-admin, set up the necessary dbTables and added the authManager settings to your config section like so
$config = [
...
'components' => [
...
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
],
'as access' => [
'class' => 'mdm\admin\components\AccessControl',
'allowActions' => [
'site/*',
//'admin/*',
//'gii/*',
]
],
];
you have access to the authManager component.
In your controller you can obtain the roles of the current user like so
$current_user_roles = Yii::$app->authManager->getRolesByUser(Yii::$app->user->id);
Next you can get a list of all roles you have defined like so
$available_roles = Yii::$app->authManager->getRoles();
From here you would have to apply your role hierarchy logic to define what roles this user can assign (you should end up with a list of roles this user cannot assign, lets say $forbidden_roles). Once you have these 2 lists that you can remove the $forbidden_roles from the $available roles array with a simple foreach() statement, for example:
foreach($forbidden_roles as $role){
if(in_array($role,$available_role)){
$index = array_search($role,$available_role);
\yii\helpers\ArrayHelper::remove($available_roles,$index);
}
}
Now you have an array with the roles that the user can assign. Pass this array to your view and subsequently to the dropdown element and you should be set.
I have not personally tried this out but let me know if it works for you. Hope this helps.
i use in my app with below code in _form
get load user_id and all name
you only change condition in query
$users= ArrayHelper::map(app\models\User::find()->orderBy('username')->asArray()->all(), 'id', 'username');
$item= ArrayHelper::map(app\models\Authitem::find()->orderBy('name')->asArray()->all(), 'name', 'name');
echo $form->field($model, 'item_name')->widget(Select2::classname(), [
'data' => $item,
'options' => [
'placeholder' => 'انتخاب کنید...',
],
'pluginOptions' => [
'allowClear' => true,
],
]);
?>
<?php
echo $form->field($model, 'user_id')->widget(Select2::classname(), [
'data' => $users,
'options' => [
'placeholder' => 'انتخاب کنید...',
],
'pluginOptions' => [
'allowClear' => true,
],
]);
?>

yii2 SluggableBehavior is applied to only emty slug field

I am using SluggableBehavior in such way
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'name',
'slugAttribute' => 'alias',
],
];
}
It works nice If field 'alias' in form is empty.
How to ignore this behaviors If field alias is not empty on form submitting ?
thanks in advance !
Add 'immutable'=>true in the behavour config.
The behaviour works in such way, that if the slugAttribute is not empty when immutable is on, that attribute will not be changed.
Try something like:
Configure this behavior with specific name:
return [
'slug' => [
'class' => SluggableBehavior::className(),
'attribute' => 'name',
'slugAttribute' => 'alias',
],
];
In controller load attributes from the form (before validation).
Check if alias attribute is empty.
If it is not - detach this behavior ($this->detachBehavior('slug')).
Validate model.

html to pdf converter in yii2 with pagination in table

view:
<p>
<?= Html::a('Download This page', ['report'], ['class' => 'btn btn-danger']) ?>
</p>
controller:
public function actionReport()
{
// setup kartik\mpdf\Pdf component
$pdf = new Pdf([
'content' => $content,
'options' => ['title' => 'Krajee Report Title'],
'methods' => [
'SetHeader' => ['Krajee Report Header'],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
This function works perfectly but my html table has pagination . so i am confused how to deal with table that has pagination.
You should disable the pagination. it all depends on how you define your data provider (read more about data providers here http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html). Probably you should do something like this
************* = new ActiveDataProvider([
'pagination' => false,
..............
]);
I think you can also call it like
$dataProvider->pagination =false;
Just in case you need to disable it in a specific case.

Multiple values in one field Yii2

How to display multpiple values in one field.. I Use Select2 Widget. If i use $courses_model[0] it display only one value
Controller
public function actionUpdateteachers($id)
{
$courses_model = ReferenceTeachersCourses::find()->where(['reference_teachers_id' => $id])->all();
.....
}
View
...
<?= $form->field($courses_model[0], 'reference_course_type_id')->widget(Select2::classname(), [
'data' =>ArrayHelper::map($courses,'id','name'),
'options' => ['multiple' => true],
'pluginOptions' => [
'allowClear' => true,
],
]);
...
?>
This widgets works fine - but your $courses_model[0]->reference_course_type_id must have an array of ids as a value if you want to see multiple values selected.