Welcome Guest, Not a member yet? Register   Sign In
Entity - allowedFields inconsistancy
#1

I have been using CI4 models with entities.
I have found an inconsistency with model and entity behaviour and would appreciate some advice on whether this is a 'bug-like' feature and/or whether there is a work around for my use case.

Model Behaviour
The behaviour for models is that if you define $allowedFields...
Code:
protected $allowedFields = ['field1','field2','field3'];
Quote:Documentation => This array should be updated with the field names that can be set during save, insert, or update methods. Any field names other than these will be discarded. This helps to protect against just taking input from a form and throwing it all at the model, resulting in potential mass assignment vulnerabilities.
Great. Only allowed fields will be passed through to the db which is what the model is used for.

Entity Behaviour
For the first time, I want to use the Entity functionality but I don't necessarily want to commit the entity record to a db. I am using an Entity to consistently format some input and possibly output it to another api. ie. I want to take advantage of the Entity functionality but I might not need the database layer in this case. I setup my entity as per standard. I add the $allowedFields as usual.
Code:
protected $allowedFields = ['field1'=>NULL,'field2'=>NULL,'field3'=>NULL];
Then in the controller I reference the Entity:
Code:
$currentRequest = new \App\Entities\CurrentRequest();
I fill the Entity using the quick fill (from an input array sourced externally - not validated):
Code:
$currentRequest->fill( ['field1'=>'test1','field2'=>'test2','field3'=>'test3','field4'=>'test4','field5'=>'test5'] );
(I can use all the great Entity functionality stuff set() and get() etc and use entity functionality as you like).
Then I want to use my Entity, however as an example the output of:
Code:
print_r($currentRequest->toArray());
outputs:   ['field1'=>'test1','field2'=>'test2','field3'=>'test3','field4'=>'test4','field5'=>'test5']

Effectively the Entity is embracing more input than the defined $allowedFields while Model does not.
  • Why doesn't Entity use $allowedFields consistently like Model and output ['field1'=>'test1','field2'=>'test2','field3'=>'test3']?
If this is not a bug or in the meantime...
  • How can I use the $allowedFields already defined in the Model to filter my output?
Code:
print_r($currentRequest);
shows that the original definition is retained:
Code:
[original:protected] => Array
        (
            [field1] =>
            [field2] =>
            [field3] =>
        )
(ie. I don't know how to access [original:protected] so I could throw it back through a loop or array_filter or such...).

Thank you very much for your insight.
Reply


Messages In This Thread
Entity - allowedFields inconsistancy - by maximusto - 08-29-2021, 02:04 PM



Theme © iAndrew 2016 - Forum software by © MyBB