Jump to content

Searching a ProFields Table from within ready.php hook code


JayGee
 Share

Recommended Posts

I've created a simple sports league fixture generator in a template called 'League'. Teams are added as page references then a fixture list is created as a ProFields table by hooking page save to add new rows to the table.

The bit I need help with is that I'm trying to check a fixture doesn't already exist before adding it to the table (e.g. if a new team is added to the league). I'm trying to do this with a PW selector to filter the fixtures table and check whether Team A vs Team B already exists in the table. Then on the next line checking no fixture was found by using count().

However as soon as I add the selector the script no longer adds any rows to the table. If I take it out, it all works fine (albeit with duplicate fixtures each time the page is saved). I've also tested the selector in a page template and it filters as expected. It's late here (UK)... I'm probably doing something stupid! Any ideas?

<?php

//Hook page save to generate league fixture lists
$wire->addHookAfter("Pages::saved(template=league)", function ($event) {

    //Get which page has been saved
    $page = $event->arguments(0);

    $noFixturesAdded = 0;

        //For each team in league cycle through and add home fixtures
        foreach ($page->teams_in_league as $teamA) {

            foreach ($page->teams_in_league as $teamB) {
                
                //Check if fixture already exists
                $existingFixtures = $page->fixtures("team_a=$teamA,team_b=$teamB");

                //Check team A is not the same as team B as you can't play yourself
                //Then add row to fixture table
                if ($teamB != $teamA && $existingFixtures->count() < 1 ) {
                    $fixture = $page->fixtures->makeBlankItem();
                    $fixture->team_a = $teamA->id;
                    $fixture->team_b = $teamB->id;
                    $page->fixtures->add($fixture);
                    $noFixturesAdded ++;
                }

            }

        }

        //Save updates to table
        $page->save('fixtures');

        $message = "League saved. $noFixturesAdded new fixtures were added";
        $this->message($message);
        
});

 

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

×
×
  • Create New...