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..
There are multiple ways to do it:
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]);
}
example:
class MyFormType extends AbstractType
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
// use it like $this->entityManager->...
}
$options
array, like this $entityManager = $options['entityManager']
, or you can even pass the entityManager to constructor.. Here you can see it..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.