2016-02-17 1 views
1

У меня есть backend на SonataAdminBundle 2.4.*@dev версия.Данные по обновлению Symfony 2 на экспорт

Перед обновлением и ядром symfony от 2,7 до 2,8 мой код работал.

Объяснение: У меня есть список подписчиков, у которых есть флаг isNew для отдельного экспорта новых или старых пользователей. По умолчанию 1, при экспорте необходимо изменить его на 0, если в списке есть новые пользователи.

Но теперь это не сработает. Потому что, если фильтр сетки задается этим полем isNew и экспорта, в поле БД изменяется раньше, и позже

return $this->get('sonata.admin.exporter')->getResponse(
     $format, 
     $filename, 
     $this->admin->getDataSourceIterator() 
    ); 

getDataSourceIterator принимать данные из БД не от результата. Таким образом, новых пользователей нет, а файл пуст.

Как обновить данные после экспорта, есть идеи?

UPDATE:

Функция экспорта:

/** 
* Export data to specified format. 
* 
* @param Request $request 
* 
* @return Response 
* 
* @throws AccessDeniedException If access is not granted 
* @throws \RuntimeException  If the export format is invalid 
*/ 
public function exportAction(Request $request = null) 
{ 
    $request = $this->resolveRequest($request); 

    $this->admin->checkAccess('export'); 

    $format = $request->get('format'); 

    $allowedExportFormats = (array) $this->admin->getExportFormats(); 

    if (!in_array($format, $allowedExportFormats)) { 
     throw new \RuntimeException(
      sprintf(
       'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', 
       $format, 
       $this->admin->getClass(), 
       implode(', ', $allowedExportFormats) 
      ) 
     ); 
    } 

    $filename = sprintf(
     'export_%s_%s.%s', 
     strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)), 
     date('Y_m_d_H_i_s', strtotime('now')), 
     $format 
    ); 


    //my code to update field isNew of subscribers 
    $this->get('cfw.subscription')->processExportEmails($controller->admin->getFilterParameters()); 

    return $this->get('sonata.admin.exporter')->getResponse(
     $format, 
     $filename, 
     $this->admin->getDataSourceIterator() 
    ); 
} 
+0

Не могли бы вы показать мне всю функцию (до возвращения)? – chalasr

+1

это функция связки – dmma

+0

Извините, я ошибся, функция переплетена – dmma

ответ

0

Хорошо, я нашел решение, может быть, кто-то знает лучше, пожалуйста, напишите здесь. Я решил обновить данные в прослушивателе на Terminate. Смотрите код:

службы конфигурации:

sonata.admin.subscription.listener: 
     class: SiteBundle\Listener\ExportSubscriptionListener 
     arguments: [@service_container] 
     tags: 
      - { name: kernel.event_listener, event: kernel.controller, method: onKernelController } 
      - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate } 

в контроллере я удалил перекрытый метод exportAction() и добавил немного метод

/** 
* @return AdminInterface 
*/ 
public function getAdmin() 
{ 
    return $this->admin; 
} 

ExportSubscriptionListener:

use Symfony\Component\DependencyInjection\ContainerInterface; 
use Symfony\Component\HttpKernel\Event\FilterControllerEvent; 
use Sonata\AdminBundle\Controller\CRUDController; 
use SiteBundle\Controller\SubscriptionAdminController; 

class ExportSubscriptionListener 
{ 
    /** 
    * @var CRUDController 
    */ 
    protected $controller; 

    /** 
    * @var ContainerInterface 
    */ 
    protected $container; 

    public function __construct(ContainerInterface $container) 
    { 
     $this->container = $container; 
    } 

    public function onKernelController(FilterControllerEvent $event) 
    { 
     $this->controller = $event->getController(); 
    } 

    /** 
    * Update new subscribers on export 
    */ 
    public function onKernelTerminate() 
    { 
     $controller = $this->controller[0]; 

     if (!$controller instanceof SubscriptionAdminController) { 
      return; 
     } 

     if ($this->controller[1] !== 'exportAction') { 
      return; 
     } 

     //here we update in service data 
     /** $var SubscriptionAdminController $controller */ 
     $this->container->get('service.subscription')->processExportEmails($controller->getAdmin()->getFilterParameters()); 
    } 
} 

и обновление данных в эксплуатации:

/** 
* @param array $subscriptions 
*/ 
public function processExportEmails(array $filterParameters) 
{ 
    $criteria = []; 

    if(!empty($filterParameters['locale']) && $filterParameters['locale']['value'] !== "") { 
     $criteria['locale'] = $filterParameters['locale']['value']; 
    } 

    if(!empty($filterParameters['new']) && $filterParameters['new']['value'] !== "") { 
     $criteria['new'] = $filterParameters['new']['value']; 
    } 

    $subscriptionRepository = $this->getRepositorySubscription(); 

    $subscriptions = null; 
    if (count($criteria) > 0) { 
     $subscriptions = $subscriptionRepository->findBy($criteria); 
    } else { 
     $subscriptions = $subscriptionRepository->findAll(); 
    } 

    /** @var array|null $subscriptions */ 
    foreach ($subscriptions as $subscription) { 
     /** @var Subscription $subscription */ 
     if ($subscription->isNew()) { 
      $subscription->setNew(false); 
      $this->getEntityManager()->persist($subscription); 
     } 
    } 

    $this->getEntityManager()->flush(); 
}