Skip to content

getting “URL key for specified store already exists.” error when trying to apply data patch to update a cms page

I am trying to update a cms page through a data patch but, the patch is not applying. I get this error below

Unable to apply data patch VendorModuleSetupPatchDataCreateRegistryPage for module vendor_module. Original exception message: URL key for specified store already exists.

I have the below code for my data patch

class CreateRegistryPage implements DataPatchInterface
{
    /**
     * @var PatchContextInterface
     */
    private $patchContext;
    /**
     * @var PageFactory
     */
    private $pageFactory;

    /**
     * CreateRegistryPage constructor.
     * @param PatchContextInterface $patchContext
     * @param PageFactory $pageFactory
     */
    public function __construct(
        PatchContextInterface $patchContext,
        PageFactory $pageFactory
    ) {
        $this->patchContext = $patchContext;
        $this->pageFactory = $pageFactory;
    }

    /**
     * @inheritDoc
     */
    public static function getDependencies(): array
    {
        return [
            AddHeroInformationToHomePage::class
        ];
    }

    /**
     * @inheritDoc
     */
    public function getAliases(): array
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function apply(): void
    {
        $template = $this->patchContext->template()
                ->get(<vendor_module>, 'registry-page');
        $this->patchContext->media()->copyModuleMedia([
                'Magebit_StarRegistration::banner-image.jpg' => 'occasions/banner-image.jpg'
        ]);

        $pageData = [
                'title' => 'International Star Registry',
                'content_heading' => 'International star registry',
                'page_layout' => 'registry',
                'identifier' => 'international-star-registry',
                'content' => $template,
                'is_active' => 1,
                'stores' => [0],
                'constellation_name' => 'What are you waiting for? {{orange}}Name a star now!{{/orange}}',
                'constellation_summary' => "<p>This is a standard star, which can be observed throughout the year in the sky from worldwide without any specific accessories. It’s a great value for the money and truly amazing gift.</p>",
                'constellation_image' => 'image_certificate.png',
                'occasions_image' => 'banner-image.jpg'
        ];

        $this->pageFactory->create()->setData($pageData)->save();
    }