简体   繁体   中英

JSON serializer output to twig file through Symfony

I'm working in Symfony and attempting to hack it a bit to simply add another conditional display, but Ive run into a wall; largely because of my unfamiliarity with serialization, and AJAX

Currently I have a fairly straightforward method to select a scanned barcode against those already in the system. Currently this works fine, as it simply checks if there are any rows and generates an error method if there are any rows.

I'm now attempting to check the status value of the result, to return a different message.

Here's what I have so far that works:

Here's the method I'm using:

    public function indexCountAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $barcode = $request->query->get('barcode');
    $items = $em->getRepository('MyBundle:Items\Item')
                ->findByBarcode($barcode);

    $response = new Response();
    $response->setContent($this->getSerializer()->serialize($items, 'json'));

    return $response;
}

The jquery in the twig is this (the path of item_index_count simply calls the above method)

<script type="text/javascript">
var verifyBarcode = function() {
    if($('#items_item_barcode').val().length != 0){
        $('#items_item_barcode').prop("readonly", true);
        $('#barcode-buttons').hide();
        jQuery.getJSON('{{ path('item_index_count') }}?' +
                         $.param({barcode: $('#items_item_barcode').val()}))
                .done(checkedBarcode);
    }
};
$("#verify-barcode").click(verifyBarcode);

var checkedBarcode = function(items) {
    if(items.length == 0){
         ... bla bla.. this works fine if there's no existing rows ..
    } else {

// this is the part that doesn't work. For some reason it's not identifying item_status - some research showed it's always bringing back "new" and never "req" even though even if there is only one line (which is always the case; its' a single barcode scan) that has that status.

        if(items.item_status == 'req'){
            $('#items_item_barcode').prop("disabled", true);
            $('#requested-barcode').removeClass('hidden');              
        }

//this works fine

        else
        {
            $('#items_item_barcode').prop("disabled", true);
            $('#existing-barcode').removeClass('hidden');
        }
    }
};

I tried bringing in the item_status variable into the twig and that seems to be identifying part of the problem, as it always brings back item_status new regardless of the status of the item, and still never brings in barcode.

Here's the main body of the twig:

    <section id="requested-barcode" class="hidden">
    <div class="panel-body callout">
        <header>This item is a request.</header>
          ---this is section never appears, even if it has status req
    </div>

    <div class="panel-body">
        <button type="button" class="btn btn-default" onclick="location.reload(true)">Cancel</button>
    </div>
</section>

<section id="existing-barcode" class="hidden">
 This section seems to work.... mostly.  This text shows

 But this line always seems to bring back the same status each time, regardless of the actual status:  
 {{ item.getItemStatus }}

    </div>

</section>

I'm pretty sure this is a fairly simple problem, I'm fairly certain the problem is within the jquery, however this is a weak spot for me and I'm unsure where to look for an answer. FWIW, doing a var_dump of $response or $items doesn't seem to do anything (Symfony makes me a little crazy; the errors just seem to disappear)


Edit:

using {{ dump(item) }} provides me with the following. For some reason it's not getting anything, but it is getting a row, but only with item_status = 'new' which is completely incorrect.

It is however, grabbing a row at the right time; this is only generated when there is an existing row:

object(MyBundle\Entity\Items\Item)#485 (17) { ["id":protected]=> NULL 
["title":protected]=> NULL 
["type":protected]=> NULL
["barcode":protected]=> NULL
["item_status":protected]=> string(3) "new"
... etc... } 

At this point I feel there's something wrong with the json, as when I run a simple query to match the $items var, I definitely get the right data.

I was able to resolve this issue. It turns out that the json feed was working fine, but that I was checking incorrectly against the new item instead of the existing item. I just needed to enter a new query in the repository to get both the item_status as well as the barcode:

    public function getExistingBarcodeItems($barcode)
{
    $em = $this->getEntityManager();
    $qb = $em->createQueryBuilder();

    $items = $qb->select('i.barcode, i.item_status')
        ->from('Bundle:Items\Item', 'i')
        ->where('i.barcode = ?1')
        ->setParameters(array(1=>$barcode))
        ->getQuery()->getResult();
    return $items;
}

and then use that in indexCountAction() in the controller:

   $barcode = $request->query->get('barcode');
   $items = $em->getRepository('Bundle:Items\Item')
        ->getExistingBarcodeItems($barcode);

And then correctly call it in the twig, calling the correct object:

   if(items.length == 0){
        $('#additional-items').removeClass('hidden');
        activateFields(['#form-volumes', '#form-editor']);
        $('#bundle_items_item_volumes').focus();
    } else {
        if(items[0].item_status == 'req'){
            $('#bundle_items_item_barcode').prop("disabled", true);
            $('#requested-barcode').removeClass('hidden');
        }
        else
        {
            $('#bundle_items_item_barcode').prop("disabled", true);
            $('#existing-barcode').removeClass('hidden');
        }
    }
};

If I recall correctly, getJSON is expecting a content-type json.

Try adding Content-Type application to your response headers like this:

$response = new Response(null, 200, ['content-type' => 'application/json']);

See if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM