php - 如果实体存在于数组中,显示添加或删除按钮

标签 php symfony doctrine-orm twig

我有实体 TravelFavoriteUser ,每个用户都可以将旅行添加到他的收藏夹列表中。

当显示所有旅行列表时,如果旅行已经在用户收藏夹列表中,则显示按钮(删除),如果不在列表中,则显示(添加到收藏夹)。

在 Action Controller 中,我做了一个 queryBuilder 来获取当前经过身份验证的用户的所有收藏夹列表,并将结果放入 ($favorite)

    public function listAction($page, Request $request)
    {
    $em = $this->getDoctrine()->getManager();

    // code of boutton add to or remove from favorite
    $user = $this->getUser(); // this is a function to verify if user is AUTHENTICATED_REMEMBERED
    if($user) {
    $favorite = $em->getRepository('ProjectTravelBundle:Favorite')->getFavoriteByUser($user);
    }
    else{
    $favorite = '';
    }

    $paginator  = $this->get('knp_paginator');

    $qb = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend();
    $nb = $qb->getQuery()->getResult();

    $pagination = $paginator->paginate(
        $qb,
        $request->query->get('page', $page),10);


    return $this->render('ProjectFrontendBundle:Travel:travel-list-view.html.twig',array(
        'pagination' => $pagination,
        'nb' => $nb,
        'favorite' =>$favorite, // list of favorites of current user 
    ));
}

我考虑的解决方案是测试 travel 是否在 array(favorite) 中,所以 show boutton remove 如果不是,则显示 boutton add ,但我没能在 显示 Twig

{% for travel in pagination %}
//..................

{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}

{% if travel.id not in favorite %}
    <span><a href="{{ path('frontend_travel_add_favorite', {'id': travel.id} ) }}" class="pull-right button btn-small red">Add to favorite</a></span>
{% else %}
    <span><a href="{{ path('frontend_travel_delete_favorite', {'id': favorite.id} ) }}" class="pull-right button btn-small red">Remove from</a></span>
{% endif %}

// if user is not AUTHENTICATED_REMEMBERED
{% else %}
<span><a href="{{ path('frontend_travel_add_favorite', {'id': travel.id} ) }}" class="pull-right button btn-small red">Add to favorite</a></span>
{% endif %}

//..........
{% endfor %}

存储库:queryBuilder

    // get list of favorite of current user
    public function getFavoriteByUser($user)
    {
        $qb = $this->createQueryBuilder('f')
            ->Where('f.user = '.$user);

        return $qb->getQuery()->getResult();
    }

已更新

最喜欢的实体

class Favorite
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\User")
 * @ORM\JoinColumn(nullable=false)
 */
protected $user;

/**
 * @ORM\ManyToOne(targetEntity="Project\TravelBundle\Entity\Travel", inversedBy="favorites")
 * @ORM\JoinColumn(nullable=false)
 */
protected $travel;


/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set user
 *
 * @param \Project\UserBundle\Entity\User $user
 * @return Favorite
 */
public function setUser(\Project\UserBundle\Entity\User $user)
{
    $this->user = $user;

    return $this;
}

/**
 * Get user
 *
 * @return \Project\UserBundle\Entity\User 
 */
public function getUser()
{
    return $this->user;
}


/**
 * Set travel
 *
 * @param \Project\TravelBundle\Entity\Travel $travel
 * @return Favorite
 */
public function setTravel(\Project\TravelBundle\Entity\Travel $travel)
{
    $this->travel = $travel;

    return $this;
}

/**
 * Get travel
 *
 * @return \Project\TravelBundle\Entity\Travel 
 */
public function getTravel()
{
    return $this->travel;
}
}

旅游实体

class Travel
{
/....

/**
 * @ORM\OneToMany(targetEntity="Project\TravelBundle\Entity\Favorite", mappedBy="travel", cascade={"remove"})
 */
private $favorites; 


public function __construct()
{
    $this->favorites = new \Doctrine\Common\Collections\ArrayCollection();
}

/...........
/**
 * Add favorites
 *
 * @param \Project\TravelBundle\Entity\Favorite $favorites
 * @return Travel
 */
public function addFavorite(\Project\TravelBundle\Entity\Favorite $favorites)
{
    $this->favorites[] = $favorites;
    $favorites->setTravel($this);
    return $this;
}

/**
 * Remove favorites
 *
 * @param \Project\TravelBundle\Entity\Favorite $favorites
 */
public function removeFavorite(\Project\TravelBundle\Entity\Favorite $favorites)
{
    $this->favorites->removeElement($favorites);
}

/**
 * Get favorites
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getFavorites()
{
    return $this->favorites;
}

最佳答案

你可以试试这个:

在你的 Controller 中:

if($user) {
    $favorite = $em->getRepository('ProjectTravelBundle:Favorite')->getFavoriteByUser($user);
    $ids = array_map(function($entity) { return $entity->getTravel()->getId(); }, $favorite);
} else{
    $favorite = '';
    $ids = array();
}
...
return $this->render('ProjectFrontendBundle:Travel:travel-list-view.html.twig',array(
        'ids' => $ids,
        'pagination' => $pagination,
        'nb' => $nb,
        'favorite' =>$favorite, // list of favorites of current user 
    ));

在你的模板中:

{% if travel.id not in ids %}
    <span><a href="{{ path('frontend_travel_add_favorite', {'id': travel.id} ) }}" class="pull-right button btn-small red">Add to favorite</a></span>
{% else %}
    <span><a href="{{ path('frontend_travel_delete_favorite', {'id': favorite.id} ) }}" class="pull-right button btn-small red">Remove from</a></span>
{% endif %}

希望对您有所帮助。

关于php - 如果实体存在于数组中,显示添加或删除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676488/

相关文章:

使用 php 变量作为 id 的 javascript 切换函数

php - 如何在 foreach 循环中创建数组?

php - 从 Controller Symfony2 中的 URL 获取参数

sql - 教义2.1,其中外键id = ?,编辑: Fixed in Doctrine 2. 2

php - 查询生成器中属性的 DQL 访问属性(学说)

PHPUnit - 数据库测试,如何管理它

php - 您如何对数千个条目使用自动完成功能?

php - 在 symfony 中避免依赖注入(inject)中的容器字符串

symfony - 带有 phpfastcache 包的 Redis 驱动程序

symfony - 如何为现有的 Symfony+Doctrine 应用程序生成初始/基础迁移?