Listview and custom dataprovider search yii2 - php

I am working on a project in which to display some data i am using a custom query and saving those data in dataProvider. Passing that dataProvider to view file and displaying using a Listview. just like below
<nav class="navbar navbar-fixed-top">
<form class="navbar-form navbar-left search-form" action="">
<div class="form-group"><input type="text" class="form-control app-search" placeholder="Search">
</div>
</form>
</nav>
<div class="panel-group" id="accordion">
<?= \yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'eventlistview',
'layout' => "{items}",
]); ?>
</div>
I want to implement a search bar for that Listview. I am not using any SearchModel so i am confused that how can i do that?
Here is my action code.
public function actionEvent()
{
$this->layout = 'app';
if(isset($_GET['latitude']) && isset($_GET['longitude'])){
$query = new Query();
$query ->select(['e.*','COUNT(d.event_id) as checkins' ,'o.clubname',new Expression("case when c.id is not null then 1 else 0 end is_checkedin")])
->from('event e')
->innerJoin('organiser o', 'e.organiser_id = o.organiser_id')
->leftJoin('checkin c', 'c.event_id = e.id and c.user_id ='.$_GET['user_id'])
->leftJoin('checkin d', 'd.event_id = e.id' )
->where('e.interest_id IN
( SELECT area_intrest.id FROM area_intrest, user WHERE FIND_IN_SET(area_intrest.id,user.area_intrest) AND user.id='.$_GET['user_id'].')')
->groupBy('e.id');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
}
return $this->render('event' ,['dataProvider' => $dataProvider]);
}
I am just confused because i am not using any search model here so i dont know how can i search using title of the event.

In view you can use an active form for sending the value
<?php
$form = ActiveForm::begin(['id' => 'my-form',
'method'=>'get',
'action' => Url::to('your-controller/event')]);
?>
<input type="text" class="form-control app-search" name="my_search" placeholder="Search">
<?= Html::submitButton('search') ?>
<?php ActiveForm::end(); ?>
in your actionEvent you can
$this->layout = 'app';
if (isset($_GET('my_search')) {
// perform what you nedd ..
}
if(isset($_GET['latitude']) && isset($_GET['longitude'])){

Related

Codeigniter data from view to controller

Each User has multi profiles. once they logged in, they are asked to select a profile,
here is the code for Form to select profile.
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 align ="center" class="panel-title">Select Profiles</h3>
</div>
<div class="panel-body">
<?php
foreach($resJacs->{'details'} as $key) {
echo form_open('selectaccess', array(
'class' => 'form-group',
'role' => 'form'
));
echo form_submit(array(
'value' => $key->profile_name,
'name' => $key->profile_type,
'class' => 'btn btn-lg btn-default btn-block'
));
echo form_close();
}
?>
</div>
</div>
</div>
</div>
when user selects the profile profile id is passed to session for later use. here is the code for "selectaccess",
public function SelectAccess() {
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => $this->input->post('')
);
print_r($sess_data);
}
how can i prfid as mentioned in selectaccess method.
I just want to give an example, maybe this can help u :
I am use pure html .
<form action="SelectAccess/<?php echo $id; ?>">
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
Controller
function SelectAccess($val='') {
$input = $this->input->post('name');
$_SESSION['whatever'] = $val;
}
Normally you need to know the name of the field in order to get the value at the controller. But you are dynamically creating the field names so that gets tricky.
Fortunately you are only posting one input so $_POST should have only one item. The way your view is written the value of $_POST[0] will be provided by $key->profile_name. Hopefully, that value is what you are looking for.
public function SelectAccess() {
{
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => isset($_POST[0])) ? $_POST[0] : NULL;
);
}

yii2 gridview no pagination wont work on more than 3 thousand records

when I click on the action of a controller and i disable pagination, the web page won't load...
the problem is when i click on the action controller which is some sort of:
public function actionMyview(){
return $this->render("//myview/index");
}
in the view code I'm making some sort of MVVM (i'm calling the ActiveDataProvider into it):
<?php
set_time_limit(0);
use yii\helpers\Html;
use yii\grid\GridView;
use frontend\models\myModel;
use yii\web\View;
use yii\data\ActiveDataProvider;
$dataProvider2 = new ActiveDataProvider([
'query' => myModel::find(),
'pagination' => false,
]);
$this->title = 'Listing 3 thousand records';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ventas-model-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create manually a new record', ['create'], ['class' => 'btn btn-success col-xs-4 col-md-4 col-sm-4 col-lg-4']) ?>
<div class="col-xs-3 col-md-3 col-sm-3 col-lg-3" >
<input type="text" class="form-control" id="search-criteria" placeholder="please write a text in order to search" width=""/>
</div>
<span class="col-xs-5 col-md-5 col-sm-5 col-lg-5"> </span>
<?php
$this->registerJs("
var rows = jQuery('.table tr');
$('#search-criteria').keyup(function() {
var val = jQuery.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
rows.show().filter(function() {
var text = jQuery(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
",
View::POS_END,
'ventanamodal001');
?>
</p>
<?php echo GridView::widget([
'dataProvider' => $dataProvider2,
'columns' => [
[
'attribute' => 'date',
'format' => ['date', 'php:d/m/Y']
],
["label"=>'First Column',"attribute"=>"first","value"=>function($data0){
return myModel::aBolivares($data0->first);
}],
["label"=>'second Column',"attribute"=>'second',"value"=>function($data0){
return myModel::aBolivares($data0->second);
}],
["label"=>"totals","value"=>function($data0){
$totals=$data0->first+$data0->secod;
return myModel::aBolivares($totals);
},"format"=>"html","enableSorting"=>true,"attribute"=>"first"],
['label'=>'description',
'value'=>function ($data){
return empty($data->Observ)?" ":"<p class='glyphicon glyphicon-eye-open'></p>";
},
"format"=>"html","attribute"=>"Observ"],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
the code sample will iterate into a yii2 ActiveDataProvider object given to the yii\grid\GridView;... when I upload into a remote location it will fail: (I'm using HostGator shared hosting).
IT'S IMPORTANT TO SAY: IT WILL FAIL WHEN GIVEN MORE THAN 3 THOUSAND RECORDS == 3000 records directly from DB. If you use let's say 1500 records it will slow down but will work... only when injecting a high volume of records will fail...

Rendering two models in View yii2

I am trying to render two models in the actionView method, but without result. Checked some answers on previous questions and it seems my method is OK, but still do not work.
This is what a made for method view:
public function actionView($id)
{
$postModel = Post::find()->where(['post_id' => $id])->one();
$currUser = BlogUser::find()->where(['id' => $postModel->user_id])->one();
return $this->render('view', [
'model' => $this->findModel($id),
'author' => $currUser
]);
}
and my view page:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Post */
//$this->title = $model->title;
//$this->params['breadcrumbs'][] = ['label' => 'Posts', 'url' => ['index']];
//$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content;
$author->username;
?>
</div>
</div>
</div>
</div>
It tells that the author variable is undefined but cannot realize why when i render it in the action. Will appreciate every advice! Thank you!
Try using:
<div class="post-view">
<div class="content">
<div class="row">
<div class="col-md-3">
<?= $model->content; ?>
<?= $author->username; ?>
</div>
</div>
</div>
</div>

Yii2 Render widget dynamically

I would like to render JQuery UI sortable list (I am using Yii2 JUI widget), to be populated with data from database table. I am passing data from database to the view and have it in a variable. The item HTML structure looks like this:
<div class="row row-item dist simple-border">
<div class="col-md-4">
<img alt="Bootstrap Image Preview" src="<IMAGE_PATH>" />
</div>
<div class="col-md-8">
<h4>
<ITEM DESCRIPTION>
</h4>
</div>
</div>
My question is: What is the best way to populate items inside the Widget, as it is impossible to execute php code within.
<?= yii\jui\Sortable::widget([
'items' => [
------<expected foreach php loop for each model>------
['content' =>
<This is where one HTML item goes>
],
------<end foreach>------
],
'options' => ['class' => 'connectedSortable',],
'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>
My first idea was to create a function that returns item content as a string, but it doesn't seem like a good, efficient practice. Any ideas would be greatly appreciated. Regards.
EDIT: So far, I have created a function, which renders mentioned above items by concatenation. Still, I don't think this is the proper way to do it. I am still new to Yii and would be thankful for any tips. Regards.
I have found such solution for my problem, feel free to review and improve it.
Controller
public function actionIndex()
{
$searchModel = new Exchange();
$dataProvider = $searchModel->getOwnerItems(Yii::$app->request->queryParams);
$ownerItems = $this->getOwnerItems($dataProvider);
return $this->render('index', [
'ownerItems' => $ownerItems,
]);
}
protected function getOwnerItems($dataProvider){
$items=array();
foreach($dataProvider->models as $model){
$item=array('content' => '<div class="row row-item dist simple-border"> <div class="col-md-4"> <img alt="Bootstrap Image Preview" src="uploads/'.$model->image.'" /> </div> <div class="col-md-8"> <h4>'. $model->name .'</h4> </div> </div>');
array_push($items,$item);
}
return $items;
}
View
<?= yii\jui\Sortable::widget([
'items' => $ownerItems,
'options' => ['class' => 'connectedSortable',],
'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>
I am aware of possible imperfection of this solution, but I have no other ideas at the moment. Regards

Yii Framework - in a main view I can't add a CActiveForm because it needs a model, when I set the model nothing happens

I put this on my view, and I have to add the <?php $model = new Usuarios; ?> and it works but then actually does not send the info to the database.
I tried on another view (index view) and without this it works: <?php $model = new Usuarios; ?>.
<a class="list-group-item">
<form role="form">
<div class="form">
<?php $model = new Usuarios; ?>
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'usuarios-form',
'action' => $this->createUrl("usuarios/create"),
'enableAjaxValidation' => false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div style="padding:1px;" class="input-group input-group-sm">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user" style="color:white"></span>
</span>
<?php echo $form->textField($model, 'Nombre', array('maxlength' => 128, 'placeholder' => 'Nombre y Apellido')); ?>
<?php echo $form->error($model, 'Nombre'); ?>
</div>
<div class="row buttons" style="padding:4%; color:white ; font-size:1.5vmax; font-family: Signika; border-radius:30px">
<center>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Enviar' : 'Save'); ?>
</center>
</div>
<?php $this->endWidget(); ?>
</div>
</form>
</a>
This is what your controller action should look like:
public function actionCreate() {
$model = new Usuarios;
if(isset($_POST['Usuarios'])) {
// Populate the model with values from form
// These attributes must be set to safe in the model rules() function
$model->attributes = $_POST['Usuarios'];
// ->save() will validate the model with the validation rules
// in the Usuarios.php model. If you do not want validation, use ->update()
if($model->save()) {
$this->redirect(array('view', 'id' => $model->primaryKey));
}
}
$this->render('create', array(
'model' => $model, // You pass the model to the view page
));
}
In your model, you need to update the rules() function to accept the fields for saving in the database:
public function rules() {
return array(
array('Nombre', 'safe'),
);
}

Categories