#php #forms #symfony
#php #формы #symfony
Вопрос:
У меня есть следующий код.
$form = $this->createFormBuilder()
->add('distributor', 'entity', array(
'class' => 'AdminBundle:Customers',
'query_builder' => function(EntityRepository $repository) {
return $repository->createQueryBuilder('c')
->where('c.customerType =:type')
->Andwhere('c.status =:status')
->andWhere('c.district =:district')
->setparameter('status', '1')
->setparameter('type', '1')
->setparameter('district', $this->get("security.context")->getToken()->getUser()->getCustomer()->getDistrict()->getId())
;
},
'property' => 'customerName',
'empty_value' => 'Select Distributor',
'multiple' => FALSE,
'expanded' => FALSE,
'required' => TRUE,
)
)
->add('excel_file', 'file'
->getForm();
Когда я собираюсь использовать элемент distributor в twig, подобный этому
{{ form_widget(form.distributor,{ 'attr': {'class': 'input-box'} }) }}
выдается сообщение об ошибке…
Неустранимая ошибка: использование $ this вне контекста объекта
Как использовать $ this в symfony QueryBuilder с form?
Спасибо, Ракхита
Ответ №1:
Вероятно, вы используете PHP 5.3, и поэтому вы не можете использовать $this
в закрытии. Чтобы устранить эту проблему, выполните следующее:
$id = $this->get("security.context")->getToken()->getUser()->getCustomer()->getDistrict()->getId();
$form = $this->createFormBuilder()
->add('distributor', 'entity', array(
'class' => 'AdminBundle:Customers',
'query_builder' => function(EntityRepository $repository) use ($id) {
return $repository->createQueryBuilder('c')
->where('c.customerType =:type')
->Andwhere('c.status =:status')
->andWhere('c.district =:district')
->setparameter('status', '1')
->setparameter('type', '1')
->setparameter('district', $id)
;
},
'property' => 'customerName',
'empty_value' => 'Select Distributor',
'multiple' => FALSE,
'expanded' => FALSE,
'required' => TRUE,
)
)
->add('excel_file', 'file'
->getForm();
Комментарии:
1. Привет, Деннис, спасибо за быстрый ответ, и я уже пробовал это, и он говорит, что id является неопределенной переменной.
2. Это невозможно. Вы заметили
use ($id)
в закрытии?