Welcome Guest, Not a member yet? Register   Sign In
DataCaster not working
#1

Hi. There is an error when converting DataСaster types for an Entity, the set() method is not specified. Because of this, type casting does not work. 
Look at this https://github.com/codeigniter4/CodeIgni...st.php#L24
My code Entity: 

PHP Code:
// Step 1, fill properties
$entity->fill($data);
// Step 2 run Entity->__set($value)

// See https://github.com/codeigniter4/CodeIgniter4/blob/fd9cb65c23c047d2a65203d9f602fe34902d48f0/system/Entity/Entity.php#L165

// Step 3 call Cast
// https://github.com/codeigniter4/CodeIgniter4/blob/fd9cb65c23c047d2a65203d9f602fe34902d48f0/system/Entity/Entity.php#L434
$value $this->castAs($value$dbColumn'set'); 

But some Casts (IntegerCast, FloatCast, ...) don't have a set (only get) method and everything breaks
Simple CI 4 project for beginners codeigniter-expenses
Reply
#2

You can't use DataCaster\Cast classes with Entity Property casting.
It is a misuse. You must use Entity\Cast classes.

DataCaster\Cast classes are for Model Field casting.
https://codeigniter4.github.io/CodeIgnit...ld-casting
Reply
#3

(This post was last modified: 05-06-2024, 01:28 AM by ozornick.)

This happens in the Model. I get the data in the form of an entity.
PHP Code:
final class SettingsParameter extends Entity
{
    private ?int $id null;
    private string $parameter;
    private string $value;
    private ?string $description;
    protected $casts = [
        'id'          => '?int',
        'parameter'  => 'string',
        'value'      => 'string',
        'description' => '?string',
    ];

    public function getId(): ?int
    
{
        return $this->id;
    

For getId() I can't get ?int
So I need to move the $cast parameter to the Model? Can this affect the entity in the future?
Simple CI 4 project for beginners codeigniter-expenses
Reply
#4

The SettingsParameter entity does not work, because you added private properties.
Remove all the private properties if you want to use Entity.
Reply
#5

Everything is working well. I change $attributes myself and use setXXX() to set the properties. The only problem is with typing. Before that, everything worked because there were no strict_types=1 in the system files.
I tried to put $casts into the Model and it works
Simple CI 4 project for beginners codeigniter-expenses
Reply
#6

Entity Property casting and Using Model Field casting with Entity behaves differently.
See Important note in https://codeigniter4.github.io/CodeIgnit...ld-casting
Reply




Theme © iAndrew 2016 - Forum software by © MyBB