cakephp / docs

CakePHP CookBook
http://book.cakephp.org
Other
680 stars 2.58k forks source link

Transforming Request Data into Entity Properties - unclear #7889

Open mehov opened 3 months ago

mehov commented 3 months ago

Hi everyone

Please clarify the documentation for Transforming Request Data into Entity Properties. Currently it's unclear how to get the custom fields from Behaviour into Entities of the Table said Behaviour is attached to. It only shows a small snippet out of context.

I created a behaviour and copied that snipet from documentation.

<?php

namespace MyPlugin\Model\Behavior;

class SluggableBehavior extends \Cake\ORM\Behavior implements \Cake\ORM\PropertyMarshalInterface
{

    public function initialize(array $config): void
    {
        // Confirm SluggableBehavior is connected and loaded
        debug([
            '$this' => $this,
            '$config' => $config,
        ]);
        parent::initialize($config);
    }

    public function buildMarshalMap(\Cake\ORM\Marshaller $marshaller, array $map, array $options): array
    {
        return [
            'slug' => function ($value, $entity) {
                // Transform the value as necessary
                return '123';
            }
        ];
    }

    public function slug($entity)
    {
        return $entity->{$this->getDisplayField()};
    }

}

When I call ->slug on an entity, I get a null. I'm clearly missing something, but I can't understand what from the documentation.

Additional resources I checked:

markstory commented 3 months ago

How are you marshalling data into your entity? Is slug part of the data that is being set into the entity?

mehov commented 3 months ago

How are you marshalling data into your entity?

Normal find(), nothing special

Is slug part of the data that is being set into the entity?

No, it isn't

ADmad commented 3 months ago

Is slug in the accessible fields list of your entity?

ADmad commented 3 months ago

Normal find(), nothing special

find() doesn't marshal anything, newEntity() or patchEntity() does.

markstory commented 3 months ago

Is slug part of the data that is being set into the entity?

No, it isn't

The field transformer won't run then. Field marshalling only happens for fields that exist in the data being set into the entity.

dereuromark commented 3 months ago

See https://github.com/dereuromark/cakephp-tools/blob/a917b0d2bf2721a083d44b89c0ea53e0221c9db5/src/Model/Behavior/SluggedBehavior.php#L219 for how you can add a slug into the entity based on certain other fields present when the callback is run.