I am new to Drupal but an experienced developer. I'm creating a DS field in which I will display a custom block chosen by the content editor. I have successfully gotten a referenced entity (two references deep) based on this answer How to get instance of referenced entity?.
Is there some data that will tell me what type of thing it is? Should I find out by looking in the UI at the block layout menu?
It would be simple to answer the question 'How do I get the block ID?' (answer: $bid = $campaignFundraisingBlock->id(); and I will fix that shortly) but the question I really want answered is 'How can I find out what type of data I have?'
The top answer (here) How can I programmatically display a block? made it clear that the type of block makes a difference in how you render it, so it seems important to be able to find out what type of data I have.
With the code (below) I am currently getting this error: Error: Cannot use object of type Drupal\block_content\Entity\BlockContent as array in Drupal\shpf_campaign\Plugin\DsField\ParentCampaignFundraisingBlock->build(), (which I will fix shortly).
Here's my code:
class ParentCampaignFundraisingBlock extends DsFieldBase {
public function build() {
$campaignStory = $this->entity();
$fieldCampaignFundraiserOptIn = $campaignStory->get('field_campaign_fundraiser_opt_in')->getValue();
$showFundraiserCta = FALSE;
if (!empty($fieldCampaignFundraiserOptIn)) {
$showFundraiserCta = $fieldCampaignFundraiserOptIn[0]['value'];
}
if ($showFundraiserCta) {
$campaign = $campaignStory
->get('field_campaign_node_type')
->first()
->get('entity')
->getTarget()
->getValue();
$campaignFundraisingBlock = $campaign
->get('field_campaign_fundraising_block')
->first()
->get('entity')
->getTarget()
->getValue();
/* question: Do I have a renderable block in $campaignFundraisingBlock, or a type? How can I tell? */
$bid = $campaignFundraisingBlock['values']->id;
/* This next code assumes that the data I have is a block created in the interface (content block), but that seems like a big assumption that is not necessarily true. */
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()
->getViewBuilder('block_content')
->view($block);
return $render;
}
}
}
Some background information: The block type is set to 'Featured CTA' and there are a bunch of blocks of that type available for content editors to choose from. The content editor chooses the block in the 'campaign' content type (it is an entity reference). The end user can fill out a form in which they tell a 'campaign story'. The end user can choose to include the campaign fundraiser or not. The campaign story has an entity reference to the campaign it is part of.
So, how do I find out what type of data I have?
field_campaign_fundraising_block
is, and when loading that entity via Entity/Field/Typed Data API methods, is that entity object something that can be rendered and how to tell that it could be rendered?