Skip to content

Page reference field integer vs Page object when hooking on changed #2142

@adrianbj

Description

@adrianbj

If you add a Profields table field row via the API and you set the value of a Page reference field within that table row and then hook on changed, the value of that Page reference field is an integer instead of a page object, eg:

Add row:

$u->of(false);
$subscription = $u->subscriptions->makeBlankItem();
$subscription->coupon = 1349;
$u->subscriptions->add($subscription);
$u->save('subscriptions');

Hook on changed:

$wire->addHookAfter('User::changed(subscriptions)', function($event) {
    
    $u = $event->object;
    $subscriptions = $event->arguments(2);
    if(!$subscriptions || $subscriptions->count() < 2) return;

    $last_sub = $subscriptions->last();

    // if it's a API call sometimes the coupon is added as an int (id) instead of a Page object
    // and $event->arguments(2) will return the integer instead of the Page object
    if(is_int($last_sub->coupon)) {
        $last_sub_coupon = $this->wire('pages')->get((int) $last_sub->coupon);
    }
    else {
        $last_sub_coupon = $last_sub->coupon;
    }

});

That $last_sub_coupon = $this->wire('pages')->get((int) $last_sub->coupon); is needed, but if the initial code to add the row looks like:

$u->of(false);
$subscription = $u->subscriptions->makeBlankItem();
$subscription->coupon = $pages->get(1349);
$u->subscriptions->add($subscription);
$u->save('subscriptions');

then $last_sub->coupon is always a Page object.

I don't know if this is unique to table fields which is why I am posting here.

I understand why it's happening, but I feel like it's inconsistent and a real confusion because you might have two blocks of code adding rows and one might assign an ID and the other a page object. And of course, if you add a row via the admin, it will be a page object so you need this is_int check.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions