Yii2-advanced : dataProvider - yii2-advanced-app

I want to increment my dataProvider in siteController. That is, at each iteration, my dataProvider should be incremented by 1 & renamed as dataProvider1,dataProvider2,dataProvider3,....& so on.
I tried to append $i to dataProvider, but it says 'dataProvider can't be converted to String...!'
My actionIndex is as follows :
public function actionIndex()
{
$query = new \yii\db\Query;
for ($i = 1; $i <= 20; $i++) {
$query->select('*')->from('business_main_categories')->where(['bmc_id' => $i]);
$query->createCommand();
$dataProvider.$i = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
return $this->render('index', [
'dataProvider' => $dataProvider.$i,
]);
}
}
And, I also want to user that dataProvider in my 'index.php' with iterations; I tried to insert a for loop & written all statements in 'echo', but I'm unable to get it done.
My way to access it in 'index.php' is as follows :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
[
'attribute' => 'bmc_image',
'format' => 'html',
'label' => '',
'value' => function ($data) {
return Html::img($data['bmc_image'],
['width' => '190px']);
},
],
]
]); ?>
Please help me to solve my issue.

I solved my problem without using gridview. As follows -
My SiteController -
public function actionIndex()
{
$searchModel = new BusinessMainCategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $dataProvider->getTotalCount(); //-1 : disable
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
using this code I get all records in dataProvider from my db.
(Note that, I'm using ActiveDataProvider in my 'BusinessMainCategoriesSearch' model)
And, my index.php is -
<?php
$m = $dataProvider->getModels();
foreach ($m as $dp) {
echo "<img src = '".$dp['bmc_image']."' />";
echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
} ?>
It worked great for me & it's a easiest way to do so.

Related

Symfony 4, remove blank fields in forms

->add('bill', EntityType::class, [
'class' => \App\Entity\Bill::class,
'attr' => [
'class' => "js-example-basic-single",
],
'label' => false,
'required' => true,
'choice_label' => function ($bill) {
$sumPrice = 0;
$sumPayment = 0;
foreach ($bill->getCost() as $item) {
$sumPrice = $sumPrice + $item->getPrice();
foreach ($bill->getPayment() as $pay) {
$sumPayment = $sumPayment + $pay->getMoney();
}
$sum = $sumPayment - $sumPrice;
if ($sum != 0) {
return
$bill->getPlayers()->getName() . " " .
$sum;
}
}
}
]);
And everything work fine, and i get only players that sum != 0, and for the rest players, I dont get players name (which is ok), but i get blank space, and I dont know how to remove it

How to increase picture using html code with yii2 syntax?

Hy guys, following code will increase picture by clicking on it:
<a class="example-image-link" href="http://lokeshdhakar.com/projects/lightbox2/images/image-1.jpg"><img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg" alt="image-1" /></a>
)
In my yii2 application, I have following valid picture-url in anonymous function:
$url = '#web/img/' . $bild->dateiname;
How to tranform upper code in yii2 syntax. I try like this, but it's not working:
return Html::a(
Html::img($url, ['alt' => 'PicNotFound', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']
), [Html::img($url, ['alt' => 'PicNotFound']
)], ['title' => 'Immobiliendaten abrufen', 'data' => ['pjax' => '0'], 'class' => 'example-image-link']
);
Firedebug will show following html-code. url in link is wrong!
a class="example-image-link" href="/yii2_ErkanImmo/frontend/web/index.php/" title="Immobiliendaten abrufen"><img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">event
<img class="img-circle" src="/yii2_ErkanImmo/frontend/web/img/villa1.jpg" alt="PicNotFound" style="width:125px;height:125px;">
</a>
Rephrasing question
I will get output as shown up at my attachement after having clicked on picture using code like this:
return Html::a(Html::img($url, ['alt' => 'image-1']), $url, ['class' => 'example-image-link']);[![enter image description here][1]][1]
Here is complete code of view file(for GRU)
[
'attribute' => $dummy,
'label' => Yii::t('app', ''),
'format' => 'html', // sorgt dafür,dass das HTML im return gerendert wird
'vAlign' => 'middle',
'value' => function($model) {
$bmp = '/bmp/';
$tif = '/tif/';
$png = '/png/';
$psd = '/psd/';
$pcx = '/pcx/';
$gif = '/gif/';
$jpeg = '/jpeg/';
$jpg = '/jpg/';
$ico = '/ico/';
try {
$bilder = \frontend\models\Dateianhang::GetBild($model);
foreach ($bilder as $bild) {
if (preg_match($bmp, $bild->dateiname) || preg_match($tif, $bild->dateiname) || preg_match($png, $bild->dateiname) || preg_match($psd, $bild->dateiname) || preg_match($pcx, $bild->dateiname) || preg_match($gif, $bild->dateiname) || preg_match($jpeg, $bild->dateiname) || preg_match($jpg, $bild->dateiname) || preg_match($ico, $bild->dateiname)) {
$url = '#web/img/' . $bild->dateiname;
}
}
return Html::a(Html::img($url, ['alt' => 'image-1', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']), $url, ['class' => 'example-image-link', 'title' => 'Touch picture to increase', 'target' => '_blank']);
//return Html::img($url, ['alt' => 'Bewerberbild nicht vorhanden', 'class' => 'img-circle', 'style' => 'width:225px;height:225px']);
} catch (Exception $e) {
return;
}
}
],
Neither picture will be increased, nor target=>_blank is doing its job :=(
Try following code -
<?php
$url = 'http://lokeshdhakar.com/projects/lightbox2/images/thumb-1.jpg';
//in your case
//$url = '#web/img/'.$bild->dateiname;
echo Html::a(
Html::img($url, ['alt'=>'image-1']),
$url, ['class'=>'example-image-link']);
?>
If you want to redirect to some action in controller, replace $url in last line with ['/controller/action']

yii2: Undefined variable: model

I am just starting Yii2 framework.
I want to create a dropdown list which is 1 to 10 and a submit button
Once select the option and click the button should go to next page to show the number I choose.
In my view file : index.php
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'QTY')->dropDownList(range(1, 10)) ?>
<?= Html::submitButton('Buy', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Then when I go to the page it gave me 'Undefined variable: model' at dropdown list there.
What should I do to make it correct?
And what is the different between Html and CHtml?
Thanks.
this code is form.php not index.php.
because we can see, there are active form.
your model is undefined maybe you write the wrong code
this is example of controller index.php
public function actionIndex()
{
$searchModel = new PersediaanBarangSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Html and Chtml is the same
in Yii1=CHtml
in Yii2=Html
This is ment to be pagination? If yes use default functionality of the grid view.
This goes to controller:
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
return $this->render('path_to_view',['dataProvider'=>$provider]);
Read more
This goes to view:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'created_at:datetime',
// ...
],
]);
Read more
Actually you model is not loaded, Please check below example.
public function actionIndex($id = Null)
{
$data=array();
$data['model'] = !empty($id) ? \app\models\YourModel::findOne($id) : new \app\models\YourModel();
return $this->render('index', $data);
}

how to pass variables "$tid, $id" into raw function?

when i call $id and $tid in raw function to fetch some data from sub document of mongodb collection it show me an error these two variables are undefined($tid,$id)?
<?php
$id=IntValue;
$tId=IntValue;
if($tId==0)
{
$maxPlayers=0;
}
else
{
$result = DB::collection('PrizeDistributionTemplate')->raw(function($collection)
{
return $collection->aggregate(array(
array(
'$match' => array( 'id' => $id,'templates.tId' => $tid)
),
array( '$unwind' => '$templates' ),
array(
'$match' => array( 'id' => $id,'templates.tId' => $tid)
),
));
});
$result=json_decode(json_encode($result),true);
$maxPlayers=$result['result'][0]['templates']['maxPlayers'];
$maxPlayers=intval($maxPlayers)+2;
}
?>
When you use a callback function in PHP, the function as it own scope and can't access variables from outside of it's scope.
$foo = true;
DB::collection('something')->raw(function ($collection) {
echo $foo;// $foo is undefined here, this create an error
});
echo $foo;// here it work
But you can feed your callback with variables using the PHP use keyword:
$foo = true;
DB::collection('something')->raw(function ($collection) use ($foo) {
echo $foo;// now it works
});
It will work great with bulk addition, this way you just need to create on array and pass it.
$temp = [
[
'item' => "envelopes"
],
[
'item' => "envelopesas"
],
[
'item' => "lala"
]
];
$userData = DB::table('log') - > raw(function ($collection) use($temp)
{
return $collection - > insertMany($temp);
});

How to populate Yii2 Autocomplete with AJAX call

I am trying to switch to Yii2 from Yii 1.1. This was source attribute of TextAreaJuiAutoComplete widget
'source'=>"js:function(request, response) {
$.getJSON('".$url"', {
term: extractLast(request.term)
}, response);
}",
This is not working in Yii2 with yii\jui\AutoComplete anymore. Can anyone give me a hint what is the cause? Underlying JavaScript objects should be the same.
If I put following code it works, but I want to use ajax calls instead.
'source' => [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ],
Try this:
use yii\web\JsExpression;
.....
.....
'source'=>new JsExpression("function(request, response) {
$.getJSON('".$url."', {
term: request.term
}, response);
}"),
Try this:
AutoComplete::widget([
'name'=>'myacfield',
'clientOptions' => [
'source' => Url::to(['autocomplete']),
'minLength'=>'2',
],
'options'=>[
'class' => 'form-control'
]
]);
But your AutoComplete action must return a one dimensional array like
...
$rs = Yii::$app->db->createCommand($sql)->queryAll();
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row['name']; //build an array
}
echo json_encode($row_set); //format the array into json data
Examle with like.
Controller:
public function actionSearch($term)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$rs = Cure::find()->where(['like', 'name_uz', $term])->all();
if($rs !=null){
$row_set = [];
foreach ($rs as $row)
{
$row_set[] = $row->name_uz; //build an array
}
return $row_set;
}else{
false;
}
}
In view:
<? use yii\jui\AutoComplete;?>
<?= AutoComplete::widget([
'model' => $model,
'attribute' => 'country',
'options' => ['class' => 'form-control'],
'clientOptions' => [
'source' => Url::to(['cure/search']),
'minLength'=>'2',
],
]); ?>