- инициализировать по дефолту, если форма не отправлялась.
Тогда остается вопрос с пагинатором - ему тоже ведь нужно передать текущие значения.
$filterForm = $this->createForm(ImageFilterType::class, [
'sortBy' => 'id',
'direction' => 'DESC',
])->handleRequest($request);
$filter = $filterForm->getData();
$images = $imageRepository->findEntities([], $filter['sortBy'], $filter['direction'], $page, 10);
class FilterModel
{
public $orderBy;
public $direction;
public function __construct()
{
$this->orderBy = 'id';
$this->direction = 'DESC';
}
}
class ImageFilterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sortBy', ChoiceType::class, [
'choices' => [
'ID' => 'id',
'label.createdAt' => 'createdAt',
'label.publishedAt' => 'publishedAt',
'label.updatedAt' => 'updatedAt',
],
'label' => 'label.sort_by',
'required' => true,
])
->add('direction', ChoiceType::class, [
'choices' => [
'label.sort_direction_ASC' => 'ASC',
'label.sort_direction_DESC' => 'DESC'
],
'label' => 'label.sort_direction',
'required' => true,
])
->add('submit', SubmitType::class, [
'label' => 'OK'
])
;
}
/**
* @inheritDoc
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => FilterModel::class,
]);
}
}
class Controller
{
public function index(int $page, Request $request, ImageRepository $imageRepository): Response
{
$filterModel = new FilterModel();
$filterForm = $this->createForm(ImageFilterType::class, $filterModel)->handleRequest($request);
$images = $imageRepository->findEntities([], $filterModel->orderBy, $filterModel->direction, $page, 10);
return $this->render('admin/gallery/image_list.html.twig', [
'images' => $images,
'filterForm' => $filterForm->createView(),
'filterModel' => $filterModel, // Если нужны параметры, то можно передать в твиг
]);
}
}
$sortBy = $request->get('sortBy', 'id');
$direction = $request->get('direction', 'DESC');