Home > Back-end >  How to use Ajax for nested form on active admin rails
How to use Ajax for nested form on active admin rails

Time:07-17

Please help me out with this problem. I am new on rails

  • I am trying to use the ajax method to get values on the active admin nested form. But only the top of the form gets dynamic values. After changing values on the top one form on the nested form then ajax makes a request then it changes the values(i.e. update the form values). But after adding a new buy line item then ajax makes a request but doesn't update the values on the form i.e.same values for every new buy line item.

my js code app/assets/javascripts/buys.js


    // for nested buyline items of buys resources
    $('.lineItem').change(function () {
        $.ajax({
            url: '/admin/get_buys_buy_line_item',
            type: 'GET',
            dataType: "json",
            data: {
                product_id: $('.lineBuyProduct').val(),
                buy_quantity: $(".lineBuyQuantity").val(),
                buy_quantity_unit: $(".lineBuyUnit").val(),
                buy_price: $(".lineBuyAmount").val(),
            },
            success: (data) => {
                alert(data);
                // if (data == null) {
                //     document.getElementById('lineQuantity').value = ' ';
                //     document.getElementById('lineAmount').value = ' ';
                // }
                // else {
                // document.getElementsByClassName("linebuyQuantity").value = data['1'];
                // document.getElementsByClassName('linebuyAmount').value = data[0];
                // console.log("Dynamic select OK!")
                // }
            }
        });
    });
});

My active admin forms

f.inputs 'Line Items', class: "lineItem" do
      table do
        thead do
          tr do
            th 'S.N', class: 'form-table__col'
            th 'Product', class: 'form-table__col'
            th 'Quantity', class: 'form-table__col'
            th 'Unit', class: 'form-table__col'
            th 'Amount', class: 'form-table__col'
            th 'Expiry Date', class: 'form-table__col'
            th 'Destroy', class: 'form-table__col'
          end
        end
      end
      f.has_many :buy_line_items, new_record: 'Add Buy Line Item', heading: false, allow_destroy: true do |x|
        x.input :sn, label: false
        x.input :product, label: false, as: :select2, collection: Product.drop_down_options,
                          input_html: { required: true, class: 'lineBuyProduct' }
        x.input :buy_quantity, label: false, input_html: { required: true, class: 'lineBuyQuantity' }
        x.input :buy_quantity_unit, label: false, collection: Unit.all.pluck(:name),
                                    input_html: { class: 'lineBuyUnit' }
        x.input :buy_price, label: false,
                            input_html: { required: true, class: 'lineBuyAmount' }
        x.input :expiry_date, as: :date_picker, input_html: { style: 'width:auto' }, label: false
      end
    end

Some of my screenshots of how my program behaves and what my expectations are

So, please expert team help me to slove this problem.

CodePudding user response:

If you want to send the data to create a new entity(record), you need to use the http POST method: https://api.jquery.com/jquery.post/ The GET request it just retrieves an already existing entity. Probably that's why you can read some data after an ajax call, but it's not updated.

More about the differences between GET and POST methods: When should I use GET or POST method? What's the difference between them?

If this fix doesn't work, check the rails logs.

CodePudding user response:

I have never used anything related to Ruby, and I'm not completely sure if I understood your question. I'm assuming you have problems with the AJAX behavior for new items in the list. Considering that, I think your problem could be related to attaching the "change" event to the new items. I think there might be many different other ways to get the behavior you want, but I will just elaborate on your solution using JS.

From the activeAdmin's code you can see they trigger an event called "has_many_add:after" when a new item was successfully added to its parent. Considering that, I would try changing your Javascript code to:

// for nested buyline items of buys resources
$("#buy_line_items").on("has_many_add:after", function(event, fieldset, parent){
    fieldset.change(function () {
        $.ajax({
            url: '/admin/get_buys_buy_line_item',
            type: 'GET',
            dataType: "json",
            data: {
                product_id: $(this).find('.lineBuyProduct').val(),
                buy_quantity: $(this).find(".lineBuyQuantity").val(),
                buy_quantity_unit: $(this).find(".lineBuyUnit").val(),
                buy_price: $(this).find(".lineBuyAmount").val()
             },
             success: (data) => {
                 alert(data);
                 // if (data == null) {
                 //     document.getElementById('lineQuantity').value = ' ';
                 //     document.getElementById('lineAmount').value = ' ';
                 // }
                 // else {
                 // document.getElementsByClassName("linebuyQuantity").value = data['1'];
                 // document.getElementsByClassName('linebuyAmount').value = data[0];
                 // console.log("Dynamic select OK!")
                 // }
             }
         });
    });
});

I'm very confident that this will work, mainly because I don't have how to try it (if you give me the generated HTML maybe it'd help me). You can try it and reach back to see if it worked or if any adjustment is required.

You might want to change your commented lines accordingly. Also about the identifier "#buy_line_items" I'm not sure if it exists in the rendered HTML so you might need to adjust that as well.

  • Related