I don't know if you experience this kind of scenario. I use mongodb in symfony. I'm doing the document to connect it to mongodb. I create collection name Product and the fields under the product are
- id
- name
- price
I add a Form Type for validation when submitting a form using AJAX.
class ProductType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', TextType::class)
->add('price', TextType::class);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(
array(
'data_class' => 'Acme\StoreBundle\Document\Product',
'csrf_protection' => false
)
);
}
}
But I want to add a field that doesn't include from the ProductType. When the time I do that. I get an error.
"This form should not contain extra fields."
This is my ajax for submitting a form
public updateCompleted(id:string,name:string,price:string,selected:string){
let data = {name:name,price:price,selected:selected};
let _data = {product: data};
return $.ajax({
url:this.setCompletedUrl(id),
type: "PATCH",
data:_data,
async:false
});
}
The other field that I'm talking about is the selected. I want to check it in my backend the selected string that client choose. But it seems symfony want me to add this field into my document Product. Is there other way to do it?
Try to use 'mapped' option of the form field:
class ProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('price', TextType::class);
->add('selected', TextType::class, [
'mapped' => false
])
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'Acme\StoreBundle\Document\Product',
'csrf_protection' => false
)
);
}
}
In this case selected wouldn't be set to Product object, but selected value you can find in Request object.
Add your new field to FormType
. In options, set 'mapped' => false
. So that the field doesn't need to be in your document Product.
You can get post value of the new field through Form object.
Hope that helps.