Populate Dropdown using database query results - php

First and foremost, i'm very green in Laravel. So pls take that into consideration if i use any wrong terminlogy or dont grasp some stuff that should be obvious to you all.
I'm trying to populate a dropdown list with the results of database query.
Model for Dropdown Entries:
Class Dropdown {
public static function getFilters() {
$filter = DB::select(DB::raw('SELECT DISTINCT filter AS filt
FROM filter.database'));
return $filter;
}
}
Controller:
class FilterController extends BaseController {
public function getSql_Test() {
$dropdown = Dropdown::getFilters();
return View::make('Dropdown.show', ['Dropdown' =>$dropdown]);
}
}
What my controller accomplishes right now is to display the results of the query (which i want to populate the dropdown) on the page. Can someone pls help me on how to pass this entries onto the select tag here and show it on my View?

That is very easy to do, and fun (cause its easy)!
$filter = DB::table('filter.database')->select(DB::raw('DISTINCT(filter) AS filt'))
->lists('filt');
This will give you an array where the key is an integer and the value is your filter.
$filter = DB::table('filter.database')->select(DB::raw('DISTINCT(filter) AS filt'))
->lists('filt', 'filt');
This will give you an array where the key is filt and the value is filt.
you can push it into the view by extending your view with the variable like so:
return View::make('Dropdown.show')->with('dropdown', $dropdown);
Now you can make your select and just push in the array where the value should be:
echo Form::select('size', $dropdown);
More information can be found here:
http://laravel.com/docs/4.2/queries#selects
As a tip, stay on the laravel docs. They are a treat to work with.

Related

How to use paginate in the model::list method for combo in laravel?

I would like to know what is the way to paginate my combo of charges; it comes from my database description column, with all rows but I just want to show some of them.
Below is the method I'm using for that purpose:
// VIEW TO REGISTER USERS
public function VistaRegistraUsuario()
{
$id_franquicia_usuario = Session::get('id_franquicia');
$charges = charges_users::lists('descripcion', 'id'); // COMBO OF CHARGES
return view('auth.register', compact('charges', 'id_franquicia_usuario'));
}// END VIEW
What am I doing wrong and how can I achieve this?
Basically it's a question of pagination I assume as you need to show some of the "Combo of Charges" in other words pagination
use list with Laravel's out of the box pagination like this
public function VistaRegistraUsuario()
{
$id_franquicia_usuario = Session::get('id_franquicia');
$charges = charges_users::lists('descripcion', 'id')->paginate(15); // IF YOU NEED TO RENDER 15 COMBO OF CHARGES ON FIRST PAGE
return view('auth.register', compact('charges', 'id_franquicia_usuario'));
}
Refer: docs

Yii2: Assigning dynamic properties to model and displaying them in a grid

To keep things short, the application itself is really simple, having only three tables.
Product:
id
name
Attribute
id
name
slug
Product Attribute
id
attribute_id
product_id
value
As you may guess the attributes may be totally random, with any content and there might be any number of them. Every product has the same set of global attributes assigned. Some are empty, some are filled.
What I want to do is displaying them in a standard Gridview, the same way as if it was a normal model, with dynamic-preassigned columns and values. Basically speaking - the attributes should serve as the columns.
I've tried to extend the main Product Model and use ActiveDataProvider class on it, but no avail, I'm getting the custom attributes values repeated for each row, as if something was missing. Here's the class I've created basing on another question from SO.
namespace common\models;
use Yii;
use common\models\Attribute;
use common\models\Product;
class ProductDynamic extends Product {
public function init() {
parent::init();
$attrExists = ProductAttribute::find()->select(['slug','value'])->joinWith(['attributeModel'])->all();
if ($attrExists) {
foreach ($attrExists as $at) {
$this->dynamicFields[$at['slug']] = $at['value'];
}
}
}
private $dynamicFields = [];
public function __get($name) {
if (array_key_exists($name, $this->dynamicFields))
return $this->dynamicFields[$name];
else
return parent::__get($name);
}
public function __set($name, $value) {
if (array_key_exists($name, $this->dynamicFields))
$this->dynamicFields[$name] = $value;
else
parent::__set($name, $value);
}
public function rules() {
return array_merge(parent::rules, $this->dynamicRules);
}
}
My question is - how would you do it? How to assign properties to a model so they act as a standard database-loaded properties usable by ActiveDataProvider? I think I need to retrieve the ProductAttributes some other way so they are not repeated. See below.
Ok, i think i got your idea...
So, I think you could generate an attribute in the model of Product (we will call it ProductAttributeArr) which would be an array, then retrieve the attributes from the Attribute table in the database according to Product Attribute table and store them in ProductAttributeArr.
Then you could create a function that dynamically generates the parameters for the GridView base on the content of ProductAttributeArr. This way it should work.
Answering it myself since there's no feedback and after some more digging i've found the quickest, but maybe not the nicest solution.
Since the properties in main Product model are added thanks to the ProductDynamic class I have added the following in Product to assign correct column values. For sure, there must be another, easier way, if you know any feel free to comment.
public function afterFind() {
$attrs = ProductAttribute::find()->select(['slug', 'value'])->joinWith(['attributeModel'])->where(['product_id' => $this->id])->all();
foreach ($attrs as $a) {
$this->{$a['slug']} = $a['value'];
}
}

Calling function with return value in cakephp

I am new to cakephp. I have a problem with calling the function. here is my issue.
In Contrloller file i get all the values using the following function
public function index()
{
$conditions = array(
'order' => array('Histroy.chat_sk DESC')
);
$this->set('histroys', $this->Histroy->find('all',$conditions));
}
In My model file have the following,
class Histroy extends AppModel
{
public $tablePrefix = 'plc_';
public $useTable = 'chat_history';
}
In my view file i have listed the values using foreach() function and that as follows
foreach ($histroys as $histroy):
$oper_name = $histroy['Histroy']['operator_fk'];
$operator_email = $histroy['Histroy']['email'];
endforeach
in that opertaor_fk is a field in history table. So i need get the operator name by another table as operators. So i need to call that function in the view.
Ex : In core we can do like as,
$operator_name = operator_name($fetch['operator_id']);
Function should be like this:
function operator_name($id)
{
// Select the value for the matched field in the operator
return $operator_name;
}
In cakephp how can i retrieve the values.
Please help me out to fix this. Thanks in Advance
Follow the blog tutorial for cake. It'll explain how to create associations and relationships between tables to let you do what is is you want, but in a nutshell, you need to create a relationship between History and Operator models and work from there.

Fetching and printing a single value from database using laravel

I'm currently trying to create my settings page by creating a table settings with company_name column. My idea is to fetch the single value company_name and print it in the title of the pages and where the name is going to be appearing. I just am not sure how to convert the array return from the DB::select to be able to print it correctly.
The code:
public function __construct()
{
$company_name = DB::table('settings')->select('company_name')->get();
return View::share('company_name', $company_name);
}
And print it in the blade system as {{ $company_name }}, although it can't convert an array to string.
Either use eloquent (that I would recommend) which would be like this :
$company_name = Setting::first()->company_name;
or using fluent :
$company_name = DB::table('settings')->company_name;
Could you use ->first() to select the first value from the returned set?
I think you should re-think your DB schema.
But if you want an answer to keep working with you current schema:
DB::table('settings')->select('company_name')->first();
This can throw an Eloquent ModelNotFound exception.
EDIT
public function __construct()
{
$result = DB::table('settings')->select('company_name')->first()->toArray();
return View::share($result);
}

how to echo out data using findAllBySql in active record

This should return a list of about five locations. It returns nothing with no errors. I've tested the sql using mysql workbench. It returns the data just fine. Right now I'm writing the back end so I'm not concerned with using views or the dataprovider. I'm just making sure my back end functions work. So with that in mind, how would you return the data retrieved by findAllBySql?
class CashLogic
{
public function AllLocations()
{
$model = new Locations;
$allLocations = $model->findAllBySql("SELECT name from locations");
return $allLocations;
}
}
class SiteController extends Controller
{
public function actionIndex()
{
$model = new CashLogic;
$data = $model->AllLocations();
return $data;
}
}
The findAllBySql() method returns an array of models. From your code it seems you only want the names of locations. An alternative method is
$AllLocations=CHtml::listData(Locations::model()->findAll(),'name','name');
This will return an array of the form array('name'=>'name','name'=>'name'). A better solution would be to replace the first name with the primary key of your locations table.

Categories