how to create treeview in yii framework - php

I want to create a tree view which fetching
data from Database and after that
order it by parent field
So table fields are included :
product_category_id
product_category_parent_id
product_category_name
the record that is been mentioned
by name " product_category_parent_id"
is 0 without any root and when it wish have any
ID code / number , parent Id should come in this palce
so structure of the table must be sent to the
View :
<ul><li><ul><li></li></ul></li></ul>

There is an example how to create CTreeView
private function generateTree($models)
{
$data = array();
foreach ($models as $category) {
$data[$category->id] = array(
'id' => $category->id,
'text' => ''.$category->category_name.'',
);
foreach ($category->goods as $item) {
$data[$category->id]['children'][$item->id] = array(
'id' => $item->id,
'text' => ''.$item->article.'',
'expanded' => false,
);
}
}
return $data;
}
In view
$this->widget('CTreeView', array('data' => $data,'persist'=>'cookie'));

Related

How to form an object from a php array

I am trying to form my data to a specific formate. I have normal data coming from a query like this
[
{
category: "Business"
},
{
category: "Events"
},
{
category: "Vip Meetup"
}
]
I want to form above data using a foreach loop to bellow structure
[
'Business' => __( 'Business', 'plugin-domain' ),
'Events' => __( 'Events', 'plugin-domain' ),
'Vip Meetup' => __( 'Vip Meetup', 'plugin-domain' ),
];
How can I create a data structure like this?
Thank you in advance...
I suppose this should be somehting like:
$options = [];
foreach ($eventCats as $cat) {
// Add an element to array under key `$cat->category`
// Value of the element will be result of calling `__` function
$options[$cat->category] = __( $cat->category, 'plugin-domain');
}

Programmatically update Menu Item in Component in joomla

I'm creating a component in Joomla, where among other things, can create and update menus, and I have successfully used this answer to create a new menu item.
https://joomla.stackexchange.com/questions/5104/programmatically-add-menu-item-in-component?newreg=1e7c576205354c0795a55607bc3e2508
$menuTable = JTableNested::getInstance('Menu');
// which menu you want to add to -
$menutype = 'thisismymenusname';
// this is heading menu item but what data you have and require will vary per case - just look at an appropriate row in yr menu table
$menuData = array(
'menutype' => $menutype,
'title' => $table->alias,
'alias' => $table->alias,
'path' => $table->alias,
'type' => 'heading',
'component_id' => 0,
'language' => '*',
'published' => 1,
);
// this item is at the root so the parent id needs to be 1
$parent_id = 1;
$menuTable->setLocation($parent_id, 'last-child');
// save is the shortcut method for bind, check and store
if (!$menuTable->save($menuData))
{
$this->setError($menuTable->getError());
return false;
}
But I'm unable to find the correct way to update a menu item, like the title and alias. But it is unsuccessful. I have tried using this with no success.
$menu_title = $_POST['title'];
$menu_alias = JFilterOutput::stringURLSafe($menu_title);
$menuTable = JTableNested::getInstance('Menu');
// this is heading menu item but what data you have and require will vary per case - just look at an appropriate row in yr menu table
$menuData = array(
'title' => $menu_title,
'alias' => $menu_alias,
);
// this item is at the root so the parent id needs to be 1
$parent_id = ($_POST['parent'] != "" ? $_POST['parent'] : '1');
$menuTable->setLocation($parent_id, 'last-child');
// save is the shortcut method for bind, check and store
if (!$menuTable->set($_POST['menuid'],$menuData)) {
$this->setError($menuTable->getError());
exit;
}
Can anyone help?

laravel Insert or update related records

I'm having trouble updating and creating related records depending on if they exist or not. I want to update the ingredient if they exist, if not insert the ingredient into the database and relate it to the current meal.
public function update($id)
{
$meal = Meal::find($id);
$meal->name = Input::get('name');
// create ingredients
$ingredients = Input::get('ingredient');
$meal_ingredients = array();
foreach($ingredients as $ingredient)
{
$meal_ingredients[] = new Ingredient(array(
'name' => $ingredient['name'],
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}
//save into the DB
$meal->save();
$meal->ingredients()->saveMany($meal_ingredients);
// redirect
Flash::success('Votre repas a bien été mis à jour!');
return Redirect::to('/meals');
}
Step 1 : Get Meal
$meal = Meal::find($id);
Step 2 : Get Ingredients of Meal (create relation for this)
$ingredients = $meal->ingredients;
Step 3 : Compare Input to current and add does not exist
$new_ingredients = array();
foreach($ingredients as $ingredient)
{
if(!in_array($ingredient->toArray(), Input::get('ingredient')) {
$new_ingredients[] = new Ingredient(array(
'name' => $ingredient['name'],
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}
}
Step 4 Update
$meal->ingredients->saveMany($new_ingredients);
Ensure you got the relation between meal and ingredient correctly
You can use the firstOrNew() method. You pass it an array of data, and it will return the first record that matches that data, or if no record is found, a new instance of the class with the searched fields already set.
foreach($ingredients as $ingredient)
{
$meal_ingredients[] = Ingredient::firstOrNew(array(
'name' => $ingredient['name'],
))->fill(array(
'unit' => $ingredient['unit'],
'quantity' => $ingredient['quantity']
));
}

retrieving data from two tables into multidimensional array api json response

I am learning Api development where i want to retrieve data from two tables
First table (items) contains:
id, feed_id, title, author, content
Second table (feeds):
feed_id,title,url
I want to get Json response like:
{
- stories :
[
id
feed_id {
title,
url
}
title
author
]
}
My PHP function to retrieve story biased on id is like:
$app->get('/stories/:id', 'authenticate', function($story_id) {
$response = array();
$result = Database::get('db')->table('items')
->eq('rowid', $story_id)
->findOne();
//$response["error"] = false;
if ($result != NULL) {
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => $result["feed_id"],
'title' => $result["title"],
'isBreaking' => $result['isBreaking'],
'author' => $result['author'],
'updated' => $result["updated"],
'url' => $result['url'],
'content' => $result["content"]);
echoRespnse(200, $response);
}
else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The result i get is like:
{
- "stories": [
{
id
feed_id
title
url
}
]
}
How can i retrieve data from the second tablet (feeds) biased on feed_id and get the data into sub array?
as #MikeBrant mentioned you have to use join between two tables to retrieve correct data. the plain query will be something like this:
select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id
and then change your $response['stories'] like this:
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
'title' => $result["feed_title"],
'url' => $result["url"]
),
'title' => $result["title"],
.
.
.
);
you get the idea :)

Recursive table which child parent relationship

I have a problem with a recursive function that takes too many resources to display a child-parent relation in a dropdown list. For example:
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
I've written some code for a recursive call to the database each time, so that's the reason why my code takes so many resources to run.
Below is my code:
--call recursive
$tmp = $this->get_nav_by_parent(0);
$a_sel = array('' => '-Select-');
$a_sel_cat = array('home' => 'home');
$this->get_child_nav_cat($tmp, 0, $a_sel);
--
public function get_nav_by_parent($parent) {
$all_nav = $this->db
->select('id, title, parent')
->where('parent',$parent)
->order_by('position')
->get('navigation_links')
->result_array();
$a_tmp = array();
foreach($all_nav as $item)
{
if($parent != 0){
$item['title'] = '--' . $item['title'];
}
$a_tmp[] = $item;
}
return $a_tmp;
}
-- Recursive function
public function get_child_nav_cat($a_data, $parent, &$a_sel) {
foreach($a_data as $item) {
$a_sel[$item['page_slug_key']] = $item['title'];
$atmp = $this->get_nav_by_parent($item['id']);
$this->get_child_nav_cat($atmp, $item['id'], $a_sel);
}
return $a_sel;
}
Please give me suggestions for the best solution to display the data as child-parent relationship in select box.
Thanks in advance!
Best way to display parent child relationship is mentain parent and child flag in Database instead of
fetching value using loop.
In your case Home, Home 1 is parent flag and menus belong on child flag.
fetch data from db and your loop look like this:-
$arr = array(0 => array('name' => 'home','parent' => 0),
1 => array('name' => 'menu 1 ','parent' => 1),
2 => array('name' => 'menu 2 ','parent' => 1),
3 => array('name' => 'home 1','parent' => 0),
4 => array('name' => 'menu 3 ','parent' => 2),
5 => array('name' => 'menu 4','parent' => 2)
);
$dd_html = '<select>';
foreach($arr as $k => $v){
if($v['parent'] == 0 )
$dd_html .='<option>'.$v['name'].'</option>';
else
$dd_html .='<option>--'.$v['name'].'</option>';
}
$dd_html .= '</select>';
echo $dd_html;
Output :-
home
-menu 1
-menu 2
home 1
-menu 3
-menu 4
Set ParentID=0 for detecting root item
then execute this:
SELECT * FROM table ORDER BY ParentID, ID
Then iterate through result and when ParentID changed, create new level.

Categories