How to get a block by id from specific folder in code?

Vote:
 

I'm facing an issue with getting block in code, can somebody help me??

scenario: I want to get a block(step_block) which is in folder("test folder/new folder/blocks"), how I can get this in code? (POV: I'm running scheduling job, which will update content to one field with above block)

if somebody knows this, please go ahead

#300429
Edited, Apr 20, 2023 7:35
Vote:
 

If you have a shared block and it's not referenced in your current page and you want to read the best thing is to create some sort of settings (such as on home page) with a ContentReference. 

Then set that link to the block and read that reference from the settings allowing to to load that block.

#300431
Apr 20, 2023 10:19
Vote:
 

Sure you can, you can traverse the tree by fetching all children using contentLoader GetChildren. The folder object is called ContentFolder

Here's an example

using Microsoft.AspNetCore.Mvc;

namespace alloyfrankenstein.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FrankensteinController : ControllerBase
    {
        private readonly IContentLoader _contentLoader;

        public FrankensteinController(IContentLoader contentLoader)
        {
            _contentLoader = contentLoader;
        }

        [HttpGet]
        public IActionResult Get(string searchPath)
        {
            var blockRoot = _contentLoader.Get<ContentFolder>(ContentReference.GlobalBlockFolder);
            var searchRoot = blockRoot;
            foreach (var path in searchPath.Split('/'))
            {
                var content = _contentLoader.GetChildren<IContent>(searchRoot.ContentLink).FirstOrDefault(x => x.Name.Equals(path, StringComparison.CurrentCultureIgnoreCase));
                if (content is ContentFolder contentFolder)
                {
                    searchRoot = contentFolder;
                    continue;
                }

                if (content is BlockData blockData)
                {
                    var block = (IContent)blockData;
                    return Ok($"{block.Name} - {block.ContentLink.ID}");
                }

                // no path found, exit
                break;
            }

            return Ok("No block found in path");
        }
    }
}

In the sample site Alloy this structure

Could be fetched by searching for "Alloy Track/Test/Events list"

In the code the last element is the actual block. Simply modify according to your needs.

#300434
Edited, Apr 20, 2023 13:18
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.