You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Akeneo中添加按钮以显示产品内的相同属性组?

Hey there! Since you already nailed adding a custom button to the product edit form following the Akeneo cookbook, expanding to add this new button that shows duplicate attribute groups for the current product should feel pretty familiar. Let’s walk through the steps tailored to this specific use case:

Step 1: Create the Action Class for Duplicate Group Logic

First, make a new action class that handles fetching and identifying duplicate attribute groups from the product. This will be the backend logic that your button triggers:

<?php

namespace Acme\Bundle\CustomBundle\Action;

use Akeneo\Pim\Enrichment\Component\Product\Model\ProductInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class ShowDuplicateAttributeGroupsAction
{
    public function __invoke(Request $request, ProductInterface $product): JsonResponse
    {
        // Grab all attribute groups associated with the product
        $attributeGroups = $product->getAttributeGroups();
        
        $duplicateGroupCodes = [];
        $seenGroupCodes = [];

        // Loop through groups to find duplicates
        foreach ($attributeGroups as $group) {
            $groupCode = $group->getCode();
            if (in_array($groupCode, $seenGroupCodes)) {
                // Only add once to duplicates list
                if (!in_array($groupCode, $duplicateGroupCodes)) {
                    $duplicateGroupCodes[] = $groupCode;
                }
            } else {
                $seenGroupCodes[] = $groupCode;
            }
        }

        return new JsonResponse([
            'duplicates' => $duplicateGroupCodes,
            'message' => empty($duplicateGroupCodes) 
                ? 'No duplicate attribute groups found for this product.' 
                : 'Duplicate attribute groups detected: ' . implode(', ', $duplicateGroupCodes)
        ]);
    }
}
Step 2: Register the Action as a Service

Add this new class to your services.yaml (or equivalent service config) so Akeneo recognizes it as a product edit action:

services:
    Acme\Bundle\CustomBundle\Action\ShowDuplicateAttributeGroupsAction:
        tags:
            - { name: 'akeneo.action', type: 'product_edit', alias: 'show_duplicate_attribute_groups' }
Step 3: Add the New Button to the Product Edit Template

Update your product edit form template override to include the new button. You’ll add this right alongside the first custom button you created:

{# In your overridden product edit template (e.g., AcmeCustomBundle/Resources/views/Product/Edit/form.html.twig) #}
{% block product_edit_actions %}
    {# Keep the original actions plus your first custom button #}
    {{ parent() }}

    <button type="button" class="AknButton AknButton--secondary" id="show-duplicate-groups-btn">
        Show Duplicate Attribute Groups
    </button>
{% endblock %}
Step 4: Add JavaScript to Handle Button Clicks

Write a small JS snippet to bind a click event to your new button, call the backend action, and display the results using Akeneo’s built-in notification system:

// In your custom JS file (e.g., AcmeCustomBundle/Resources/public/js/product-edit-custom.js)
document.addEventListener('DOMContentLoaded', () => {
    const duplicateBtn = document.getElementById('show-duplicate-groups-btn');
    const productId = document.querySelector('[data-product-id]').dataset.productId;

    duplicateBtn.addEventListener('click', async () => {
        try {
            const response = await fetch(`/rest/products/${productId}/actions/show_duplicate_attribute_groups`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            const result = await response.json();

            // Show feedback to the user
            if (result.duplicates.length > 0) {
                Akeneo.UI.notification.showSuccess(result.message);
            } else {
                Akeneo.UI.notification.showInfo(result.message);
            }
        } catch (error) {
            Akeneo.UI.notification.showError('Oops! Failed to load duplicate attribute groups.');
            console.error('Error fetching duplicates:', error);
        }
    });
});
Quick Notes to Keep in Mind
  • Make sure your bundle is properly registered and your assets are built (if you added new JS) using Akeneo’s asset commands.
  • If you run into routing issues, double-check the akeneo.action tag configuration—Akeneo should auto-generate the route for your action, but verifying with bin/console debug:router can help.

Since you already have experience with the cookbook’s button setup, this should follow the same pattern—just focused on the duplicate attribute group logic. Let me know if you hit any specific roadblocks!

内容的提问来源于stack exchange,提问作者FortuneSoldier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:08:27