I have created a component in joomla 2.5 that creates a new article and adds that article to a menu item.
Creating the article is working fine, but I am having some trouble with creating the menu item.
I have the following code:
//add the article to a menu item
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuData = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => '1',
'level' => 1,
);
// Bind data
if (!$menuTable->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$menuTable->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$menuTable->store())
{
$this->setError($menuTable->getError());
return false;
}
The error seems to be with setting the parent_id and level. On debugging libraries/joomla/database/tablenested.php sets the parent_id and level to 0. This caused the following error on my administrator page:
Warning: str_repeat() [function.str-repeat]: Second argument has to be greater than or equal to 0 in /Applications/MAMP/htdocs/joomla_2_5/administrator/components/com_menus/views/items/tmpl/default.php on line 129
Try using JTableNested::setLocation($referenceId, $position = 'after'):
$table->setLocation($parent_id, 'last-child');
I also think that you need to rebuild the path:
// Rebuild the tree path.
if (!$table->rebuildPath($table->id)) {
$this->setError($table->getError());
return false;
}
If it still doesn't work, try to find out what MenusModelItem::save does that you don't.
$table->setLocation($parent_id, 'last-child');
is all that is needed to ensure that left/right values are created correctly for the new menu item. There is no need to rebuild the path as this is now handled by JTableMenu's store method.
Additionally, the convenience method "save" can be used to bind, check and store the menu item:
$menuItem = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => $parent_id,
'level' => 1,
);
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuTable->setLocation($parent_id, 'last-child');
if (!$menuTable->save($menuItem)) {
throw new Exception($menuTable->getError());
return false;
}
Somehow $menutable does not update parent_id and level in database table so you have to manually update those two fields by joomla query.
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuData = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => '1',
'level' => 1,
);
// Bind data
if (!$menuTable->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$menuTable->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$menuTable->store())
{
$this->setError($menuTable->getError());
return false;
}
$db = $this->getDbo();
$qry = "UPDATE `#__menu` SET `parent_id` = 1 , `level` = 1 WHERE `id` = ".$menuTable->id;
$db->setQuery($qry);
$db->query();
This code worked for me
JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/com_menus/tables/');
$menuTable =& JTable::getInstance('menu', 'menusTable');
$menuData = array(
'menutype' => 'client-pages',
'title' => 'mytrialmenu',
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=index.php? option='com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => 'choose some parent',
'level' => 1,
);
// Bind data
if (!$row->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$row->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$row->store())
{
$this->setError($menuTable->getError());
return false;
}
I think the reason is menusTable extends JnestedTable which is required for manipulating lft and rgt fields in the menu table
Related
I'm currently developing this code that traverse a hierarchical array which should compute the sub-total of a property called cur_compensation. My issue is that the changes I do is not getting save
private function computeSubTotal($hierarchy){
foreach($hierarchy["_children"] as $key => $value){
if(isset($value["_children"]))
{
static::computeSubTotal($value);
}
else{
foreach($hierarchy["_children"] as $employee){
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
return $hierarchy;
}
}
return $hierarchy;
}
This is the function so what it does it goes to the deepest node, the deepest node is a value that does not have any _children which mean it doesn't have any sub department (the hierarchy is sorted that the sub department are always on top)
The issue I have, once it reaches the bottom it computes the cur_compensation by looping through the employees of that department and adding it on the department "cur_compensation" property.
The issue is that, it doesn't save any of my changes.
So the purpose of the function is to add up the 'cur_compensation' of each employee/sub-department.
For example ->
$rows = array(
array(
'name' => "Main",
'id' => 1,
'parent_id' => 0,
'cur_compensation' => 0,
'_children' => array(
array(
'name' => "Dept A",
'id' => 2,
'parent_id' => 1),
),
array(
'name' => "Dept B",
'id' => 3,
'parent_id' => 1,
'_children' => array(
array(
'name' => "Dept C",
'cur_compensation' => 30000,
'id' => 4,
'parent_id' => 3),
array(
'name' => "Employee C",
'cur_compensation' => 30000,
'id' => 7,
'parent_id' => 3
)
)),
array(
'name' => "Employee A",
'cur_compensation' => 20000,
'id' => 5,
'parent_id' => 1
),
array(
'name' => "Employee B",
'cur_compensation' => 30000,
'id' => 6,
'parent_id' => 1
)
)
)
);
The result I want to get would be:
$rows = array(
array(
'name' => "Main",
'id' => 1,
'parent_id' => 0,
'cur_compensation' => 120000,
'_children' => array(
array(
'name' => "Dept A",
'id' => 2,
'cur_compensation' => 0,
'parent_id' => 1),
),
array(
'name' => "Dept B",
'id' => 3,
'parent_id' => 1,
'cur_compensation' => 60000,
'_children' => array(
array(
'name' => "Dept C",
'cur_compensation' => 30000,
'id' => 4,
'parent_id' => 3),
array(
'name' => "Employee C",
'cur_compensation' => 30000,
'id' => 7,
'parent_id' => 3
)
)),
array(
'name' => "Employee A",
'cur_compensation' => 30000,
'id' => 5,
'parent_id' => 1
),
array(
'name' => "Employee B",
'cur_compensation' => 30000,
'id' => 6,
'parent_id' => 1
)
)
)
);
So you would notice that Main and Dept B got the cur_compensation based on the _children property
There's a few things to make note on here - so I'm going to add comments to your existing code, then provide an example of how you could change it.
(I've formatted the code in each case)
class Example {
// filler code so that we can call
public function process($array){
return $this->computeSubTotal($array);
}
private function computeSubTotal($hierarchy) {
// we're not checking whether "_children" property exists before looping on it
foreach ($hierarchy["_children"] as $key => $value) {
if (isset($value["_children"])) {
// we're calling the method, but not doing anything with the return value.
static::computeSubTotal($value);
// we can set the original array value instead which will provide a modified copy
// this can be resolved by uncommenting the line below
// $hierarchy["_children"][$key] = static::computeSubTotal($value);
// also note that if this "child" doesn't have any *grand*children
// then we won't get an updated value due to how this is structured
// to fix this, you could remove the else wrapping so that the code
// below runs always
} else {
// double looping - we're already looping this array
// this will cause the end value to increase exponentially
foreach ($hierarchy["_children"] as $employee) {
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
// returning whole array inside the loop is not ideal
// we have already adjusted the main array
// comment out this return to prevent that from happening
return $hierarchy;
}
}
return $hierarchy;
}
}
$example = new Example;
// calling this on $rows won't give us anything back
// since $rows doesn't contain the property "_children"
$rows = $example->process($rows);
// in this case, you would want to process each array result
// only on this primary array
foreach($rows as $index => $value){
$rows[$index] = $example->process($value);
}
echo json_encode($rows, JSON_PRETTY_PRINT);
Taking those comments into account, you would end up with something like this:
private function computeSubTotal($hierarchy) {
// we're not checking whether "_children" property exists before looping on it
foreach ($hierarchy["_children"] as $key => $value) {
if (isset($value["_children"])) {
$hierarchy["_children"][$key] = static::computeSubTotal($value);
}
// double looping - we're already looping this array
// this will cause the end value to increase exponentially
foreach ($hierarchy["_children"] as $employee) {
$employee_cur_compensation = $employee["cur_compensation"] ?? 0;
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
$hierarchy["cur_compensation"] += $employee_cur_compensation;
}
}
return $hierarchy;
}
That's closer but still, it's not quite correct due to the double looping.
I've made a simpler version that is hopefully easy to follow:
private function computeSubTotal($hierarchy) {
if (!isset($hierarchy["_children"])) {
return $hierarchy;
}
// define this outside the loop for clarity
if (!isset($hierarchy["cur_compensation"])) {
$hierarchy["cur_compensation"] = 0;
}
foreach ($hierarchy["_children"] as $key => $value) {
// don't need to check for "_children" property
// as it's now handled in this function
$updated = static::computeSubTotal($value);
// reference the $updated array to increment
// the "cur_compensation" field
$hierarchy["cur_compensation"] += $updated["cur_compensation"] ?? 0;
// update original array
$hierarchy["_children"][$key] = $updated;
}
return $hierarchy;
}
// call like
foreach ($rows as $index => $value) {
$rows[$index] = static::computeSubTotal($value);
}
You will still need to change how you're passing the $rows variable due to it now containing a "_children" property (as shown in the examples) - either pass each element or add additional logic in that function to handle that.
You need to pass the array as a reference.
https://www.php.net/manual/en/language.references.pass.php
PHP passes the array to the function as a pointer, but when you try to update the array, PHP first makes a full copy of the array and updates the copy instead of the original.
Change your function signature to the following and it should be good.
private function computeSubTotal(&$hierarchy){
P.S. You are calling computeSubTotal statically, but the function is not static itself.
I have a hierarchical array in my project like this:
$Array = array(
array(
'Id' => 1,
'Title' => 'Some Text1',
'Children' => array(
array(
'Id' => 11,
'Title' => 'Some Text11',
'Children' => array(
array(
'Id' => 111,
'Title' => 'Some Text111',
),
array(
'Id' => 112,
'Title' => 'Some Text112',
'Children' => array(
array(
'Id' => 1121,
'Title' => 'Some Text1121',
)
)
)
)
),
array(
'Id' => 12,
'Title' => 'Some Text12',
'Children' => array(
array(
'Id' => 121,
'Title' => 'Some Text121',
)
)
)
)
),
array(
'Id' => 2,
'Title' => 'Some Text2',
)
);
I want to search my string (such as 'Some Text1121') in 'Title' index in this array and return it's path such as after search 'Some Text1121' I want to return this result:
"1 -> 11 -> 112 -> 1121"
Or when I Search 'Some' string, return all path in array.
please help me, thanks.
I've quickly written you something. It's not perfect, but you get the idea:
<?php
function searchRec($haystack, $needle, $pathId = Array(), $pathIndex = Array()) {
foreach($haystack as $index => $item) {
// add the current path to pathId-array
$pathId[] = $item['Id'];
// add the current index to pathIndex-array
$pathIndex[] = $index;
// check if we have a match
if($item['Title'] == $needle) {
// return the match
$returnObject = new stdClass();
// the current item where we have the match
$returnObject->match = $item;
// path of Id's (1, 11, 112, 1121)
$returnObject->pathId = $pathId;
// path of indexes (0,0,1,..) - you might need this to access the item directly
$returnObject->pathIndex = $pathIndex;
return $returnObject;
}
if(isset($item['Children']) && count($item['Children']>0)) {
// if this item has children, we call the same function (recursively)
// again to search inside those children:
$result = searchRec($item['Children'], $needle, $pathId, $pathIndex);
if($result) {
// if that search was successful, return the match-object
return $result;
}
}
}
return false;
}
// useage:
$result = searchRec($Array, "Some Text11");
var_dump($result);
// use
echo implode(" -> ", $result->pathId);
// to get your desired 1 -> 11 -> 112
EDIT: rewritten to make the function actually return something. It now returns an Object with the matching item, the path of Id's and the path of (array-) Indexes.
I am working on populating the database tables. The table have fields which some of them are enum.
Consider a user which have a field status , whose values can be active, inactive etc. Assume we can modify the configuration values and running the script the data can be populated accordingly.
Let us represent the user table whose status field as
'status' => array(
'active' => 3,
'inactive',
'deleted',
),
In this case assume we need to create 3 users with status , active. 1 user with status inactive and 1 with deleted.
The table may be having more enum fields. So the config can expand. Depending on the configuration and fields the values will be multiples.
Consider the below example.
Eg :
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
In this case there need to populate table1 whose field field1 with active, inactive, deleted and roles with admin, user, editor etc. ( The active, inactive etc are provided just for example. It can be just values. )
The idea is to generate more users depending on the count if any provided.
Eg :
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
)
....,
'more-fields' => array(
'more-values',
)
So that there will be
10 * 4 => active users (10 * 2 active admin / 10 active user, 10 active editor ) +
2 * 4 => inactive users ( 2 inactive admin , 1 user, 1 editor ) +
3 * 4 => deleted users in total.
I am struggling to build the algorithm for the same.
array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
)
// In this example you can see we have not covered the fields of the table when they are more than 1 on save.It looks we need to build the array with values first.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
} else {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
}
}
}
}
}
UPDATE :
Changes made according to #the-fourth-bird answer https://stackoverflow.com/a/33354032/487878
Problem is it only look for 2 fields, the fields can be 1 or n.
Are you looking for a setup like this? (Not sure what the fields for the User can be, I used 'role' and 'admin' in this example.)
$fields = array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin',
'user',
'editor'
)
);
$roles = $fields['roles'];
$statuses = $fields['status'];
foreach ($roles as $role) {
foreach ($statuses as $status => $statusCount) {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->role = $role;
$model->status = $status;
}
}
}
// Update with dynamic properties
<?php
class table1name {
public function save() {}
}
class table2name {
public function save() {}
}
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user' => 2,
'editor'
),
'more-fields' => array(
'more-values' => 2,
),
'color' => array(
'blue' => 2,
'red'
),
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
// Adjust data structure
// If the key is a string, turn the key into values for the given multiplier in the same array.
// Then unset the key.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
for ($i = 0; $i< $statusCount; $i++) {
$config[$table][$field][] = $key;
}
unset($config[$table][$field][(string)$key]);
}
}
}
}
$cartesians = [];
// If you want all the possible combinations for for example the 'table1name', you need a cartesian product. Used the function from this page:
//http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays
function cartesian($input) {
$input = array_filter($input);
$result = array(array());
foreach ($input as $key => $values) {
$append = array();
foreach($result as $product) {
foreach($values as $item) {
$product[$key] = $item;
$append[] = $product;
}
}
$result = $append;
}
return $result;
}
// Create the cartesian products for all the keys in the $config array.
foreach ($config as $key => $tables) {
$cartesians[$key] = cartesian($tables);
}
// Loop all the objects created by the cartesian function.
foreach ($cartesians as $objectName => $cartesian) {
foreach($cartesian as $key => $value) {
$model = new $objectName();
$model->$key = $value;
$model->save();
}
}
I can only add one item to my cart at a time.
The previous item I add to the cart will just get replaced here is my method I use:
public function addcart(){
if(isset($this->session->userdata)){
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('title'=> $this->input->post('title')));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0){
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
check what $cart['product'] = $this->cart->contents(); returns to you
if there is a problem there it probably reset your array of products and then you insert the second product and get a total cart of one product
I think you are using $this->db->get() badly, you are searching product by string, which is not "correct". What happens if you have same (title) identical products? You get the first one/second one?
please adjust your table as follows
id, title, price... 'custom fields', active
make id as autoincrement, active as boolean (so you can later turn on/off product)
Make your method accept parameters:
public function addcart( $id = FALSE ) {
if ($id === FALSE || !is_numeric($id)) {
//wrong ID do nothing or throw alert or inform user about it
redirect('');
}
if(isset($this->session->userdata)) {
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('id' => $id, 'active' => '1'));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0) {
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
Happy cod(e)igniting.
I have a MySQL database in this format :
table name : btree_mst
fields : id, parent_id, left_node_id, right_node_id, user_name
Now what I have to do is print it in the Un-ordered list format like below
Root Node
Node A
Node A Left
Node A Right
Node B
Node B Left
Node B Right
I tried to make a recursive function for that but didn't work as expected.
Any suggestions ?
Here is the Code I made, http://pastebin.com/X15qAKaA
The only bug in this code is, it is printing UL every time. It should print only when the Level is changed.
Thanks in advance.
If you do not have ordered list in your DB, recursion is suitable.
class A
{
private $a = array(
array(
'id' => 1,
'parent_id' => 0,
'title' => 'ROOT'
),
array(
'id' => 2,
'parent_id' => 1,
'title' => 'A'
),
array(
'id' => 3,
'parent_id' => 1,
'title' => 'B'
),
array(
'id' => 4,
'parent_id' => 2,
'title' => 'A left'
)
);//your database values
public function buildTree()
{
$aNodes = array();
$iRootId = 1;//your root id
foreach ($this->a AS $iK => $aV)
{
if($aV['id'] == $iRootId)
{
unset($this->a[$iK]);
$aNodes[$aV['id']] = $aV;
$aNodes[$aV['id']]['childs'] = $this->getChilds($aV['id']);
}
}
print_r($aNodes);//print tree
}
private function getChilds($iParentId)
{
$aChilds = array();
foreach ($this->a AS $iK => $aV)
{
if($aV['parent_id'] == $iParentId)
{
unset($this->a[$iK]);
$aChilds[$aV['id']] = $aV;
$aChilds[$aV['id']]['childs'] = $this->getChilds($aV['id']);
}
}
return $aChilds;
}
}
$o = new A();
$o->buildTree();