M Markero
M Markero

Reputation: 199

Symfony 2 - writing new method in entity class

i'm trying to write new get method in my entity class

This is the property

protected $courseLink;

The get method for it

/**
     * Get courseLink
     *
     * @return string 
     */
    public function getCourseLink()
    {
        $this->courseLink = '/courses/'.$this->getCourseTitle();

        return $this->courseLink;
    }

The getCourseTitle method

/**
     * Get courseTitle
     *
     * @return string 
     */
    public function getCourseTitle()
    {
        return $this->courseTitle;
    }

This is the controller with select query

    $em = $this->getDoctrine()->getEntityManager();
    $query = $em->createQuery(
    'SELECT c FROM DprocMainBundle:Courses c ORDER BY c.Id DESC'
    );
    $course = $query->setMaxResults(4)->getResult();
    //print_r($course);
    return $this->render('DprocMainBundle:Dproc:index.html.twig', array('courses' => $course));

print_r shows

Array

(
    [0] => Dproc\MainBundle\Entity\Courses Object
        (
            [Id:protected] => 1
            [courseTitle:protected] => 3ds Max и Vray
            [courseContent:protected] => 3ds max course is awesome!
            [courseCategory:protected] => 3ds-max
            [courseTeacher:protected] => Ваге Мурадян
            [coursePayment:protected] => payment..
            [courseSchedule:protected] => schedule..
            [courseDescription:protected] => description..
            [courseLink:protected] => 
        )

)

courseLink is null, but why? how should i give to it value in class then?

Upvotes: 0

Views: 122

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52493

As the courseLink property itself is not being stored in your database it will be null until you call the getCouseLink() method. That's actually the correct behavior.

Just pass the $course object you fetched from database to your view and access it like this:

{{ course.courseLink }}

Twig will call the getCourseLink() methdod which will return the correct string / url.

Upvotes: 1

Related Questions