Transforming Request Data into Entity Properties - unclear
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:
- https://api.cakephp.org/5.0/interface-Cake.ORM.PropertyMarshalInterface.html#buildMarshalMap()
- https://github.com/cakephp/cakephp/blob/c43c253efeeda1fd2b5f5c9aca329c7cd383bc6b/src/ORM/Behavior/TranslateBehavior.php#L264
How are you marshalling data into your entity? Is slug part of the data that is being set into the entity?
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
Is slug in the accessible fields list of your entity?
Normal find(), nothing special
find() doesn't marshal anything, newEntity() or patchEntity() does.
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.
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.
This issue is stale because it has been open for 120 days with no activity. Remove the stale label or comment or this will be closed in 15 days