This blog is somewhat related to my previous post but with bit easy implementation and more generic. We have encountered this implementation multiple time so thought of sharing it with all.
Ever thought of replicating this feature in any of your custom object?
Now the only complication is, in case of self lookup you don't know the end node and where your loop should stop (to think about the logic). So hope I will make it easy for you.
*Note : My blog code formatter is not working properly, so please check the spaces before using the code.
Step 1 : Create an apex class called HierarchyController, as shown below and save it.
Step 1 : Create an apex class called HierarchyController, as shown below and save it.
public with sharing class DynamicHierarchyForBlogController { public String objectApiName {get;set;} public String fieldApiName {get;set;} public String nameField {get;set;} public String currentsObjectId {get;set;} public String topParentId {get;set;} public String jsonMapsObjectString {get;set;} private String jsonString; private Map> sObjectIdMap ; private Map selectedsObjectMap ; private Map allsObjectMap; public DynamicHierarchyForBlogController() { currentsObjectId = Apexpages.currentPage().getParameters().get('id'); sObjectIdMap = new Map >(); selectedsObjectMap = new Map (); allsObjectMap = new Map (); } public String getjsonMapString() { retrieveInfo(); return jsonString; } public void retrieveInfo() { String dynamicQuery = 'SELECT ID ,' + fieldApiName + ' , ' + nameField + ' FROM ' + objectApiName + ' ORDER BY ' + fieldApiName + ' LIMIT 50000'; for(sObject obj: Database.query(dynamicQuery)) { allsObjectMap.put(obj.id,obj); } if(currentsObjectId != null) { String dQuery = 'SELECT ID FROM ' + objectApiName + ' WHERE id =\'' + currentsObjectId +'\''; List objList = Database.query(dQuery); currentsObjectId = objList[0].Id; retrieveTopParent(currentsObjectId); retrieveAllChildRecords(new Set {topParentId}); for(String str : sObjectIdMap.keySet()) { selectedsObjectMap.put(str,allsObjectMap.get(str)); } jsonString = JSON.serialize(sObjectIdMap); jsonMapsObjectString = JSON.serialize(selectedsObjectMap); } } public void retrieveTopParent(String sObjectId) { if(allsObjectMap.keySet().contains(sObjectId) && allsObjectMap.get(sObjectId).get(fieldApiName) != null) { topParentId = String.valueOf(allsObjectMap.get(sObjectId).get(fieldApiName)); retrieveTopParent(topParentId); } } public void retrieveAllChildRecords(Set sObjectIdSet) { if(sObjectIdSet.size() > 0) { Set allChildsIdSet = new Set (); for(String str : sObjectIdSet) { Set childsObjectIdSet = new Set (); for(sObject obj : allsObjectMap.values()) { if(obj.get(fieldApiName) != null && String.valueOf(obj.get(fieldApiName)) == str) { childsObjectIdSet.add(obj.Id); allChildsIdSet.add(obj.Id); } } sObjectIdMap.put(str,childsObjectIdSet); } retrieveAllChildRecords(allChildsIdSet); } } }
Step 2 : Now create a component called Hierarchy, as shown below and save it.
<apex:component controller="DynamicHierarchyForBlogController"> <apex:attribute name="objectName" description="Name of Object." type="String" required="true" assignTo="{!objectApiName}"/> <apex:attribute name="FieldName" description="Name of the field of the object." type="String" required="true" assignTo="{!fieldApiName}"/> <apex:attribute name="RepersenterField" description="Name field of the object." type="String" required="true" assignTo="{!nameField}"/> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div id="parentDiv"></div> <style> #parentDiv ul:first-child { padding: 0; } #parentDiv li { list-style: none; padding: 10px 5px 0 5px; position: relative; } #parentDiv li span { -moz-border-radius: 5px; -webkit-border-radius: 5px; /*border: 1px solid #999;*/ border-radius: 5px; display: inline-block; padding: 3px 8px; cursor: pointer; } .selectedRecord { font-weight:bold; color:blue; } </style> <script> var accountMap = JSON.parse('{!jsonMapString}'); var accountValueMap = JSON.parse('{!jsonMapsobjectString}'); var cClass = ''; if("{!topParentId}".indexOf('{!$CurrentPage.parameters.id}') != -1) cClass = 'selectedRecord'; var ul = '<ul><li id="{!topParentId}" ><span class="' + cClass + '" onclick="toggleChilds(\'' + '{!topParentId}' + '\',event)" ><b id="i{!topParentId}" class="minus" style="font-size: 1.5em;" >-</b> ' + accountValueMap['{!topParentId}'].{!RepersenterField} + '</span></li></ul>' ; $(ul).appendTo("#parentDiv"); appendUl('{!topParentId}','{!topParentId}'); function appendUl(key) { $.each( accountMap[key], function( index, value ) { var dclass = ''; if(value.indexOf('{!$CurrentPage.parameters.id}') != -1) dclass = 'selectedRecord'; var ul = '<ul class="' + key + '"><li id="' + value + '" ><span class="' + dclass + '" onclick="toggleChilds(\'' + value + '\',event)" ><b id="i' + value + '" class="minus" style="font-size: 1.5em;" >-</b> ' + accountValueMap[value].{!RepersenterField} + "</span></li></ul>" ; $(ul).appendTo("#" + key); if(value) appendUl(value); }); } function toggleChilds(key,event) { $('.'+key).toggle('slow'); $('#i'+key).toggleClass('minus'); $('#i'+key).toggleClass('plus'); if($('#i'+key).hasClass("minus")) $('#i'+key).html("-"); if($('#i'+key).hasClass("plus")) $('#i'+key).html("+"); event.stopPropagation(); } </script> </apex:component>
Step 3 : Now create a visualforce page, as shown below.
<apex:page standardcontroller="Account" showHeader="true" sidebar="true"> <apex:pageblock title="Hierarchy"> <c:DynamicHierarchyForBlog objectName="Account" FieldName="ParentId" RepersenterField="Name"/> </apex:pageblock> </apex:page>
Informative article and useful blog, thank you for sharing keep posting
ReplyDeletesalesforce training,salesforce online training,online salesforce training
Very informative blog and very useful article thank you for sharing with us , keep posting learn more about salesforce training,salesforce online training
ReplyDeleteThis is very informative blog and useful article thank you for sharing with us keep posting more details aboutsalesforce training in bangalore,salesforce online training
ReplyDeleteThis is very informative blog and good content thank you for sharing with us keep postingSelenium training selenium online training Selenium training in bangalore selenium testing training
ReplyDeleteThis is very informative blog and nice article , I really like your technique of writing a blog. I book marked it to my bookmark site list and will be checking back in the near future.Salesforce training, salesforce online training
ReplyDeleteNice information about dynamic nth Level hierarchy My sincere thanks for sharing this post and please continue to share this kind of post
ReplyDeleteSalesfoce Training in Chennai
Thanks for sharing this. This is really a very informative blog. Nice information regarding salesforce implementation services .This is very helpful for those who want to become a saleforce developer. Keep Posting.
ReplyDeleteNice blog..! I really loved reading through this article... Thanks for sharing such an amazing post with us and keep blogging...
ReplyDeleteios app development course
iphone app training course in bangalore
Are you looking for Best Cloud Computing training in Delhi. DIAC offering best online Salesforce training , CRM training, Salesforce Lightning - Admin developer training. Free Demo Class. Call now 9310096831.
ReplyDeleteAre you looking for Best Cloud Computing training in Delhi. DIAC offering best online Salesforce training , CRM training, Salesforce Lightning - Admin developer training. Free Demo Class. Call now 9310096831.
ReplyDeletegreat blog,thank you for sharing valuable information..
ReplyDeleteSalesforce training in USA
Salesforce online training in India
Salesforce is future and its going to rule the world. I can bet you will see that in future.
ReplyDeleteaudience response system
audience response system
audience response system
audience response system
audience response system rental
ReplyDeleteAwesome blog. It was very informative. I would like to appreciate you. Keep updated like this best sap simple finance online training institute in hyderabad
Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.
ReplyDeletedgreatwallofchina
Article submission sites
Very nice your post and tips sharing thanks forceguru
ReplyDeletehttp://www.seotraininginchennai.co.in/Seotrainginchennai
Very nice your post and tips sharing thanks forceguru
ReplyDeleteSEO Training in Chennai
Good blog informative
ReplyDeleteSanjary Academy provides excellent training for Piping design course. Best Piping Design Training Institute in Hyderabad, Telangana. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
Piping Design Course in India
This is an extremely abundant benefit for everyone ... thank you for providing such valuable varieties of data. I am currently a daily reader of your blogs. thank you the most for the fantastic assortment, keep writing.
ReplyDeleteDedicatedHosting4u.com
Good Information
ReplyDelete"Yaaron media is one of the rapidly growing digital marketing company in Hyderabad,india.Grow your business or brand name with best online, digital marketing companies in ameerpet, Hyderabad. Our Services digitalmarketing, SEO, SEM, SMO, SMM, e-mail marketing, webdesigning & development, mobile appilcation.
"
Best web designing companies in Hyderabad
Best web designing & development companies in Hyderabad
Best web development companies in Hyderabad
Thank you for sharing .The data that you provided in the blog is informative and effective.salesforce admin training in bangalore
ReplyDeleteThis is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me.salesforce developer training in bangalore
ReplyDeleteIf you are stuck with your Management assignment then in this case you can opt for our Management Assignment. we provide the bestOnline home work.We also provideLeadership Assignment Help for students across the globe. for more information contact us +16692714848.
ReplyDeleteThe blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents. 123movies
ReplyDelete
ReplyDeleteThanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you once agian
birth certificate in ghaziabad
birth certificate in delhi
birth certificate in gurgaon
birth certificate in bangalore
birth certificate correction
birth certificate online
birth certificate in noida
birth certificate in india
birth certificate apply online
Hi, please share the apex class code again.. i am getting errors.
ReplyDeletewe at SynergisticIT offer the best aws bootcamp
ReplyDeleteI read this post your post so nice and very informative post thanks for sharing this post
ReplyDeleteStudy app for e learning
Adidas showroom in madurai | Woodland showroom in madurai
ReplyDeletePuma showroom in madurai | Crocs showroom in Madurai
Thanks for sharing such amazing content which is very helpful for us. Please keep sharing like this. Also check for Introduction to Salesforce or many more.
ReplyDeleteNice Content. Thanks for sharing this valuable information.
ReplyDeleteSpark Training Institute in Chennai
Spark Training Academy Chennai
Very useful article for a java programming assignment help services, they can easily enhance their skills in coding and hacking with this kind of information.
ReplyDeleteThis post is so interactive and informative.keep updating more information...
ReplyDeleteJava Certificate
Java Learning Course
This blog contains more valuable information, keep sharing your thoughts.
ReplyDeleteRobot Framework Test Automation Training in Chennai
Robot Framework Test Automation Online training
More impressive blog!!! Thanks for shared with us.... waiting for you upcoming data.
ReplyDeleteWhy software testing is important
Why testing is important
ReplyDeleteThis blog contains lot of information about the topic, thanks for this blog.
Components of Spreadsheet
In excel function
Europe Biodiesel Market Report and Forecast 2022-2027’, gives an in-depth analysis of the Europe Biodiesel Market, assessing the market based on its segments like feedstocks, types, technologies, applications, and major regions. The report tracks the latest trends in the industry and studies their impact on the overall market. It also assesses the market dynamics, covering the key demand and price indicators, along with analyzing the market based on the SWOT and Porter’s Five Forces models. The limited supply can be associated with factors like the advent of COVID-19 pandemic, which led to disruptions in supply chain and hampered imports and exports. Furthermore, Argentina is considered as one of the major suppliers of soybean in Europe but due to changes in production and consumption patterns of soybean, the market witnessed a decline.
ReplyDeleteIf you wish to see more reports check here: Asia Pacific Vaccine Market, Micro Inverter Market, Albumin Market, Middle East and Africa Cybersecurity Market, Rice Seeds Market, Vegetable Concentrates Market, Learning Management System Market, States Flooring Market, Sports and Energy Drinks Market, Brazil Healthcare, Sterilisation Services Market, Media Monitoring Tools Market
Do you want to know about Matthew Patrick Net Worth, early life, biography, age, and relationship status?
ReplyDeleteYou have really stickiest my fancy after surfing your useful content and I have come to the conclusion that you are a professional. I love your post and same time love your kind publication. Thank you so much for sharing. maryam abacha american university form out
ReplyDelete