New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default value for a form field #249

Closed
hisie opened this Issue Aug 23, 2011 · 13 comments

Comments

Projects
None yet
7 participants
@hisie

hisie commented Aug 23, 2011

I would like to have a default value in a form field, but i am not being lucky. I have readen the SonataAdminBundle docs and the Forms one and i supose i have todo:

public function configureFormFields(FormMapper $formMapper)
{
    $formMapper
      ->add('padre', 'hidden', array('data'=>$this->getRequest()->get('padre')), array( ))
      ->add('hijo', 'sonata_type_model', array('required'=>false, ), array('edit' => 'list'))
      ->add('orden');

}

So the data will be set default to the request, But i does not work.

I have tried to instantiate the object in the formBuilder (overwriting it in the inherited class ContenidoContenidoAdmin):

public function getFormBuilder($object = null, $options = array())
{
    if (!$object) {
        $object = $this->getSubject();
    }

    if (!$object) {
        $object = $this->getNewInstance();
        $padre = $this->getModelManager()->findOne('CarlaCmsBundle:Contenido', $this->getRequest()->get('padre'));
        $object->setPadre($padre);
        echo "debug";
    }

    // add the custom inline validation option
    $metadata = $this->validator->getMetadataFactory()->getClassMetadata($this->class);
    $metadata->addConstraint(new \Sonata\AdminBundle\Validator\Constraints\InlineConstraint(array(
        'service' => $this,
        'method'  => 'validate'
    )));

    $formBuilder = $this->getFormContractor()->getFormBuilder(
        $this->getUniqid(),
        array_merge($this->formOptions, $options)
    );

    $formBuilder->setData($object);

    $this->defineFormBuilder($formBuilder);

    return $formBuilder;
}

Debug is echoed, but object has no "$padre" value.

I am bit lost, on how to declare predefined data in this admin generator. Thank you.

@rande

This comment has been minimized.

Show comment
Hide comment
@rande

rande Aug 23, 2011

Member

The issue is something you have to figure out from the Form Framework. If you want to define custom value, then set value right into the object. You can't set default value from the form type.

On Aug 23, 2011, at 9:24 PM, hisie wrote:

I would like to have a default value in a form field, but i am not being lucky. I have readen the SonataAdminBundle docs and the Forms one and i supose i have todo:

public function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('padre', 'hidden', array('data'=>$this->getRequest()->get('padre')), array( ))
->add('hijo', 'sonata_type_model', array('required'=>false, ), array('edit' => 'list'))
->add('orden');

}

So the data will be set default to the request, But i does not work.

I have tried to instantiate the object in the formBuilder (overwriting it in the inherited class ContenidoContenidoAdmin):

public function getFormBuilder($object = null, $options = array())
{
if (!$object) {
$object = $this->getSubject();
}

   if (!$object) {
       $object = $this->getNewInstance();
       $padre = $this->getModelManager()->findOne('CarlaCmsBundle:Contenido', $this->getRequest()->get('padre'));
       $object->setPadre($padre);
       echo "debug";
   }

   // add the custom inline validation option
   $metadata = $this->validator->getMetadataFactory()->getClassMetadata($this->class);
   $metadata->addConstraint(new \Sonata\AdminBundle\Validator\Constraints\InlineConstraint(array(
       'service' => $this,
       'method'  => 'validate'
   )));

   $formBuilder = $this->getFormContractor()->getFormBuilder(
       $this->getUniqid(),
       array_merge($this->formOptions, $options)
   );

   $formBuilder->setData($object);

   $this->defineFormBuilder($formBuilder);

   return $formBuilder;

}
Debug is echoed, but object has no "$padre" value.

I am bit lost, on how to declare predefined data in this admin generator. Thank you.

Reply to this email directly or view it on GitHub:
#249

Member

rande commented Aug 23, 2011

The issue is something you have to figure out from the Form Framework. If you want to define custom value, then set value right into the object. You can't set default value from the form type.

On Aug 23, 2011, at 9:24 PM, hisie wrote:

I would like to have a default value in a form field, but i am not being lucky. I have readen the SonataAdminBundle docs and the Forms one and i supose i have todo:

public function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('padre', 'hidden', array('data'=>$this->getRequest()->get('padre')), array( ))
->add('hijo', 'sonata_type_model', array('required'=>false, ), array('edit' => 'list'))
->add('orden');

}

So the data will be set default to the request, But i does not work.

I have tried to instantiate the object in the formBuilder (overwriting it in the inherited class ContenidoContenidoAdmin):

public function getFormBuilder($object = null, $options = array())
{
if (!$object) {
$object = $this->getSubject();
}

   if (!$object) {
       $object = $this->getNewInstance();
       $padre = $this->getModelManager()->findOne('CarlaCmsBundle:Contenido', $this->getRequest()->get('padre'));
       $object->setPadre($padre);
       echo "debug";
   }

   // add the custom inline validation option
   $metadata = $this->validator->getMetadataFactory()->getClassMetadata($this->class);
   $metadata->addConstraint(new \Sonata\AdminBundle\Validator\Constraints\InlineConstraint(array(
       'service' => $this,
       'method'  => 'validate'
   )));

   $formBuilder = $this->getFormContractor()->getFormBuilder(
       $this->getUniqid(),
       array_merge($this->formOptions, $options)
   );

   $formBuilder->setData($object);

   $this->defineFormBuilder($formBuilder);

   return $formBuilder;

}
Debug is echoed, but object has no "$padre" value.

I am bit lost, on how to declare predefined data in this admin generator. Thank you.

Reply to this email directly or view it on GitHub:
#249

@hisie

This comment has been minimized.

Show comment
Hide comment
@hisie

hisie Aug 23, 2011

Thank you rande,
I knew, but in theory in the second option the FormBuilder is setting the data of the object with the parameter passed to it. The string "debug" is shown as output so $object->setPadre($padre); is executed, so object must have the predefined value $padre in the attribute padre of the object, and this mus means that the form shown must have this $padre as the value of the form field, but it is not working.

Well, i go to sleep, if tomorro mornig i haver better ideas i will share with you...

hisie commented Aug 23, 2011

Thank you rande,
I knew, but in theory in the second option the FormBuilder is setting the data of the object with the parameter passed to it. The string "debug" is shown as output so $object->setPadre($padre); is executed, so object must have the predefined value $padre in the attribute padre of the object, and this mus means that the form shown must have this $padre as the value of the form field, but it is not working.

Well, i go to sleep, if tomorro mornig i haver better ideas i will share with you...

@hisie

This comment has been minimized.

Show comment
Hide comment
@hisie

hisie Aug 24, 2011

Well i solved the funcionality by doing

public function create($object)
{
        $object->setPadre($this->getModelManager()->findOne('CarlaCmsBundle:Contenido', $this->getRequest()->get('padre')));

    $this->prePersist($object);
    $this->modelManager->create($object);
    $this->postPersist($object);
}

I think this is not the best solution, but it works. I also would like that SonataAdminBundle include any way to instantiate objects before the form generation.

hisie commented Aug 24, 2011

Well i solved the funcionality by doing

public function create($object)
{
        $object->setPadre($this->getModelManager()->findOne('CarlaCmsBundle:Contenido', $this->getRequest()->get('padre')));

    $this->prePersist($object);
    $this->modelManager->create($object);
    $this->postPersist($object);
}

I think this is not the best solution, but it works. I also would like that SonataAdminBundle include any way to instantiate objects before the form generation.

@pachay

This comment has been minimized.

Show comment
Hide comment
@pachay

pachay Aug 26, 2011

Hi rande,

is it will be possible to set default value in future versions?

i'd like to set default value so user can easily edit them.

pachay commented Aug 26, 2011

Hi rande,

is it will be possible to set default value in future versions?

i'd like to set default value so user can easily edit them.

@rande

This comment has been minimized.

Show comment
Hide comment
@rande

rande Sep 4, 2011

Member

this can be done by overwriting the Admin::getNewInstance method

Member

rande commented Sep 4, 2011

this can be done by overwriting the Admin::getNewInstance method

@rande rande closed this Sep 4, 2011

@dcsg

This comment has been minimized.

Show comment
Hide comment
@dcsg

dcsg Nov 8, 2011

Contributor

Hi, I am facing this problem too. It's possible overwrite the method but IMO it shouldn't be done, because this functionality is provided by the base form field type in SF2.

So I started debugging it to see what should be changed but my expertise in internals is not good.
I identified an empty instance of the entity/class is being set to the form on the line #391 of the CRUDController class. This overwrites the default values that have been set before in the configureFormField() method inside the Admin class.

I am not confortable with the internals of the Sonata Admin Bundle, but I am trying to figure out a way to do that without overwrite that method.

@rande, in your opinion do you think this is hard to change?

Contributor

dcsg commented Nov 8, 2011

Hi, I am facing this problem too. It's possible overwrite the method but IMO it shouldn't be done, because this functionality is provided by the base form field type in SF2.

So I started debugging it to see what should be changed but my expertise in internals is not good.
I identified an empty instance of the entity/class is being set to the form on the line #391 of the CRUDController class. This overwrites the default values that have been set before in the configureFormField() method inside the Admin class.

I am not confortable with the internals of the Sonata Admin Bundle, but I am trying to figure out a way to do that without overwrite that method.

@rande, in your opinion do you think this is hard to change?

@rande

This comment has been minimized.

Show comment
Hide comment
@rande

rande Nov 8, 2011

Member

The Admin bundle is model centric, so default values should be set in the model. Maybe the Admin Bundle need a specific 'create' method to solve your problem. However the getNewInstance can do the job too.

Member

rande commented Nov 8, 2011

The Admin bundle is model centric, so default values should be set in the model. Maybe the Admin Bundle need a specific 'create' method to solve your problem. However the getNewInstance can do the job too.

@ibasaw

This comment has been minimized.

Show comment
Hide comment
@ibasaw

ibasaw Mar 8, 2012

allright, can we have an example for this ?

I just want definie a default value for my dropdownlist...

I try to do this:

/** \* @ORM\ManyToOne(targetEntity="\Application\Sonata\UserBundle\Entity\User") */ protected $auteur = "toto";

but got this error in the log: request.CRITICAL: Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "object", "string" given (uncaught exception) at

Thanks for your help

ibasaw commented Mar 8, 2012

allright, can we have an example for this ?

I just want definie a default value for my dropdownlist...

I try to do this:

/** \* @ORM\ManyToOne(targetEntity="\Application\Sonata\UserBundle\Entity\User") */ protected $auteur = "toto";

but got this error in the log: request.CRITICAL: Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "object", "string" given (uncaught exception) at

Thanks for your help

@webdevilopers

This comment has been minimized.

Show comment
Hide comment
@webdevilopers

webdevilopers Sep 5, 2014

Contributor

@ibasaw You can't pass a string to the $auteur var since the annotations define it as an object resp. entity.

As @rande mentioned and @hisie tried in his example you should add your default object via getNewInstance method:

    public function getNewInstance()
    {
        $instance = parent::getNewInstance();

        $entityManager = $this->getModelManager()->getEntityManager('Application\Sonata\UserBundle\Entity\User');
        $auteurReference = $entityManager->getReference('Application\Sonata\UserBundle\Entity\User', 666); // the ID of your `toto` $auteur

        $instance->setAuteur($auteurReference);

        return $instance;
    }

The Reference does not load the complete Entity into memory unlike using the findBy method().

Contributor

webdevilopers commented Sep 5, 2014

@ibasaw You can't pass a string to the $auteur var since the annotations define it as an object resp. entity.

As @rande mentioned and @hisie tried in his example you should add your default object via getNewInstance method:

    public function getNewInstance()
    {
        $instance = parent::getNewInstance();

        $entityManager = $this->getModelManager()->getEntityManager('Application\Sonata\UserBundle\Entity\User');
        $auteurReference = $entityManager->getReference('Application\Sonata\UserBundle\Entity\User', 666); // the ID of your `toto` $auteur

        $instance->setAuteur($auteurReference);

        return $instance;
    }

The Reference does not load the complete Entity into memory unlike using the findBy method().

@webdevilopers

This comment has been minimized.

Show comment
Hide comment
@webdevilopers

webdevilopers Sep 5, 2014

Contributor

BTW @rande : Has the getNewInstance method since 2.2.4 been documented yet?
I couldn't find it there - unfortunately there is no search function for the docs! ;)

Where should it be mentioned - here:http://sonata-project.org/bundles/admin/master/doc/reference/action_create_edit.html
?

Contributor

webdevilopers commented Sep 5, 2014

BTW @rande : Has the getNewInstance method since 2.2.4 been documented yet?
I couldn't find it there - unfortunately there is no search function for the docs! ;)

Where should it be mentioned - here:http://sonata-project.org/bundles/admin/master/doc/reference/action_create_edit.html
?

@rande

This comment has been minimized.

Show comment
Hide comment
@rande

rande Sep 5, 2014

Member

@webdevilopers There is no clear documentation about "nice functions" of the Admin class. Maybe you can initiate an 101 list ;)

Member

rande commented Sep 5, 2014

@webdevilopers There is no clear documentation about "nice functions" of the Admin class. Maybe you can initiate an 101 list ;)

@webdevilopers

This comment has been minimized.

Show comment
Hide comment
@webdevilopers
Contributor

webdevilopers commented Sep 5, 2014

@shkkmo

This comment has been minimized.

Show comment
Hide comment
@shkkmo

shkkmo Jul 9, 2015

what about unmapped fields?

shkkmo commented Jul 9, 2015

what about unmapped fields?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment