Jump to content

Save matrix field value to template field


combicart
 Share

Recommended Posts

In my current setup I've added a matrix field called 'body_extended'. Inside this field one of the matrix types is a 'text' block. Inside this block I have two fields: 'title' and 'body'. The body field is a CKEditor text area field.

I would like to copy the content of the 'body' field that is inside the first 'text' block that is available on the page inside a different field (called 'seo_description') on the same page (just a regular field, not a matrix field) however I'm struggling to find the best approach. I've started looking into hooks but I'm not sure if and which hook is suitable for this situation.

Has somebody faced a similar situation before or could someone point me in the right direction? I've attached a screenshot of what I'm trying to accomplish.

Thanks!

Screenshot 2020-04-20 at 19.33.10.png

Link to comment
Share on other sites

I’m sure a hook specific to your site wouldn’t be a problem. A couple of questions you’ll need to ask yourself:

Do you want to copy all body texts from the matrix field or just the first one? Should the markup CKEditor generates be included? Do you want changes made to the SEO Description field to sync back? Should the text be copied live as users are typing or just once when the page is saved? Is the SEO Description field locked or can it be edited by users? What should happen if a user changes both fields?

The simplest way would probably be to hook Page::save in your ready.php, find the text and copy it over.

Link to comment
Share on other sites

Thanks for pointing me in the right direction. I've add a hook to the ready.php file. If someone is interested, below i've added a snippet of what i'm using:

wire()->addHookAfter('Pages::saveReady', function(HookEvent $event) {
    $page = $event->arguments(0);

    foreach ($page->body_extended as $item) { // $body_extended is the name of the matrix field
        if ($item->type == 'text') { // Looking for a 'text' matrix field
            $seo_description = substr(strip_tags($item->body), 0, 255); // Find the body text and strip/trim the html tags
            break;
        }
    }

    $page->seo_description = $seo_description; // Save the body inside the seo_description field on the page
});

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...