dynamic / silverstripe-elemental-blog

Display a list of the most recent posts of a specific blog
BSD 3-Clause "New" or "Revised" License
1 stars 10 forks source link

Getter for pulling content #2

Closed korthjp17 closed 6 years ago

korthjp17 commented 6 years ago

Since the blocks replace the content zone, we can't pull the copy from the page anymore. Can we write a getter to pull the content zone from the first ContentBlock?

Or open to other suggestions on how to do this

mak001 commented 6 years ago

This can be solved with

/**
 * Returns the content of the first content element block
 *
 * @return HTMLText
 */
public function getContent()
{
    $content = $this->owner->ElementalArea()
        ->Elements()->filter(array(
            'ClassName' => ElementContent::class
        ))->first();
    // if the block exists return its content
    if ($content && $content->exists()) {
        return $content->HTML;
    }
   // else return and empty HTMLText
    return DBHTMLText::create();
}

This can be tested with

public function testGetContent()
{
    $expected = "Test";
    /** @var BlogPost $post */
    $post = $this->objFromFixture(BlogPost::class, 'one');
    $this->assertEquals('', $post->getContent());

    $post->ElementalArea()->Elements()->add(ElementContent::create());
    $this->assertEquals('', $post->getContent());

    $element = $post->ElementalArea()
        ->Elements()->filter(array(
            'ClassName' => ElementContent::class
        ))->first();
    $element->HTML = $expected;
    $element->write();

    $this->assertEquals($expected, $post->getContent());
}

This was not put into the module because it was implemented in another module and would potentially cause conflicts if elements/blocks are not implemented on blog posts.