symfony - Sonata User Admin - Custom field dependency -


i have extended sonataadmin class fosuser , added 2 custom fields (choice type external data source): company , sector

i'd make sector dependent on company, if user selects company filters available sectors.

i though using formevents filtering @ page load, don't know how company value of current form.

here part of custom sectortype

public function buildform(formbuilderinterface $builder, array $options) {     $builder->addeventlistener(formevents::pre_set_data     , function(formevent $event) {         $data = $event->getdata();         $form = $event->getform();         // need company value here if set     }); }  public function setdefaultoptions(optionsresolverinterface $resolver) {     $resolver->setdefaults(array(         'choices' => $this->getsectors(),     )); }  public function getsectors() {     $sects = array();     // need pass selected company value getlist     // (which gets list of sector can imagine)     if (($tmp_sects = $this->ssrs->getlist('sector'))) {         foreach ($tmp_sects $sect) {             $label = $sect['id'] ? $sect['label'] : '';             $sects[$sect['id']] = $label;         }     }     return $sects; } 

so question is:

how selected company custom sectortype ?


after i'll need able refresh sector ajax, question

i had similar problem. needed create sale entity needed associated in many 1 relationship enterprise entity , many many relationship services entities. here sale entity:

the thing services available depending on companies chosen. instance services , b provided company x. , services b , c provided company y. in admin, depending on chosen company had display available services. these needed 2 things:

first create dynamic form sale admin, on server side right services available company specified in sale record. , second, had create custom form type company form element, when changed user on client side, send ajax request right services company chosen.

for first problem, did similar trying achieve, instead of creating specific custom type services element, added de event listener directly in admin.

here sale entity:

/**  *  * @orm\table(name="sales")  * @orm\entity  * @orm\haslifecyclecallbacks()  */ class sale {     /**      * @var integer $id      *      * @orm\column(name="id", type="integer", nullable=false)      * @orm\id      * @orm\generatedvalue(strategy="identity")      */      public $id;     /**      * @orm\manytoone(targetentity="branch")      * @orm\joincolumn(name="branch_id", referencedcolumnname="id", nullable = false)      * @assert\notblank(message = "debe especificar una empresa la cual asignar el precio de este exámen!")      */     private $branch;      /** unidirectional many many      * @orm\manytomany(targetentity="service")      * @orm\jointable(name="sales_services",      *      joincolumns={@orm\joincolumn(name="sale_id", referencedcolumnname="id")},      *      inversejoincolumns={@orm\joincolumn(name="service_id", referencedcolumnname="id")}      *      )      * @assert\count(min = "1", minmessage = "debe especificar al menos un servicio realizar!")      */     private $services;       public function __construct() {         $this->services = new \doctrine\common\collections\arraycollection();     }      /**      * id      *      * @return integer       */     public function getid()     {         return $this->id;     }      /**      * set branch      *      * @param astricom\neurocienciasbundle\entity\branch $branch      */      //default value have null, because when validation constraint set notblank,       //if default not null, before calling validation constraint error pop explaining      //that no instance of branch passed $branch argument.     public function setbranch(\astricom\neurocienciasbundle\entity\branch $branch = null)     {         $this->branch = $branch;     }      /**      * branch      *      * @return astricom\neurocienciasbundle\entity\branch       */     public function getbranch()     {         return $this->branch;     }       /**      * add service      *      * @param \astricom\neurocienciasbundle\entity\service|null $service      */     public function addservices(\astricom\neurocienciasbundle\entity\service $service = null)     {         $this->services[] = $service;     }      /**      * services      *      * @return doctrine\common\collections\collection       */     public function getservices()     {         return $this->services;     }       /**      * sets creation date      *      * @param \datetime|null $createdat      */     public function setcreatedat(\datetime $createdat = null)     {         $this->createdat = $createdat;     }      /**      * returns creation date      *      * @return \datetime|null      */     public function getcreatedat()     {         return $this->createdat;     }      /**      * sets last update date      *      * @param \datetime|null $updatedat      */     public function setupdatedat(\datetime $updatedat = null)     {             $this->updatedat = $updatedat;     } 

so in admin form builder:

protected function configureformfields(formmapper $formmapper)  {     $em = $this->container->get('doctrine')->getentitymanager();     $branchquery = $em->createquerybuilder();      $branchquery->add('select', 'b')        ->add('from', 'astricom\neurocienciasbundle\entity\branch b')        ->add('orderby', 'b.name asc');      $formmapper       ->with('empresa/sucursal')          ->add('branch','shtumi_ajax_entity_type',array('required' => true, 'label'=>'empresa/sucursal','error_bubbling' => true, 'empty_value' => 'seleccione una empresa/sucursal', 'empty_data'  => null, 'entity_alias'=>'sale_branch', 'attr'=>array('add_new'=>false), 'model_manager' => $this->getmodelmanager(), 'class'=>'astricom\neurocienciasbundle\entity\branch', 'query' => $branchquery))        ->end()     ;      $builder = $formmapper->getformbuilder();     $factory = $builder->getformfactory();      $sale = $this->getsubject();     $builder->addeventlistener(formevents::pre_set_data,          function(dataevent $event) use ($sale,$factory, $em) {              $form = $event->getform();             $servicesquery = $em->createquerybuilder();             $servicesquery->add('select','s')                 ->add('from','astricom\neurocienciasbundle\entity\service s');              if (!$sale || !$sale->getid()) {                 $servicesquery                     ->where($servicesquery->expr()->eq('s.id', ':id'))                     ->setparameter('id', 0);             }             else {                 $servicesquery                     ->join('s.branch', 'b')                     ->where($servicesquery->expr()->eq('b.id', ':id'))                     ->setparameter('id', $sale->getbranch()->getid());             }              $form->add($factory->createnamed('services','entity',null,array('required' => true, 'label'=>'servicios','error_bubbling' => true, 'attr'=>array('show_value_label'=>true),'class'=>'astricom\neurocienciasbundle\entity\service','multiple'=>true,'expanded'=>true,'query_builder'=>$servicesquery)));         }     ); } 

the trick thing pass forms data. doesn't work use evet->getdata() in event listener's function. instead passed through admin->getsubject() method. instead of adding sonataadmin form type, inside event listener's function, had use plain symfony form type.

the ajax part mentioned question. weird things on branch add method in form builder related customized field type matter. don't worry it.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -