从数据库或实体检索表并在 JavaScript 块内迭代

问题描述 投票:0回答:1

我对 symfony 和 web 开发总体来说是新手。我需要检索我的实体信息并迭代我的表,而不是静态添加的列表“项目”,并且我不知道如何将其获取到 JavaScript 块中。这是为了实现动态分页。 我希望我说清楚了。

这是我要更改的代码:

const list_items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
    "Item 7",
    "Item 8",
    "Item 9",
    "Item 10",
    "Item 11",
    "Item 12",
    "Item 13",
    "Item 14",
    "Item 15",
    "Item 16",
    "Item 17",
    "Item 18",
    "Item 19",
    "Item 20",
    "Item 21",
    "Item 22"
];

const list_element = document.getElementById('list');
const pagination_element = document.getElementById('pagination');

let current_page = 1;
let rows = 5;

function DisplayList (items, wrapper, rows_per_page, page) {
    wrapper.innerHTML = "";
    page--;

    let start = rows_per_page * page;
    let end = start + rows_per_page;
    let paginatedItems = items.slice(start, end);

    for (let i = 0; i < paginatedItems.length; i++) {
        let item = paginatedItems[i];

        let item_element = document.createElement('div');
        item_element.classList.add('item');
        item_element.innerText = item;
        
        wrapper.appendChild(item_element);
    }
}

function SetupPagination (items, wrapper, rows_per_page) {
    wrapper.innerHTML = "";

    let page_count = Math.ceil(items.length / rows_per_page);
    for (let i = 1; i < page_count + 1; i++) {
        let btn = PaginationButton(i, items);
        wrapper.appendChild(btn);
    }
}

function PaginationButton (page, items) {
    let button = document.createElement('button');
    button.innerText = page;

    if (current_page == page) button.classList.add('active');

    button.addEventListener('click', function () {
        current_page = page;
        DisplayList(items, list_element, rows, current_page);

        let current_btn = document.querySelector('.pagenumbers button.active');
        current_btn.classList.remove('active');

        button.classList.add('active');
    });

    return button;
}

DisplayList(list_items, list_element, rows, current_page);
SetupPagination(list_items, pagination_element, rows);

这是我的实体:

<?php

namespace App\Entity;

use App\Repository\TeamsRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass=TeamsRepository::class)
 */
class Teams
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $teamName;

    /**
     * @ORM\Column(type="string", length=3)
     * @Assert\NotBlank
     * @Assert\Length(
     *      min = 3,
     *      max = 3,
     *      minMessage = "Your team tag must be at least {{ limit }} characters long",
     *      maxMessage = "Your team tag cannot be longer than {{ limit }} characters"
     * )
     */
    private $teamTag;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email(
     *     message = "The email '{{ value }}' is not a valid email."
     * )
     */
    private $teamMail;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $teamReg;


    /**
     * @ORM\OneToMany(targetEntity=TeamMates::class, mappedBy="team", orphanRemoval=true)
     */
    private $teamMates;

    /**
     * @ORM\OneToMany(targetEntity=Matches::class, mappedBy="team1")
     */
    private $matches;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private ?string $teamLogo;

    public function __construct()
    {
        $this->matches = new ArrayCollection();
        $this->teamMates = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTeamName(): ?string
    {
        return $this->teamName;
    }



    public function setTeamName(string $teamName): self
    {
        $this->teamName = $teamName;

        return $this;
    }

    public function getTeamTag(): ?string
    {
        return $this->teamTag;
    }

    public function setTeamTag(string $teamTag): self
    {
        $this->teamTag = $teamTag;

        return $this;
    }

    public function getTeamMail(): ?string
    {
        return $this->teamMail;
    }

    public function setTeamMail(string $teamMail): self
    {
        $this->teamMail = $teamMail;

        return $this;
    }

    public function getTeamReg(): ?string
    {
        return $this->teamReg;
    }

    public function setTeamReg(string $teamReg): self
    {
        $this->teamReg = $teamReg;

        return $this;
    }

    /**
     * @return Collection<int, Matches>
     */
    public function getMatches(): Collection
    {
        return $this->matches;
    }

    public function addMatch(Matches $match): self
    {
        if (!$this->matches->contains($match)) {
            $this->matches[] = $match;
            $match->addTeam($this);
        }

        return $this;
    }

    public function removeMatch(Matches $match): self
    {
        if ($this->matches->removeElement($match)) {
            $match->removeTeam($this);
        }

        return $this;
    }

    /**
     * @return Collection<int, TeamMates>
     */
    public function getTeamMates(): Collection
    {
        return $this->teamMates;
    }

    public function addTeamMate(TeamMates $teamMate): self
    {
        if (!$this->teamMates->contains($teamMate)) {
            $this->teamMates[] = $teamMate;
            $teamMate->setTeam($this);
        }

        return $this;
    }

    public function removeTeamMate(TeamMates $teamMate): self
    {
        if ($this->teamMates->removeElement($teamMate)) {
            // set the owning side to null (unless already changed)
            if ($teamMate->getTeam() === $this) {
                $teamMate->setTeam(null);
            }
        }

        return $this;
    }

    public function getTeamLogo(): ?string
    {
        return $this->teamLogo;
    }

    public function setTeamLogo(string $teamLogo): self
    {
        $this->teamLogo = $teamLogo;

        return $this;
    }
}
javascript php html symfony
1个回答
1
投票

用JS来做这个:

您需要做的第一件事是以某种方式将数据从 Symfony 获取到 Javascript 前端。有很多方法可以做到这一点,通常人们使用前端框架。如果我们要使用 Vanilla,您可以考虑使用 XMLHTTPRequest 向您的 Symfony 后端发出请求。

对于 Symfony 方面,由于您使用的是 JS,因此您需要将要提供给前端的数据转换为 Javascript 可以理解的数据。这是通过使用所谓的 JSON 来完成的。你可以通过这样做来做到这一点:

<?php 

namespace App\Controller; 

use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

Class YourController extends AbstractController {

        /**
         * @Route("/my-route", methods={"GET"})
         */
        public function IndexAction(Request $request){
            $myDataFromSomewhere = ....; 
            $response = new Response(json_encode($myDataFromSomewhere), 200);
            return $response; 
        }
}

从那里您等待 XMLHttpRequest 的结果,并通过执行以下操作将其转换为 Javascript 对象:


JSON.parse(myDataFromTheGreatBeyond);

这样您就可以在 Javascript 代码中使用它了。

请注意,我尚未实际测试过任何此代码。这只是我一起吐出来的东西,为您提供从 A 点到 B 点获取数据的一般概念。此外,通过分页,通过使用内置于学说中的查询生成器创建您自己的查询,这会变得更加复杂。

例如,我构建了一个完整的 QueryHelper 类,以帮助在我从前端向 Symfony 发送请求时将查询放在一起。我的分页方法看起来像这样:

        public function paginationQuery($qb, $request){
            if($request->query->has("page") && $request->query->has("show")){
                //Convert to integer value to protect from SQL Injection
                $sanPage = intval($request->get("page")) ?: 1;
                $sanShow = intval($request->get("show")) ?: 10;
                $first = 0;
                if($sanPage > 1 ){
                    $sanPage --;
                    $first = $sanShow * $sanPage;
                }
                $qb->setFirstResult($first);
                $qb->setMaxResults($sanShow);
            };
            return $qb;
        }

我们使用分页之类的功能的原因是为了减少我们需要调用的较重记录的加载时间。并非所有数据都应该一直被调用,或者实际上通常从不被调用。它更多的是后端任务而不是前端。前端只需要指定想要哪个页面以及显示多少条记录即可。真正的魔力发生在 Symfony 方面。

当您开始处理具有数千条关系的记录,这些记录会变成数据库通过更复杂的查询返回的数千条记录时,分页是一个很好的性能增强器。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.