Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

php - Symfony2 use with Ajax, to get the result of a query in doctrine

UPDATE

My function in repository of Ads

    public function findByExceptOwner($paramFetcher)
    {

        $query = $this->getEntityManager()->createQueryBuilder('ad');

        // parametros iniciais da query: status, departure de destination
        $query->select('ad');

        if(array_key_exists('type', $paramFetcher)){
            $query->from('DelivveWebBundle:' . $paramFetcher['type'], 'ad');
        }else{
            $query->from('DelivveWebBundle:Ad', 'ad');
        }

        $query
            ->where('ad.owner <> :ownerId')
            ->andWhere($query->expr()->eq('ad.status', ':status'))
            ->andWhere('ad.dateFinal <= :today')
            ->setParameter('ownerId', $paramFetcher['ownerId'])
            ->setParameter('status', 'new')
            ->setParameter('today', new DateTime("now"));

        if (array_key_exists('departure',$paramFetcher)) {
            $departureArray = preg_split('/ - /', $paramFetcher['departure']);
            $departureCityArray = preg_split('/,/', $departureArray[count($departureArray) - 2]);
            $departureUFArray = preg_split('/,/', $departureArray[count($departureArray) - 1]);
            $departure = $departureCityArray[count($departureCityArray) - 1] . ' - ' . $departureUFArray[0];
            $query
                ->andWhere($query->expr()->like('ad.departure', ':departure'))
                ->setParameter('departure', "%{$departure}%");
        }

        if (array_key_exists('destination',$paramFetcher)) {
            $destinationArray = preg_split('/ - /', $paramFetcher['destination']);
            $destinationCityArray = preg_split('/,/', $destinationArray[count($destinationArray) - 2]);
            $destinationUFArray = preg_split('/,/', $destinationArray[count($destinationArray) - 1]);
            $destination = $destinationCityArray[count($destinationCityArray) - 1] . ' - ' . $destinationUFArray[0];
            $query
                ->andWhere($query->expr()->like('ad.destination', ':destination'))
                ->setParameter('destination', "%{$destination}%");
        }

        // raio de busca com centro nas coordenadas de departure
        if (array_key_exists('departure_latitude', $paramFetcher) && array_key_exists('departure_longitude', $paramFetcher) && array_key_exists('radius', $paramFetcher)) {
            $query
                ->andWhere('earth_distance_operator(earth_box(ll_to_earth(:departure_lat, :departure_lon), :radius), '@>', ll_to_earth(ad.departureLatitude, ad.departureLongitude)) = true')
                ->setParameter('departure_lat', floatval($paramFetcher['departure_latitude']), DoctrineDBALTypesType::FLOAT)
                ->setParameter('departure_lon', floatval($paramFetcher['departure_longitude']), DoctrineDBALTypesType::FLOAT)
                ->setParameter('radius', floatval($paramFetcher['radius']) / 1.609, DoctrineDBALTypesType::FLOAT);
        }

        // raio de busca com centro nas coordenadas de destionation
        if (array_key_exists('destination_latitude', $paramFetcher) && array_key_exists('destination_longitude', $paramFetcher) && array_key_exists('radius', $paramFetcher)) {
            $query
                ->andWhere('earth_distance_operator(earth_box(ll_to_earth(:destination_lat, :destination_lon), :radius), '@>', ll_to_earth(ad.destinationLatitude, ad.destinationLongitude)) = true')
                ->setParameter('destination_lat', floatval($paramFetcher['destination_latitude']), DoctrineDBALTypesType::FLOAT)
                ->setParameter('destination_lon', floatval($paramFetcher['destination_longitude']), DoctrineDBALTypesType::FLOAT)
                ->setParameter('radius', floatval($paramFetcher['radius']) / 1.609, DoctrineDBALTypesType::FLOAT);
        }

        return $query->getQuery()->getResult();
    }

I have the following method in the controller

public function searchAdsAction(Request $request)
{
    $this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');

    $em = $this->getDoctrine()->getManager();

    $owner = $this->getUser();

    $parameter = array();
    $parameter["departure_latitude"] = $request->request->get('departure_lat');
    $parameter["departure_longitude"] = $request->request->get('departure_long');
    $parameter["radius"] = Constant::RADIUS;
    $parameter["ownerId"] = $owner->getId();
    $entities = $em->getRepository('DelivveWebBundle:Ad')->findByExceptOwner($parameter);

    return new JsonResponse($entities);
}

my route this written as follows

search_ads:
pattern: /ad/search
defaults: { _controller: DelivveWebBundle:Ad:searchAds }

my function ajax

$(window).load(function() {
        var url = window.location.href;
        var urlArray = url.split("/");
        var path = urlArray[0]+"//"+urlArray[2];

        var departureLatitude = $("#bundle_ad_departureLatitude").val();
        var departureLongitude = $("#bundle_ad_departureLongitude").val();

        $.post(path+"{{ path('search_ads') }}",
            {departure_lat: departureLatitude, departure_long: departureLongitude},
            function (entities){
                alert("success ");
                console.log(entities);

                $(".panel-foot-information").remove();

                $div = "<div class='panel-foot-information row big-not-visible'>";

                 if (entities != null){
                 $div = $div + "<table id='ads'><thead><tr><th>Departure</th><th>Destination</th></tr></thead><tbody>";
                 $.each( entities, function( key, value ) {
                     $div = $div + "<tr class='ad-tr'>";
                     $div = $div + "<td class='hidden'><input type='hidden' id='idLat' value="+ value.departureLatitude +"/></td>";
                     $div = $div + "<td class='hidden'><input type='hidden' id='idLong' value="+ value.departureLongitude +"/></td>";
                     $div = $div + "<td>"+ value.owner.username +"</td>";
                     $div = $div + "<td>"+ value.departure +"</td>";
                     $div = $div + "<td>"+ value.destination +"</td>";
                     $div = $div + "<td class='packageType'>"+ value.packageType +"</td>";
                     $div = $div + "<td class='transportation'>"+ value.transportation +"</td>";
                     $div = $div + "<td class='price'>"+ value.price +"</td>";
                     $div = $div + "<td class='date'>"+ value.date + " - " + value.dateFinal +"</td>";
                     $div = $div + "</tr>";
                     alert($div)
                 });
                 $div = $div + "</tbody></table></div>";
                 }
                 $div = $div + "</div>";
                 $(".panel-middle").append($div);
            }, "json"
        );
    });

I tried another solution for those who saw my anterirormente question.

After much searching and doubt taken by several guys in stackoverflow could reach it, but when I go return on ajax he has a photo of the object type, this makes no sense.

Anyone know how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error was in the JasonResponse could not serialize my class, then manipulated it to iterate power over the result in jQuery.

public function searchAdsAction(Request $request)
{
    ...
    $data = array();
    foreach($entities as $ad){
        $adArray = array();
        $adArray["departureLatitude"] = $ad->getDepartureLatitude();
        $adArray["departureLongitude"] = $ad->getDepartureLongitude();
        $adArray["owner_username"] = $ad->getOwner()->getUserName();
        $adArray["departure"] = $ad->getDeparture();
        $adArray["destination"] = $ad->getDestination();
        $adArray["packageType"] = $ad->getPackageType();
        $adArray["price"] = $ad->getPrice();
        $data[] = $adArray;
    }

    return new JsonResponse($data);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...