Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Create Cms Page from PHP code

1
by mjauvin, last modified on May 12th, 2021 - Previously published on OctoberTricks

Use this code to programatically create a CMS Page with URL/Title translations:

    $page = new \Cms\Classes\Page([
        'fileName' => 'test-page',
        'title' => 'My Page Title',
        'url' => '/test-page',
        'layout' => 'default',
    ]);

    $page->attributes['viewBag'] = [
            'localeUrl' => [
                    'fr' => '/french-URL',
                    'de' => '/deutch-URL',
            ],
            'localeTitle' => [
                    'fr' => 'French Title',
                    'de' => 'Deutch Title',
            ],
    ];

    $page->save();

(Note: to be used with Rainlab.Translate or Winter.Translate plugin)

Use this code to programatically create a CMS Page and attach a component:

    $page = new \Cms\Classes\Page([
        'fileName' => 'test-page',
        'title' => 'My Page Title',
        'url' => '/test-page',
        'layout' => 'default',
    ]);

    $page->attributes['myComponent'] = [];

    $page->save();

Discussion

2 comments

0
Meindert
Post on October 29th, 2021 1:46 PM

Hello,

When adding this in my Plugin.php boot function it errors because the page already exists. How do I prevent this error, and only generate the page on first plugin initialisation?

0
Dreanad
Post on January 18th, 2022 8:40 AM

Hello :) i have a simple function that list all page in the current thème, you can use it to prevent if the page already exists

    public function listUrlIntern(){
        $currentTheme   = Theme::getEditTheme();
        $allPages       = Page::listInTheme($currentTheme, true);
        $options        = [];
        foreach ($allPages as $pg) {
            $options[str_replace('.htm', '', $pg->fileName)] = $pg->title;
        }

        return $options;
    }
We use cookies to measure the performance of this website. Do you want to accept these cookies?