I'm working on a Symfony application to add meter values to a meter. A meter can have a set of measurements, and for each measurement I want to display a value form to enter values.
For this I have a function in a controller that creates an ArrayCollection
of new elements depending on the corresponding measurements like so:
/**
* @Route("/{id}/add", name="metervalue_add", methods={"GET","POST"})
*/
public function add(Request $request, Meter $meter): Response
{
$metervalues = new ArrayCollection();
$measurements = $meter->getMeasurements();
// create an empty metervalue for each measurement of the meter
foreach ($measurements as $measurement) {
$mv = new MeterValue();
$mv->setMeter($meter);
$mv->setMeasurement($measurement);
$metervalues->add($mv);
}
$form = $this->createForm(MeterValueAddType::class, ['metervalues' => $metervalues]);
$form->handleRequest($request);
// ... form submitting stuff
// ...
return $this->renderForm('metervalue/add.html.twig', [
'form' => $form
]);
}
The corresponding MeterValueAddType looks like
class MeterValueAddType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('metervalues', CollectionType::class, [
'entry_type' => MeterValueType::class
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
When I render the form all works fine, the empty objects are rendered as expected, I can submit the form and all data is inserted correctly in the DB, including measurement and meter ids.
However, in my template I cannot access the properties of a metervalue
object, like metervalues.measurement
or metervalue.meter
{% for metervalue in form.metervalues %}
{{ form_widget(metervalue.value) }}
{{ form_widget(metervalue.date) }}
Name of measurement: {{ metervalue.measurement.name }} <-- this throws the following error
{% endfor %}
Error: Neither the property "measurement" nor one of the methods "measurement()", "getmeasurement()"/"ismeasurement()"/"hasmeasurement()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
I don't understand why I can't access the properties in here just to display them, as they are assigned above in the controller and stored correctly in the DB on save...
The property "measurement" and a correspoding "getmeasurement()" exist and e.g. if I display all saved objects in a list I can access these
CodePudding user response:
The hint from msg was pointing me in the right direction. Had to use
{{ metervalue.vars.data.meter.name }}
to get it working! Thanks