1

My customer will have lots of sections and lots of entries in each, for each site. Over time they will add new language sites.

When a new site is added, there are no sections or entries for it. So we have to then edit each section to set the URL format and template, even though they will be the same for each site.

I would like to make it as easy and quick for the customer to add new sites.

So is there a way I can automatically set these values, enable the site, and propagate entries, for every section (or even certain sections), every time they create a new Site?

Thanks

enter image description here

  • Yes it is but only with PHP. Do you search for a solution without custom code? – Robin Schambach Mar 19 '19 at 22:16
  • Searching for solution with or without code. – Laurence Cope Mar 20 '19 at 9:57
2

You can use the EVENT_AFTER_SAVE_SITE event to create/update the new section settings

Event::on(
    Sites::class,
    Sites::EVENT_AFTER_SAVE_SITE,
    function (SiteEvent $event) {
        if ($event->isNew) {

            ProjectConfigHelper::ensureAllSitesProcessed();
            $siteId = $event->site->id;

            // array of sections you want to propagate
            $sectionsToActivate = [
                'test',
            ];

            foreach ($sectionsToActivate as $sectionHandle){

                $section = Craft::$app->getSections()->getSectionByHandle($sectionHandle);
                if($section !== null){
                    /** @var \craft\models\Section_SiteSettings[] $siteSettings */
                    $siteSettings = $section->getSiteSettings();

                    // the site you want to clone from
                    $siteSettings[$siteId] = clone $siteSettings[1]; 
                    $siteSettings[$siteId]->id = null;
                    $siteSettings[$siteId]->siteId = $siteId;

                    // eventually you want to change some other settings ¯\_(ツ)_/¯
                    //$siteSettings[$siteId]->template = '';
                    //$siteSettings[$siteId]->uriFormat = '';
                    //$siteSettings[$siteId]->hasUrls = '';

                    $section->setSiteSettings($siteSettings);
                   Craft::$app->getSections()->saveSection($section);
                }
            }
        }
    }
);

Explanation: As soon as you create a new site, you'll loop all sections you want to activate and grab their "main" site settings, copy them and set the id to null in order to create a new record

|improve this answer|||||
  • Sorry for late reply, this worked! Thanks a lot. – Laurence Cope Jun 13 '19 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.