bolt-cms

Bolt 4 Add Records Programmatically via Cron


Want to add content to bolt 4 programmatically however can only really see 1 example for Bolt 3.

Would like this to run via cron in long run however this functionality looks on the backburner for Bolt 4 too but sure I can botch a way to run.

Within Bolt 3 the below was suggested:

$values = file('myfile.csv');

// now create an associative array to use below

$record = $this->app['storage']->getEmptyContent($contenttypeslug);
$record->setValues($values);

$id = $this->app['storage']->saveContent($record);

This however does not seem to work as i'm guessing a lot has changed in this update. I intend to get my data via api and then run similar to above if anyone in the know can suggest how to go about this?

I have started by looking at using Bolt\Repository\ContentRepository; and Bolt\Controller\Backend\ContentEditController by trying to pick apart similar functionality here:

https://github.com/bobdenotter/conimex/blob/master/src/Import.php

However this seems overly complicated for me to quite pick apart and just want a simpler example maybe with image / image galleries.

So far I have started with a command line function then can use system cron to run it at desired frequency. The below code is not working for many reasons firstly getFieldToUpdate seems to throw a private function error and can't seem to get passed that.

public function import(): void
{
    $user = $this->getUser();
    /** @var Content $content */
    $slug = 'test-property';

    $contentTypeSlug = 'properties';
    $contentType = $this->config->getContentType($contentTypeSlug);
    $content = $this->contentRepository->findOneBySlug($slug, $contentType);

    if (! $content) {
        $content = new Content($contentType);
        $content->setStatus('published');
        $content->setAuthor($user);
    }
    $content->setFieldValue("bedrooms", 2);
    //$field = $this->contentEditController->getFieldToUpdate($content, 'bedrooms');
    //$this->contentEditController->updateField($field, $item, null);
    //$content->setFieldValue($key, $item);
    
    $this->em->persist($content);
    $this->em->flush();
    
}

private function getUser()
{
    $user = null;

    // Fall back to the first user we can find. 🤷‍
    if (! $user) {
        $user = $this->userRepository->findOneBy([]);
    }

    return $user;
}

Solution

  • There's a working example here:

    https://github.com/bobdenotter/phpnews_2019/blob/master/src/RssFetcherExtension.php#L93-L191