1

Есть таблица в которой выводятся данные из 2 таблиц, как в эту таблицу добавить еще одно поле у которого информация была бы в зависимости от условий 2 других таблиц или одной, к примеру мне надо добавить поле Trial в котором была бы информация на основании поля Price, Если поле Price больше 0 то в Trial вставляем одно значение если 0 то другое. В метод configureListFields я добавил поле Trial таким образом: ->add('trial') оно добавилось, а теперь как его наполнить данными, вот весь код:

namespace AdminBundle\Admin;

use IntlDateFormatter;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;

class PurchaseAdmin extends AbstractAdmin
{
    protected $datagridValues = [
        '_page'       => 1,
        '_sort_order' => 'DESC',
        '_sort_by'    => 'createdAt',
    ];

    protected $accessMapping = [
        'refund' => 'REFUND',
    ];

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);

        $rootAlias = $query->getRootAliases()[0];
        $query->leftJoin($rootAlias.'.paymentTransaction', 'pt');
        $query->leftJoin($rootAlias.'.language', 'll');
        $query->addSelect('pt, ll');


        return $query;
    }

    public function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection);
        $collection->remove('delete');
        $collection->remove('create');
        $collection->remove('edit');
        $collection->add('refund', $this->getRouterIdParameter().'/refund');
        $collection->add('studentInfo', $this->getRouterIdParameter().'/student-info');
    }

    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add(
                'teacher', null, [
                             'show_filter' => true
                         ]
            )
            ->add(
                'student', null, [
                             'show_filter' => true
                         ]
            )
            ->add(
                'language', null, [
                              'show_filter' => true
                          ]
            )
            ->add('lessonLength')
            ->add('lessons')
            ->add(
                'status', null, [], 'choice', [
                            'choices' => [
                                0 => 'created',
                                1 => 'paid',
                                2 => 'used',
                                3 => 'refunded',
                            ],
                        ]
            );
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier(
                'id',
                null,
                [
                    'route' => [
                        'name' => 'show'
                    ]
                ]
            )
            ->add('statusText')
            ->add('teacher')
            ->add('student')
            ->add(
                'studentInfo',
                'string',
                [
                    'template' => ':CRUD:list__action_student_info.html.twig'
                ]
            )
            ->add('language')
            ->add('lessonLength')
            ->add('lessons')
            ->add('lessonsLeft')
            ->add('price')
            ->add('trial')
            ->add('teacher.currency', null, ['label' => 'Currency'])
            ->add('paymentTransaction')
            ->add(
                'createdAt', 'datetime', [
                               'dateType' => IntlDateFormatter::SHORT,
                               'timeType' => IntlDateFormatter::SHORT,
                           ]
            )
            ->add(
                'updatedAt', 'datetime', [
                               'dateType' => IntlDateFormatter::SHORT,
                               'timeType' => IntlDateFormatter::SHORT,
                           ]
            )
            ->add(
                '_action',
                null,
                [
                    'actions' => [
                        'show'   => [],
                        'refund' => [
                            'template' => ':CRUD:list__action_refund.html.twig'
                        ],
                    ]
                ]
            );
    }

    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('id')
            ->add('price')
            ->add('lessonLength')
            ->add('lessons')
            ->add('lessonsLeft')
            ->add('commission')
            ->add('status')
            ->add('createdAt')
            ->add('updatedAt');
    }

    /**
     * @param ShowMapper $showMapper
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('teacher')
            ->add('student')
            ->add('language')
            ->add('price')
            ->add('teacher.currency', null, ['label' => 'Currency'])
            ->add('lessonLength')
            ->add('lessons')
            ->add('lessonsLeft')
            ->add('commission')
            ->add('statusText')
            ->add('paymentTransaction')
            ->add('createdAt')
            ->add('updatedAt');
    }

    public function getTemplate($name)
    {
        if ($name === 'refund') {
            return ':Purchase:base_refund.html.twig';
        }

        return parent::getTemplate($name);
    }

}

1 ответ 1

1

Вам нужно сохранять данные о Trial перед отправкой в ДБ. Либо стоит это сделать черех хук [preUpdate][1].

public function preUpdate($purchase)
{
    $purchase.setTrial((boolean)$purchase.getPrice())
}

Либо в Вашем CRUDController реализовать заполнение поля trial (строчку $collection->remove('create'); наверное надо будет удалить)

public function createAction()
 {
     $object = $this->admin->getSubject();
     $object->setTrial((boolean)$object->getPrice());
     return parent::createAction();
 }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.