Algorithm to Save Items with Parent-Child Relationship to Database - recursion

I need help designing the logic of an app that I am working on.
The application should enable users to create mindmaps and save them to a mysql database for later editing.
Each mindmap is made up of inter-related nodes, meaning a node should have a parent node and the id of the mindmap to which it belongs.
I am stuck here. How can I save the nodes to the database and be able to query and rebuild the mindmap tree from the query results.
Root
Child1
Child2
GrandChild1
GreatGrandChild1
GreatGrandChild1
Child3
GrandChild2
I need an algorithm, that can save the nodes and also be able to figure out the relationships/order of items similar to the Tree that I have given. This is very much like how menus are saved and retrieved in Wordpress but I can't find the right logic to do this.
I know there are really great people here. Please help.

This is very easy in a 3 column table.
Column-1: id, Column-2: name, Column-3: parent_id
for example, the data would be like this:
1 ROOT NULL
2 Child1 1
3 Child2 1
... and so on..

I finally found a solution. Here's my full code.
require_once('config.php');//db conn
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$nav_query = MYSQL_QUERY("SELECT * FROM `nodes` ORDER BY `id`");
$tree = ""; // Clear the directory tree
$depth = 1; // Child level depth.
$top_level_on = 1; // What top-level category are we on?
$exclude = ARRAY(); // Define the exclusion array
ARRAY_PUSH($exclude, 0); // Put a starting value in it
WHILE ( $nav_row = MYSQL_FETCH_ARRAY($nav_query) )
{
$goOn = 1; // Resets variable to allow us to continue building out the tree.
FOR($x = 0; $x < COUNT($exclude); $x++ ) // Check to see if the new item has been used
{
IF ( $exclude[$x] == $nav_row['id'] )
{
$goOn = 0;
BREAK; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
}
}
IF ( $goOn == 1 )
{
$tree .= $nav_row['name'] . "<br>"; // Process the main tree node
ARRAY_PUSH($exclude, $nav_row['id']); // Add to the exclusion list
IF ( $nav_row['id'] < 6 )
{ $top_level_on = $nav_row['id']; }
$tree .= build_child($nav_row['id']); // Start the recursive function of building the child tree
}
}
FUNCTION build_child($oldID) // Recursive function to get all of the children...unlimited depth
{
$tempTree='<ul>';
GLOBAL $exclude, $depth; // Refer to the global array defined at the top of this script
$child_query = MYSQL_QUERY("SELECT * FROM `nodes` WHERE parent_id=" . $oldID);
WHILE ( $child = MYSQL_FETCH_ARRAY($child_query) )
{
IF ( $child['id'] != $child['parent_id'] )
{
FOR ( $c=0;$c<$depth;$c++ ) // Indent over so that there is distinction between levels
{ $tempTree .= " "; }
$tempTree .= "<li>" . $child['name'] . "</li>";
$depth++; // Incriment depth b/c we're building this child's child tree (complicated yet???)
$tempTree .= build_child($child['id']); // Add to the temporary local tree
$depth--; // Decrement depth b/c we're done building the child's child tree.
ARRAY_PUSH($exclude, $child['id']); // Add the item to the exclusion list
}
}
RETURN $tempTree.'</ul>'; // Return the entire child tree
}
ECHO $tree;
?>
This is based on the piece of code found here http://psoug.org/snippet/PHP-Recursive-function-to-generate-a-parentchild-tree_338.html I hope this helps someone as well

Related

wpallimport, run function 'dont_create_terms' only for specidied taxonomies

So, prefix that my coding level is practically equal to zero...
I'm using Wordpress with Wp All Import plugin, and i have this code to prevent wpallimport to create new categories/taxonomies etc.
function dont_create_terms( $term_into, $tx_name ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
Now, as specified in the title, i have to run this code only for certain taxonomies...
I have tried multiple solutions, for last i tried to add this line
if ($tx_name == 'taxonomyname') {
like here
function dont_create_terms( $term_into, $tx_name ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
if ($tx_name == 'taxonomyname') {
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
but everytime nothing appens.
Any help is really appreciated, thanks to everyone in advance
Edit:
Solution found
function dont_create_terms( $term_into ) {
// Check if term exists, checking both top-level and child
// taxonomy terms.
$term = empty($term_into['parent']) ? term_exists( $term_into['name'], $tx_name, 0 ) : term_exists( $term_into['name'], $tx_name, $term_into['parent'] );
if ( $tx_name == 'taxonomy_name' ){
// Don't allow WP All Import to create the term if it doesn't
// already exist.
if ( empty($term) and !is_wp_error($term) ) {
return false;
}
// If the term already exists assign it.
return $term_into;
}
add_filter( 'pmxi_single_category', 'dont_create_terms', 10, 2 );
And than call the function:
[dont_create_terms({yourxmldata[1]})]
Edit 2
It only works with single taxonomies, if the taxonomies contain multiple values it will not work
So again, if you have any suggestions you are welcome
The right way to do this would be writing your our custom function as shown here: https://www.wpallimport.com/documentation/code-snippets/#reference-taxonomy-terms-by-custom-id
However, although it is not elegant at all, I have found a different solution that could work for some, which involves wp-all-import's [foreach()] function.
It is not flexible as it requires that you add the max amount of values possible in your file (e.g 6 values tops in this example):
[foreach( {ParentNode/CategoryNode} )] {#id} > {Value1} |
{#id} > {Value[2]} | {#id} > {Value[3]} | {#id} > {Value[4]} |
{#id} > {Value[5]} | {#id} > {Value[6]} | [endforeach]
Where {ParentNode/CategoryNode} + #id + Value represent this portion of the xml file:
<ParentNode>
<CategoryNode id="this-cat-id">
<Value>Your value here</Value>
</CategoryNode>
</ParentNode>
Important: This will generate this error log while importing, every time it tries to import a value that does not exist, but the import will still work:
WARNING: It is necessary to assign a name to this term.
Important:
(1) In the import settings, you will need to go to 'Taxonomies, Categories, Tags', and select 'An element in my file contains the entire hierarchy...'.
(2) Then, check 'Separate hierarchy groups via symbol'.
(3) Do not check 'Only assign Your-cat-name-goes-here to the bottom level term in the hierarchy'
Here is how I set it up....
Screenshot WPAllImport
Hope this helps newcomers!

get count with hasMany not working yii2

I have CLub model (clubs) hasMany with User model like
Club n-n User
and I have UserClub model with columns: id, club_id, user_id, etc
In Club model
public function getCountUsers()
{
return $this->hasMany(UserClub::className(), ['club_id'=>'id'])->count();
}
I wanna count all User on Club as code:
$query = Club::find()
->joinWith(['countUsers']);
// ->with('countUsers');
->all();
so it is not working and throwing an error
Club has no relation named \"countUsers\"."
Because it isn't a relation as it does not return a model object or an array of model objects, instead you are using ->count() that makes it return a string that contains the total count for the user against the club.
If you are looking to get a count for the users against all the Clubs you can use the currently defined relation like $club->countUser see below.
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->countUser;
}
or change the relation to
public function getCountUser(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
and use it like
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->countUser);
}
or like below
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->getCountUser()->count();
}
EDIT
You are actually trying to transform the following query using ActiveRecord as far as I understood from the discussion.
SELECT clubs.id, count(user_clubs.id) as total
FROM
clubs
left join user_clubs on clubs.id = user_clubs.club_id
group by clubs.id
if that is correct you can use the following
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(uc.[[id]]) as total' ) ] )
->leftJoin ( '{{%user_clubs}} uc' , 'uc.club_id=c.id' )
->groupBy ( 'c.id' )
->all ();
Note : You have to do one more thing you have to add a public property $total inside your Club model and add it to safe rules, because you are selecting the count as an alias total and until unless you define it inside the model the result set won't show you the count, so add the following inside the Club model.
public $total;
under rules
[[other fields...,'total'] , 'safe' ] ,
EDIT2
For some reason, I have a feeling that you are trying to count by specifying a relation instead of specifying the ->leftJoin () with the table user_clubs in the query.
If that is so then you have to change your relation getUserCount() you should better give a meaningful name that describes it. i would rename it to getClubUsers()
public function getClubUsers(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
After this, you still have to declare a public property $total as I described before inside your Club model, and add it to safe rules.
Now you can write your query in the following way
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(cu.[[id]]) as total' ) ] )
->joinWith( ['clubUsers cu'] )
->groupBy ( 'c.id' )
->all ();
You can do this with join, in my case i get users who have more than 0 referrals.
$users = User::find()->with('referrals')
->from(User::tableName() . ' t')
->join('left join',User::tableName().' r','r.Deeplink = t.ReferralID')
->select('t.*,count(r.ID) as ct')
->groupBy('t.ID')
->andFilterHaving(['>','ct',0])
->all();
Hi your relation is correct check you error Club has no relation named \"countUsers\"."
Means you are calling a relation which not exist :
change query like this, Relation name should be in Club Model
public function getCount(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->getCount);
}
$query = Club::find()
->joinWith(['count']);
// ->with('countusers');
->all();
If you want count just do like this .
Load the Club model .
$club_model = Club::find()
$count = club_model->count;

Drupal: How to override a function from a contrib module

I am using a module that builds a price table for Drupal Commerce items. There is a function that formats the table headers:
/**
* Helper function that takes care of the quantity displayed in the headers of
* the price table.
*/
function commerce_price_table_display_quantity_headers($item) {
// Set the quantity text to unlimited if it's -1.
$max_qty = $item['max_qty'] == -1 ? t('Unlimited') : $item['max_qty'];
// If max and min qtys are the same, only show one.
if ($item['min_qty'] == $max_qty) {
$quantity_text = $item['min_qty'];
}
else {
$quantity_text = $item['min_qty'] . ' - ' . $max_qty;
}
return $quantity_text;
}
As you can see, this is not a theme function where I can override it in template.php but I can to tweak some of the output.
How can I redefine this function so I can chop and change a few things?
My work so far...
So far, I have tried to create it as a seperate module with a few subtle changes to show if it's working or not, but it's not overriding any of the output.
Info file
; $id$
name = Price Table: Tweaked Display
description = A different layout for the price table as shown on the product display nodes
package = Commerce (contrib)
core = 7.x
dependencies[] = commerce_product
dependencies[] = commerce_price
dependencies[] = commerce_price_table
Module File
/**
* Override of the helper function that takes care of the quantity displayed in the headers of
* the price table.
*/
function commerce_table_tweak_display_quantity_headers($item) {
// Set the quantity text to unlimited if it's -1.
$max_qty = $item['max_qty'] == -1 ? t('Unlimited gnhh') : $item['max_qty'];
// If max and min qtys are the same, only show one.
if ($item['min_qty'] == $max_qty) {
$quantity_text = $item['min_qty'];
}
else {
$quantity_text = $item['min_qty'] . ' - this is working - ' . $max_qty;
}
return $quantity_text;
}
Most drupal modules I believe have a hook_function (or at least ones that are hookable) I don't do this much so I would search the drupal api for how to hook functions and if your module will support it.

Drupal module_invoke() and i18n

I am tasked with i18n-ing our current CMS setup in Drupal.
The problem that I am facing is with use of module_invoke() to place blocks within nodes.
I have managed to string translate blocks, and that is working when a block is placed in a region (block content is successfully translated) using the UI.
However, when a block is injected into a node like such:
$block = module_invoke('block', 'block', 'view', 22); print $block['content'];
It is not getting translated, or even worse, not showing at all.
I have also tried this variation using t(). e.g.:
$block = module_invoke('block', 'block', 'view', 22); print t($block['content']);
to no avail.
Generally speaking I've having a bit of trouble with blocks for i18n. Does anyone have a recommended approach for dealing with blocks in drupal with regards to translating them? I would prefer not to create different blocks for each language.
So .. After digging around in the bowels of Drupal - and much hair pulling .. I've come up with an almost decent solution.
Basically, with this function, I can extract a translated version of a block:
function render_i18n_block($block_id, $region = "hidden"){
if ($list = block_list($region)) {
foreach ($list as $key => $block) {
// $key == <i>module</i>_<i>delta</i>
$key_str = "block_".$block_id;
if ($key_str == $key){
return theme('block', $block);
}
}
}
}
Then, in my node, I simple call:
<?php echo render_i18n_block(<block_id>,<region>); ?>
There can be some issues where your blocks might not be displaying in a region (and therefore you can't pass a region into block_list). For this case, I simply created a region called "hidden" which is not rendered anywhere in my template, but can be used to call block_list.
Finally (and this is the part that I still need to find a good solution for), I discovered that block_list() in: includes/blocks/block.inc has a bit of an issue.
It appears that $theme_key is not reliably set unless block_list() is being called from the theme() function (in includes/themes.inc) .. this causes the SQL to return an empty results set. The SQL looks like this:
$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (". db_placeholders($rids) .") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));
As you can see, if theme_key is not set, then it will just return an empty result.
For now I am bypassing this by simply adding:
if (!isset($theme_key)){$theme_key="<my_theme_name>";}
in modules/blocks/block.inc::block_list() around line 429 .. I still need to work out a better way to do this.
10 for anyone with suggestions on how I could ensure that $theme_key is set before calling block_list :)
I had exactly the same problem as you, since I was using
$block = module_invoke('block', 'block_view', 'block_id');
print render($block['content']);
to inject the block into my nodes. However, looking up module_invoke in the Drupal reference, I found a comment titled "to render blocks in Drupal 7 better to use Block API", with this code:
function block_render($module, $block_id) {
$block = block_load($module, $block_id);
$block_content = _block_render_blocks(array($block));
$build = _block_get_renderable_array($block_content);
$block_rendered = drupal_render($build);
return $block_rendered;
}
I just un-functioned it to use directly, like so:
$block = block_load('block', 'block_id');
$block_content = _block_render_blocks(array($block));
$build = _block_get_renderable_array($block_content);
print render($build);
And for me it works like a charm. Be aware however that this method prints the block title as well, so maybe you'll want to set it to 'none' in the original language.
Create a function like this
<?php
function stg_allcontent2($allC, $level
= "1") {
global $language; $lang = $language->language;
foreach ($allC as $acKey => $ac) {
if($ac['link']['options']['langcode']
== $lang){ if ($level == "1")
$toR .= "";
if (is_array($ac['below']))
$class="expanded"; else
$class="leaf";
$toR .= "<li class=\"".$class."\">" . l($ac['link']['link_title'], $ac['link']['link_path']) . "</li>";
if ($level != "1") $toR .= ""; if (is_array($ac['below'])) $toR .= "<ul class=\"menu\">".stg_allcontent2($ac['below'], "2")."</ul>"; if ($level == "1") $toR .= ""; }
}
return $toR; } ?>
call like this
<?php echo '<ul class="menu">'; echo stg_allcontent2(menu_tree_all_data($menu_name
= 'menu-header', $item = NULL)); echo '</ul>'; ?>
This may help you: http://drupal-translation.com/content/translating-block-contents#
UPDATE: the t() function allows you to pass in the language code to use.

WordPress loop by function

I'm creating magazine style theme (not e-commerce) and I want to display 3 latest posts from ex. X, Y and Z category, where this 1st post will be with thumb and other 2 only titles. I found some similar solution themes, but when I look into the code, they created 2 loop for each category (2x3=6) and with this 6 loops code looks very messy. So I decided to create function (ex. latest_post_from_category($cat);) to display this post.
Here comes the question is my decision right, if yes do have any advices to make this function more flexible?
Thanks for your time.
a function can become more flexible with params and switches. example follows
function getPosts($type,$return = false,$amount = 4)
{
switch($type)
{
case 'comments':
//Get latest comments here
break;
case 'posts':
case 'posts-desc':
case 'posts-asc':
if($type == 'posts-asc'){ $order = 'ASC';}else{$order = 'DESC';/*default*/}
//Get posts
break;
/*(etc...etc)*/
}
}
$comments = getPosts('comments',true,5); //5 comments
$posts= getPosts('posts-desc',true,6); //5 Latest
Things like that can really make a design come together.
The Thumbs
In regards to this you only really need the post id and wordpress provide the functions so with my example above you can loop and do an if statement
$i = 0;
foreach(getPosts('post-asc',true,3) as $row)
{
$i++;
if($i == 1)
{
//Show thumb for $row
if(!wct_display_thumb("width:200px;height:150px", $row->ID))
{
//Show title
}
}else
{
//Show title for $row!
}
}

Resources