Search code examples
phpdoctrine-ormsymfony4

Call to a member function setDp() on null in symfony4


I am beginning to learn symfony4. I am stuck with the problem that is to update the existing data in the database by using Symfony form. The problem occurs with the file to set by the member function which is shown in the code. Have any solution? please resolve

The file move successfully but no set with the member function Here is the code

enter image description here

/**
 * @Route("/new", name="new")
 */
public function new()
{
    return $this->render('dashboard/new.html.twig', [
        'controller_name' => 'DashboardController',
    ]);
}[enter image description here][1]

/**
 * @Route("/edit/{username}", name="edit")
 */
public function edit(Request $request, $username)
{   
    $user = new User();
    $user = $this->getDoctrine()->getRepository(User::class)->find($username);
    $imageConstraints = [
        new Image([
            'maxSize' => '5M'
        ])
    ];
    $form = $this->createFormBuilder($user)
        ->add('name', TextType::class)
        ->add('username', TextType::class)
        ->add('bio', TextType::class)
        ->add('location', TextType::class)
        ->add('website', UrlType::class)
        ->add('dob', BirthdayType::class)
        ->add('dp', FileType::class, [
            'multiple' => false,
            'mapped' => false,
            'required' => false,
            'constraints' => $imageConstraints
        ])
        ->add('header_pic', FileType::class, [
            'required' => false,
            'multiple' => false,
            'mapped' => false,
            'constraints' => $imageConstraints
        ])
        ->add('save', SubmitType::class)
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $entityManager = $this->getDoctrine()->getManager();
        /**@var UploadedFile $uploadedFile */
        //dd($form['dp']->getData());

        $destination = $this->getParameter('kernel.project_dir').'/public/uploads';

        //for Dp means Profile pic
        $uploadedFileDp = $form['dp']->getData();
        $originalFilenameDp = pathinfo($uploadedFileDp->getClientOriginalName(), PATHINFO_FILENAME);
        $newFilenameDp = $originalFilenameDp.'-'.uniqid().'.'.$uploadedFileDp->guessExtension();
        $uploadedFileDp->move(
            $destination,
            $newFilenameDp
        );
        $user->setDp($newFilenameDp);

        //Header pic
        $uploadedFileHeaderPic = $form['header_pic']->getData();
        $originalFilenameHeaderPic = pathinfo($uploadedFileHeaderPic->getClientOriginalName(), PATHINFO_FILENAME); 
        $newFilenameHeaderPic = $originalFilenameHeaderPic.'-'.uniqid().'.'.$uploadedFileHeaderPic->guessExtension();

        $uploadedFileHeaderPic->move(
            $destination,
            $newFilenameHeaderPic
        );
        $user->setHeaderPic($newFilenameHeaderPic);
        $entityManager->flush();

        // do anything else you need here, like send an email

        return $this->redirectToRoute('new');
    }
    return $this->render('dashboard/edit.html.twig', array
        ('form' => $form->createView())
    );
  }
}

Call to a member function setDp() on null


Solution

  • Your problem is here:

    $user->setDp($newFilenameDp);
    

    The error is telling you that the setDp can't be called against null, therefore what that then means is $user must be null and not an instance of the user object you are expecting.

    You have this line of code:

    $user = $this->getDoctrine()->getRepository(User::class)->find($username);
    

    It is possible that your find is failing and returning you the null, ie you're failing to actually locate the user and populate $user with your object. You should be throwing an exception in your edit method or aborting at this point.


    $user = $this->getDoctrine()->getRepository(User::class)->find($username);
    if( $user === null or $user instanceof WhatObjectYouExpect === false )
    {
       throw new Exception('Failed to load user data');
    }