Sunday, March 13, 2022

[FIXED] Alpine JS x-model and php parsed value

Issue

is there a way to tell Alpine Js to update its model info when passing value from php?

In this case id stays 0 and load_id and order_num stays empty string until user manually changes value even though the element has different value from php.

<div class="row" x-data="Load()" x-on:input.debounce="saveRow()">
  <div>
    <input type="text" value="<?= $load->id ?>" disabled x-model="id" />
    <input type="text" value="<?= $load->load_id ?>" x-model="load_id" />
    <input type="text" value="<?= $load->order_num ?>" x-model="order_num" />
  </div>
</div>
    function Load(){
        return {
            id: 0,
            load_id: "",
            order_num: "",
            
            saveRow(){      
                const self = this;
                $.ajax({
                    method: "POST",
                    url: "/harmonogram-api.php",
                    data: {
                        method: "saveTransport",
                        id: self.id,
                        load_id: self.load_id,
                        order_num: self.order_num,
                    }
                }).done(function(response){

                });
            }
        }
    }

Solution

If the Load() component is on the same page, then you can put the default values there:

function Load(){
    return {
        id: "<?= $load->id ?>",
        load_id: "<?= $load->load_id ?>",
        order_num: "<?= $load->order_num ?>",
        
        // ...
    }
}

If the Load() component is in an external file, then you can use x-init directive to set default values:

<div class="row" 
     x-data="Load()" 
     x-init="id = '<?= $load->id ?>'; load_id = '<?= $load->load_id ?>'; order_num = '<?= $load->order_num ?>'"
     x-on:input.debounce="saveRow()">
  <div>
    <input type="text" value="<?= $load->id ?>" disabled x-model="id" />
    <input type="text" value="<?= $load->load_id ?>" x-model="load_id" />
    <input type="text" value="<?= $load->order_num ?>" x-model="order_num" />
  </div>
</div>


Answered By - Dauros

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.