crud-view
crud-view copied to clipboard
Column type of related field fetched from the wrong table
I created simple app with 2 tables:
Users
and UserRoles
UserRoles
table has 3 collumns: id
(int), user_id
(int) and role
(custom EnumType)
In my AppView.php i have added:
$this->CrudView->setConfig(
'fieldFormatters.enum-role',
function (string $field, $value, EntityInterface $context, array $options): string {
return $this->element('enum', compact('value', 'field', 'context', 'options'));
},
);
Now when i visit https://localhost/admin/user-roles/view/1
Enum is field rendered correctly
But when i try visit https://localhost/admin/users/view/1
I get following exception:
Object of class App\Model\Enum\Role could not be converted to string
After debugging i think i found the core of the issue.
Problem is inside schema
method:
CrudViewHelper.php:393, CrudView\View\Helper\CrudViewHelper->schema()
CrudViewHelper.php:175, CrudView\View\Helper\CrudViewHelper->columnType('role')
CrudViewHelper.php:126, CrudView\View\Helper\CrudViewHelper->introspect('role', {App\Model\Entity\UserRole}, ['formatter' => null])
CrudViewHelper.php:97, CrudView\View\Helper\CrudViewHelper->process('role', {App\Model\Entity\UserRole}, [])
has_many.php:51, include()
When process function is called current context is set to App\Model\Entity\UserRole
entity here.
But when later CrudViewHelper->schema()
is called this context is completely ignored and schema of current table App\Model\Table\UsersTable
is used instead of App\Model\Table\UserRolesTable
schema
Since role
field does not exists in App\Model\Table\UsersTable
$type will became null.
Since $type is null
script will fallback to calling formatString('role', {\App\Model\Enum\Role})
.
Inside formatString string cast will cause Object of class App\Model\Enum\Role could not be converted to string
excepion mentioned earlier
My current work around fix to replace schema() method: https://github.com/FriendsOfCake/crud-view/blob/fad8ab9261a3e145f739fa2201a8a31d0796b555/src/View/Helper/CrudViewHelper.php#L393-L396 With following contents:
public function schema(): TableSchemaInterface
{
return TableRegistry::getTableLocator()->get($this->getContext()->getSource())->getSchema();
}
But i have mixed feelings with using table locator inside helper.