在Shopware 6中,您可以通过以下步骤将类别ID发送给AJAX,并根据该ID展示产品:
custom_template.html.twig
的模板文件。{% block content %}
<div>
<select id="categorySelect">
{% for category in categories %}
<option value="{{ category.id }}">{{ category.name }}</option>
{% endfor %}
</select>
<button onclick="getProducts()">Get Products</button>
</div>
<div id="productContainer">
<!-- Products will be displayed here -->
</div>
<script>
function getProducts() {
var categoryId = document.getElementById('categorySelect').value;
// Send AJAX request to fetch products based on category ID
// You can use any AJAX library or native JavaScript methods
// Example using jQuery AJAX
$.ajax({
url: '/get-products',
type: 'POST',
data: { category_id: categoryId },
success: function(response) {
// Handle the response and display products
var products = JSON.parse(response);
var productContainer = document.getElementById('productContainer');
// Render products in the productContainer
// You can use any front-end framework or native JavaScript to render the products
}
});
}
</script>
{% endblock %}
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\Framework\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* @RouteScope(scopes={"api"})
*/
class ProductController extends AbstractController
{
/**
* @Route("/get-products", name="get_products", methods={"POST"})
*/
public function getProducts(Request $request): JsonResponse
{
$categoryId = $request->request->get('category_id');
// Use the received category ID to fetch products from the database
// You can use Shopware's EntityRepository or any other ORM methods
// Example code using Shopware's EntityRepository
$entityManager = $this->container->get('doctrine.orm.default_entity_manager');
$productRepository = $entityManager->getRepository(ProductEntity::class);
$products = $productRepository->findBy(['categoryId' => $categoryId]);
// Return the products as JSON response
return new JsonResponse(json_encode($products));
}
}
请注意,这只是一个简化的示例,实际实现可能会根据您的项目结构和需求有所不同。确保在实际开发中遵循Shopware 6的最佳实践和文档。
相关产品和文档链接:
领取专属 10元无门槛券
手把手带您无忧上云