python-3.xflasktagsmaterializechips

How to get data or selected tags from Materialize Chips to Flask


I've been trying to get the tags selected in a Chips field of Materialize CSS, but without success, can anyone help me?

Full HTML Template:

<form action="{{ url_for('add') }}" method="POST">
    {{ form.csrf_token }}
       
    <span>{{ form.pecas.label }}</span>
    <div class="chips" >    
    </div>
                                   
    <input type="submit" class="btn btn-success" value="Save">
</form>
            
<script>
    $(document).ready(function() {
    $('.chips').chips(); 
        
    $('.chips-placeholder').chips({
     placeholder: 'Código da peça',
     secondaryPlaceholder: '+ Peça',
     class: 'pecas',
     name: 'pecas',
     });
     var chipInstance = M.Chips.getInstance($(".chips"));
     var pecas = chipInstance.chipsData
     console.log(pecas)  
     });
</script>
         
<script>
     $(document).ready(function(){
     $('select').formSelect();
     });
</script>  

Flask route:

@app.route("/add", methods=['POST', 'GET'])
def add():   
            
    form = AddDispositivoForm(request.form)
    if request.method == 'POST':                
        pecas = request.form.getlist("pecas")
        print(pecas)   
                
        return redirect(url_for('index'))
    return render_template("add.html", form=form)

Everything I tried returned an empty list [ ]


Solution

  • You could use a hidden field like the following, to carry the chips data:
    <input type="hidden" name="pecas" id="pecasInput">

    Then you should define a js function to extract the tags and populate the hidden field with the JSON string of tags.

    function updateHiddenInput() {
        var chipInstance = M.Chips.getInstance($('.chips'));
        $('#pecasInput').val(JSON.stringify(chipInstance.chipsData));
    }
    

    After this, make sure this function runs on submit of the form, one way to do this is with another function like:

    $('#yourFormID').on('submit', function(e) {
        updateHiddenInput();
    });
    

    Then at the backend you can get the values with:

    if request.method == 'POST':                
        pecas_json = request.form.get("pecas", "[]")
        pecas = json.loads(pecas_json)
    

    The pecas will have a list of dictionaries with the tags as a keys.