问题
I'm new in symfony2 ver 2.7: I would like to create registration number in form with data from count rows in existing table.
It's OK when i create in PatientController and show the result in twig format. But i need show the result in text type form. I write in PatientRepository a function:
public function getNumberPatient()
{
$qb = $this->createQueryBuilder('name')
->select('COUNT(name)');
return (int)$qb->getQuery()
->getSingleScalarResult();
}
And in my Entity file to generate like this:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('dateBirth', 'date', array(
'years' => range(date('Y'), date('Y', strtotime('-50 years'))),
'required' => TRUE,
))
->add('regCode', 'text', array(
'required' => TRUE,
'data' => function(PatientRepository $r){
return $r->getNumberPatient();
},
I have a trouble when i call this function from PatientEntity. Is it Possible?
I did create function with:
'query_builder' => function(PatientRepository $r){
return $r->getNumberPatient();
but it give an error
The option "query_builder" does not exist. Defined options are: "action",
Please help me..
回答1:
There are multiple ways to do it:
- You can get the data in controller, then pass it to form, like this:
example in controller:
public function someAction()
{
$data = $em->getRepository(...)->getNumberPatient();
$form = $this->createForm(new MyFormType, NULL_OR_OBJECT, [
'text_data' => $data
]);
...
}
MyFormType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$data = $options['text_data'];
$builder
->add('regCode', 'text', ['data' => $data])
...
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['text_data' => null]);
}
- Another way, declare your form type as a service, inject the entity manager:
example:
class MyFormType extends AbstractType
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
// use it like $this->entityManager->...
}
- another way, pass the entityManager to form like 1-option, then get by
$options
array, like this$entityManager = $options['entityManager']
, or you can even pass the entityManager to constructor.. Here you can see it..
来源:https://stackoverflow.com/questions/30744798/symfony2-how-to-call-functions-in-repository-class-from-type