Reputation: 261
I have an error: "Cannot use object of type AppBundle\Entity as array", and it makes no sense for me, imo it's okay.
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$repository = $this->getDoctrine()->getRepository(User::class);
$findUser = $repository->findOneBy(['username' => $form->getData()['username']]);
if ($findUser) {
return $this->redirectToRoute('login');
}
Error Cannot use object of type AppBundle\Entity\User as array is at line with "$findUser ="
Can someone explain my why isn't it working?
Symfony 3.3, PHP 7
Upvotes: 1
Views: 6145
Reputation: 267
Usualy when you get error like this you have to check data type. If variable is array you can access it only as array using $variable['index'];
, if it is object you can access it using $variable->index;
. Best way to figure out variable type is to use print_r($variable);
or var_dump($variable);
and it will output variable type for you. In your case you will use print_r($form->getData());
or var_dump($form->getData());
. If you use wrong way to get data from variable (array/object) you will receive (Cannot use object of type) error.
If it is array (in your case it isn't):
$form->getData()['username'];
If it is object:
$form->getData()->username;
if your framework has getters and setters:
$form->getData()->getUsername();
Upvotes: 3
Reputation: 904
It seems you doesn't see differences between objects and arrays. Let's say you have an object (class) Car
and that object has a property e.g. type
set to 'Van'. Now you want to get this type. How you do it? Using ->
symbol.
$car = new Car();
echo $car->type; //Van
Now we have an array $car
with named index type
set to Muscle
.
$car = ['type' => 'Muscle'];
echo $car['type']; //Muscle
You cannot treat Object as Array and vice versa. You have Entity (which is just a class, object) so you have to treat it like an object.
So if you have Entity User
you access its properties using ->
not []
.
Upvotes: 1
Reputation: 14210
This example here explains everything:
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
$task = $form->getData();
...
}
Thus, $form->getData()
holds the entity. So, if your User
entity has a username
attribute, you should call it as $form->getData()->getUsername()
or whatever getter you have there.
Upvotes: 5