foreach and query display laravel - foreach

I have a table with join, and group by, so i have multiple item in the table like:
namecat nameprod
1 a
1 b
1 c
2 a
2 a
2 c
I want to display in a select drop down menu, Since is a result from a query that i have in the $products variable, I passed the it to my view
return View::make('admin.view')->with('products',$products);
Then in my admin.view
#foreach ($products as $product)
{{Form::select('categorie', array(
$product-namecat => array($product->nameprod => $product-nomeprod)))
}}
#endforeach
like this i just get a lot of drop down for each category i have. how can i do to have a drop down menu with title in bold with namecat e.g. (1) and then all the product in 1. like this in laravel docs:
Generating A Grouped List
echo Form::select('animal', array(
'Cats' => array('leopard' => 'Leopard'),
'Dogs' => array('spaniel' => 'Spaniel'),
));
I try to use 2 foreach:
#foreach ($products as $product)
#foreach ($product->namecat as $category)
{{Form::select('categorie', array(
$category => array($product->nameprod => $product-nomeprod)))
}}
#endforeach
#endforeach
but it says Trying to get property of non-object (BTW i saw someone using that kind of build inside a foreach but there's no way i can $product->namecat work inside a foreach it says Invalid argument supplied for foreach() Why?)
Actually I have in mind (in a normal programming way) something like:
echo Form::select('animal', array(
foreach ($product->nomecat as $cat)
$cat => array( foreach ($product->nameprod as $prod)
$prod => $prod
endforeach),
endforeach));

i assume your $products array looks something like
$products = [
(object) ['namecat' => 1, 'nameprod' => 'a'],
(object) ['namecat' => 1, 'nameprod' => 'b'],
(object) ['namecat' => 2, 'nameprod' => 'a'],
(object) ['namecat' => 2, 'nameprod' => 'b'],
// ...
]
for a grouped list with that $products array to work, you'd need some tweaking. an easy way would be bringing a new variable $categories into the game, that you can fill in your controller for instance.
$categories = [];
foreach ($products as $product) {
if (!isset($categories[$product->namecat])) {
$categories[$product->namecat] = [];
}
array_push($categories[$product->namecat], $product->nameprod);
}
View::make('leView')->with('categories' => $categories);
within the view:
so since $categories looks like this:
$categories[1] => ['a', 'b']
$categories[2] => ['a', 'b']
you should be able to use the Form::select
{{ Form::select('category', $categories) }}

Related

Opencart custom page foreach not showing

Am creating a custom page using Opencart. Here am using foreach for displaying customer details.
But customer details not showing.
Following codes:
.tpl
<?php foreach($dealerData as $invoice){ ?>
<label> <b>Dealer Name:</b> <?php echo $invoice['name']; ?></label><br>
<label><b>Dealer TIN Number:</b> <?php echo $invoice['tin_number'];?></label><br>
<?php } ?>
Controller
$query13 = $this->db->query("select concat(firstname, ' ', lastname) as name, tin_number from ".DB_PREFIX."customer where customer_id='".$customer_id."'");
$dataDelar = $query13->rows;
foreach ($dataDelar as $dealer) {
$data['dealerData'][] = array(
'name' => $dealer['name'],
'tin_number' => $dealer['tin_number']
);
}
Why are you putting queries in your controller? You have models van database related functions. An foreach on the variable $invoiceData1 should work, you can see in the print_r that there is 1 array in the array. Did you put the print_r in your controller? So yes, look bellow that, maybe you are overriding $invoiceData1.
EDIT
You are not creating an empty array to put your values in:
$query13 = $this->db->query("select concat(firstname, ' ', lastname) as name, tin_number from ".DB_PREFIX."customer where customer_id='".$customer_id."'");
$dataDelar = $query13->rows;
$data['dealerData'] = [];
foreach ($dataDelar as $dealer) {
$data['dealerData'][] = array(
'name' => $dealer['name'],
'tin_number' => $dealer['tin_number']
);
}

Yii2 join 6 tables + dropdown filter in grid

I have the following tables/models: A, B, C, BC, D, BCD
(A:B 1:N) Connecting table D to BCD would be no problem. However I would like to filter key attributes as dropdown from A, B, C and D to find results in BCD (because in the end I need BCDid). In BCD next to BCid and Did I can store of course Aid, Bid and Cid, and it would seem to me quite an easy workaround, however I know it's totally against db normalisation. Is there another, better way (with eager loading of course)?
I've now this in BCD:
public function getB() {
return $this->hasOne(\app\models\B::className(), ['id' => 'Bid'])
->via('BC');
}
and it seems to work, but it's not eager loading.
And how do I get to model A? can I define it like this in BCD?:
public function getA() {
return $this->hasOne(\app\models\A::className(), ['id' => 'Aid'])
->via('BC')
->via(B);
}
It doesn't really work yet.
This way it works (BCSearch):
public function search($params) {
$query = BC::find()->joinWith('A', true)->joinWith('C', true);
Relation A in BC defined with "via". Dropdown filter also works.
But I still don't know how to achieve one more level deep into db structure.
This way it seems to work fully:
models/BCDSearch.php
public function search($params) {
$query = BCD::find()
->select([
'BCD.id',
'BCD.amount',
'A.id AS A_Id',
'A.name AS A_name',
'B.name AS B_name',
'B.name2 AS B_name2',
'C.name AS C_name',
'D.name AS D_name',
])
->leftJoin('BC', 'BC.id = BC_Id')
->leftJoin('B', 'B.id = B_Id')
->leftJoin('A', 'A.id = A_Id')
->leftJoin('C', 'C.id = C_Id')
->leftJoin('D', 'D.id = D_Id');
$query->andFilterWhere([
...
'A.id' => $this->A_Id,
'B.name' => $this->B_name,
'B.name2' => $this->B_name2,
'C.name' => $this->C_name,
'D.name' => $this->D_name,
]);
public function rules() {
return [
...
[[... 'A_Id', 'B_name', 'B_name2', 'C_name', 'D_name'], 'safe'],
];
}
models/base/BCD.php:
class BCD extends Whatever {
public $A_Id;
public $A_name;
public $B_name;
public $B_name2;
public $C_name;
public $D_name;
views/BCD/index.php:
GridView::widget([
'layout' => '{summary}{pager}{items}{pager}',
'dataProvider' => $dataProvider,
'pager' => [
'class' => yii\widgets\LinkPager::className(),
'firstPageLabel' => Yii::t('app', 'First'),
'lastPageLabel' => Yii::t('app', 'Last')],
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'A_Id',
'value' => 'A_name',
'filter' => yii\helpers\ArrayHelper::map(app\models\A::find()->all(), 'id', 'name')
],
[
'attribute' => 'B_name',
'value' => 'B_name',
'filter' => yii\helpers\ArrayHelper::map([['id' => 'name1', 'name' => 'name1'], ['id' => 'name2', 'name' => 'name2']], 'id', 'name')
],
[
'attribute' => 'B_name2',
'value' => 'B_name2',
'filter' => yii\helpers\ArrayHelper::map([['id' => 'name2_1', 'name' => 'name2_1'], ['id' => 'name2_2', 'name' => 'name2_2']], 'id', 'name')
],
[
'attribute' => 'C_name',
'value' => 'C_name',
'filter' => yii\helpers\ArrayHelper::map(app\models\C::find()->all(), 'C_name', 'C_name')
],
[
'attribute' => 'D_name',
'value' => 'D_name',
'filter' => yii\helpers\ArrayHelper::map(app\models\D::find()->all(), 'D_name', 'D_name')
],
'amount',
...
hope this helps others. It was not easy to figure out (at least for me) this basically easy solution. I don't know why but so far I couldn't find any relevant info on the web like this.

Create an array with hash Ruby on Rails 4

I am new at Ruby and Rails and I'm trying to create an array like this:
#data =[
{
order => {key => value, key1 => value1},
folder => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}},
document => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}}
},
{
order => {key => value, key1 => value1},
folder => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}},
document => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}}
},
]
I have 3 tables, Order, Folder and Document. I have to make a find in Order with certain condition and is going to retrieve some records.
If the find in Order retrieve 3(can be any number) records then I have to make 3 find in Folders and the condition is the Order.id.
Then I have to make a find in Document and the condition is the last Folder.id, this can retrieve many records.
So, I wanna make this so i can send #data to the view and make some foreach for show all the necessary information.
EDIT:
Mudasobwa this is what I try:
Order.where(conditions).find_each do |order|
logger.debug(order.id) #first log
Folder.where(condition order.id).find_each do |folder|
logger.debug(folder.id) #second log
end
Document.where(folder.id).find_each do |doc|
logger.debug(doc.id) #third log
end
end
With this I am getting the info that I want. 1 order.id then all the folders related with that order.id and all the document related with the last folder.id but I dont know how to create the #data array with all this info, how to join everything.

Zend2: Creating a radio button list with extra information?

So far I have this:
$radio = new Element\Radio('gender');
$radio->setLabel('What is your gender ?');
$radio->setValueOptions(array(
array(
'0' => 'Female',
'1' => 'Male',
)
));
The problem is, I want a table output like this:
Gender | Description | Button
-------------------------------
Male | The workers | [X]
Female | The peacekeepers | [ ]
So the problem is that I want to associate more information to the individual form elements and alter the standard way the get printed to the screen. If something like this could work, I would be pretty happy:
$radio = new Element\Radio('gender');
$radio->setLabel('What is your gender ?');
$radio->setValueOptions(array(
array(
'0' => 'Female',
'1' => 'Male',
)
));
$radio->setExtraData(array(
array(
'0' => 'The workers',
'1' => 'The peacekeepers',
)
));
That obviously doesn't work. So what is the correct "zend" way to accomplish this?
Instead of providing a plain array, you could add extra information in the value options like this:
$radio->setValueOptions(array(
array(
'value' => '0',
'label' => 'Female',
'description' => 'The peacekeepers',
),
array(
'value' => '1',
'label' => 'Male',
'description' => 'The workers',
)
));
The following step would be to create a custom View Helper for rendering the table, or loop through the options and render the table in the view itself.

How to store the choice array_keys as values when using sfWidgetFormChoice when multiple equals true

Here’s my widget in the Form.Class:
$this->widgetSchema['schools'] = new sfWidgetFormChoice(array(
'choices' => Doctrine_Core::getTable('school')->getUsersSchools($userId),
'renderer_class' => 'sfWidgetFormSelectDoubleList',
'renderer_options' => array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
)));
The above works just fine, but the values that are stored are unassociated to the choices list referenced above. I need to store the ids of the array retrieved as the values. Instead, the list that is retrieved is chronological and the ids are ignored.
Here's the schoolTable query:
public function getUsersSchools($id){
$q =Doctrine_Query::create()
->select('id')
->from('school')
->where('user_id = ?', $id)
->execute();
return $q;
}
If I understand your question correctly you would like to store associated school ids.
Use the sfWidgetFormDoctrineChoice widget instead and it will work out of the box, as it using primary keys as ids.
$query = Doctrine_Core::getTable('school')->queryForSelect($userId);
$this->setWidget('schools', new sfWidgetFormDoctrineChoice(array(
'model' => 'school',
'query' => $query,
'multiple' => true,
'renderer_class' => 'sfWidgetFormSelectDoubleList',
'renderer_options' => array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
),
)));
$this->setValidator('schools', new sfValidatorDoctrineChoice(array(
'model' => 'schoool',
'query' => $query,
'multiple' => true,
)));
// in SchoolTable class
public function queryForSelect($userId)
{
return $this->createQuery('s')
->andWhere('s.user_id = ?', $userId)
;
}
If you has a proper schema (I presume the schools should be a many-to-many association), then the current from should has a schools_list field (properly defined in the generated base from) and then you can modify that field to be rendered by sfWidgetFormSelectDoubleList:
$this->widgetSchema['schools_list']->setOption('renderer_class', 'sfWidgetFormSelectDoubleList');
$this->widgetSchema['schools_list']->setOption('renderer_options', array(
'label_unassociated' => 'Unassociated',
'label_associated' => 'Associated'
));

Resources