Why my listview not found any record in yii2? - 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
],
];

Related

Pass Data Directly to yii2-tree-manager

I have a tree node in my form. I am using kartik-v's Tree Manager.
This is my view code:
echo TreeViewInput::widget([
'query' => Tree::find()->addOrderBy('root, lft'),
'headingOptions' => ['label' => 'Set Permission'],
'name' => 'name',
'value' => '1,2,3',
'asDropdown' => false,
'multiple' => true,
'fontAwesome' => true,
'rootOptions' => [
'label' => '<i class="fa fa-tree"></i>',
'class' => 'text-success'
]);
But, in this I have to follow the same table structure as mentioned in the widget. I have some extra fields and more permissions. So it is a bit complicated to use the same structure.
Is it possible to pass the value in an array directly to this widget? If possible let me know the array format.
Now I am stuck with this tree node implementation.
You can do this by doing some tricks, or by using another way:
1) you can add a condition to your query like this:
Tree::find()->andWhere(['not in','id',[2,3,4]])->addOrderBy('root, lft'),
by this solution you can ignore unwanted rows like you send data direct in array...
2) you can use another solution by using js lib/plugin direct like jsTree, in this case you can create and pass custom array direct...look at this example: jsTree Example

yii2 mpdf render html reached max memory size

I trying to render a very big pdf with mdpdf on Yii2 framework.
I genereate an html page, but when i call the render function, php run out of memory.
I don't wanna expand the memory_limit ini settings (256M is more than necessary).
I use this configuration, $html contains my huge code:
$pdf = new Pdf([
'mode' => Pdf::MODE_CORE,
'content' => $html,
'options' => [
'title' => 'Report',
],
'marginHeader' => 2,
]);
return $pdf;
Maybe there's a way to render step to step the pdf?
In Yii2 mpdf the content is normally a renderPartial for a form layout
and the renderPartial is populated by one or more models that are the result of query eg:
$models = MyModel::find()->all();
$content = $this->renderPartial('_mpdf_report_scheda', [
'model' => $models,
]);
$pdf = new Pdf([
.......
'content' => $content,
could be that in your case the result of the query retrieve to much rows so you could spliet you content in a part
eg: using limit() and offset()
$models = MyModel::find()
->limit(20)
->all();
$models = MyModel::find()
->limit(20)
.>offset(20)
->all();
and launch the pdf for parts

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,
],
]);
?>

Handle Image update in 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
}

yii2 join model as dataProvider

I've joined 2 tables like following:
$model = SalesEntry::find()
->joinWith('salesItems')
->all();
then in view used DataProvider like following:
GridView::widget([
'dataProvider' => $model,
'columns' => [
'date', // sample field from first table to see if ok
],
]);
and I’ve got following error:
Call to a member function getCount() on a non-object
What am I doing wrong here?
That is because an ActiveQuery instance is not a DataProvider, which the widget expects. You need to wrap it in an ActiveDataProvider for it to work:
GridView::widget([
'dataProvider' => new \yii\data\ActiveDataProvider(['query' => $model]),
' columns' => [
'date', // sample field from first table to see if ok
],
]);
DataProvider in GridView should be an instance of yii\data\DataProviderInterface
See docs.