Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8014421
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T19:55:41+00:00 2026-06-04T19:55:41+00:00

I have a Merchant entity with the following fields and associations:- /** * @ORM\ManyToMany(targetEntity=Category,

  • 0

I have a Merchant entity with the following fields and associations:-

/**
 * @ORM\ManyToMany(targetEntity="Category", inversedBy="merchants")
 */
public $categories;

/**
 * @ORM\ManyToMany(targetEntity="Tag", inversedBy="merchants")
 */
public $tags;

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="merchants")
 */
protected $primaryCategory;

/**
 * @ORM\ManyToOne(targetEntity="Tag", inversedBy="merchants")
 */
protected $primaryTag;

The Tags and Categories also have a ManyToMany mapping.
So we have Tag_Category, Merchant_Tag, Merchant_Category mapping tables.

Now I want to perform some ajax on these fields.

I want to allow the user to select the Primary Tag first. On the basis of the Primary Tag, ajax refresh the categories to only those which belong to this Tag and some more operations.

How can I achieve this?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T19:55:43+00:00Added an answer on June 4, 2026 at 7:55 pm

    I was able to make this work a few months back. While what a.aitboudad has shared is accurate. There are a few gotcha’s that first timers with Symfony/Sonata might face.

    Here are the steps.

    1> Extend Sonata CRUD’s edit.html.twig / base_edit.html.twig .
    For simplicity, I’ll use only the latter.
    Copy vendor/bundles/Sonata/AdminBundle/Resources/views/CRUD/base_edit.html.twig into the views folder corresponding to the MerchantAdminController – YourBundle/Resources/views/Merchant/base_edit.html.twig

    2> We need to tell our MerchantAdmin class to use this template. So we override SonataAdmin’s getEditTemplate method like this:

    public function getEditTemplate()
    {
        return 'YourBundle:Merchant:base_edit.html.twig';
    }
    

    3> Next we need to code the Ajax functionality in our base_edit.html.twig . Standard Ajax comprises of the following:

    3.1> — Create an Action in the controller for the Ajax request
    We primarily want to get a list of category IDs corresponding to a particular tag. But most likely you are just using Sonata’s CRUD Controller.

    Define your MerchantAdminController which extends CRUDController

    <?php
    
    namespace GD\AdminBundle\Controller;
    
    use Sonata\AdminBundle\Controller\CRUDController as Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use GD\AdminBundle\Entity\Merchant;
    
    class MerchantAdminController extends Controller
    {
    
    }
    

    3.2> — Tell your Admin service to use this newly created controller instead of the default CRUDController by defining it in YourBundle/Resources/config/services.yml

    gd_admin.merchant:
            class: %gd_admin.merchant.class%
            tags:
                - { name: sonata.admin, manager_type: orm, group: gd_merchant, label: Merchants }
            arguments: [null, GD\AdminBundle\Entity\Merchant, GDAdminBundle:MerchantAdmin]
    

    Notice that the 3rd argument is the name of your controller. By default it would have been null.

    3.3> — Create an Action named getCategoryOptionsFromTagAction in your controller. Your Ajax call will be to this Action.

    // route - get_categories_from_tag
    public function getCategoryOptionsFromTagAction($tagId)
        {   
            $html = ""; // HTML as response
            $tag = $this->getDoctrine()
                ->getRepository('YourBundle:Tag')
                ->find($tagId);
    
            $categories = $tag->getCategories();
    
            foreach($categories as $cat){
                $html .= '<option value="'.$cat->getId().'" >'.$cat->getName().'</option>';
            }
    
            return new Response($html, 200);
        }
    

    3.4> — Create the corresponding route in app/config/routing.yml. Remember to expose your route if you are using the FOSJsRoutingBundle (else you’ll have to hardcode which is not a good idea).

    get_categories_from_tag:
        pattern: /{_locale}/admin/gd/admin/merchant/get-categories-from-tag/{tagId}
        defaults: {_controller: GDAdminBundle:MerchantAdmin:getCategoryOptionsFromTag}
        options:
            expose: true
    

    3.5> — Make the Ajax Request and use the response

    {% block javascripts %}
        {{ parent() }}
        <script type="text/javascript">
    
            $(document).ready(function(){
                var primaryTag = $("#{{ admin.uniqId }}_primaryTag");
                primaryTag.change(updateCategories()); // Bind the function to updateCategories
                primaryTag.change(); // Manual trigger to update categories in Document load.
    
                function updateCategories(){
                    return function () {
                        var tagId = $("#{{ admin.uniqId }}_primaryTag option:selected").val();
                        var primaryCategory = $("#{{ admin.uniqId }}_primaryCategory");
                        primaryCategory.empty();
                        primaryCategory.trigger("liszt:updated");
                        var locale = '{{ app.request.get('_locale') }}';
    
                        var objectId = '{{ admin.id(object) }}'
    
                        var url = Routing.generate('get_categories_from_tag', { '_locale': locale, 'tagId': tagId, _sonata_admin: 'gd_admin.merchant', id: objectId });
                        $.post(url, { tagId: tagId }, function(data){
                            primaryCategory.empty().append(data);
                            primaryCategory.trigger("liszt:updated");
                        },"text");
    
                        primaryCategory.val("option:first").attr("selected", true);
                    };
                }
            });
        </script>
    {% endblock %}
    

    Gotcha 1: How to get the Unique ID that is appended to all Sonata elements

    Solution: Use the admin variable which will give you access to all the Admin Class’s properties including uniqId. See code on how to use it.

    Gotcha 2: How to get the Router in your JS.

    Solution: By default Symfony2 Routing doesn’t work in JS. You need to use a bundle called FOSJSRouting (explained above) and expose the route. This will give you access to the Router object within your JS too.

    I have modified my solution slightly to make this example clearer. If you notice anything wrong, please feel free to comment.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two models store and category . A store can have many categories
I have two models merchant and category with a HABM relationship so have a
I have the following models: class Merchant acts_as_authentic has_one :store accepts_nested_attributes_for :store end class
For my trading program, I have a Merchant class. A given Merchant object may
I have here a nested multidimensional array: Array ( [merchant] => Array ( [XML_Serializer_Tag]
I'm noticing strange behavior. I have merchant and order tables and doing two selects
For example, I have several different merchant clients who I handle transactions for. They
Merchant has_many Shops Shop belongs_to Merchant i.e. One merchant (Starbucks) can have many shops
I have integrated PayPal merchant account to the website , m doing it for
I have an association, Shop habtm Products Product habtm Shops Shop belongs_to Merchant For

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.