Casper Britz Casper Britz - 2 months ago 26
jQuery Question

Silverstripe - populate fields depending on selected DataObject

I want to display a

members
details on screen when I select their name from a
Dropdown


More information: I have a form that submits a few fields. Amongst them I have a "Select User"
Dropdown
to link this person to the data being submitted

Problem is- client wants the user's details to show when they select a user(make sure its the right person etc)

How can i accomplish this? There are like 3 seperate input fields that will need to contain data. I know how to do it using raw PHP/javascript, but do not know how to implement this in a
Silverstripe
way

Answer

Got a solution based off of this: https://www.silverstripe.org/community/forums/form-questions/show/24628

The way I did it was like this:

SS template

$("table.myTable").on('change','select#Some_Form',function(){
 $.ajax({
   type: "POST",
   data: {param:param},
   url: window.location.href+"your_action_here",
   success: function(result) {
      var resArr = JSON.parse(result);
      $('input#Some_Field').val(resArr['key']);
    }
 }); 
});

Controller

static $allowed_actions = array('your_action_here');
  //parameter is a SS_HTTPRequest
public function your_action_here($request){
 //assuming my parameter is an ID
 $ID = $request['param'];
 $dataObject = DataObject::get_by_id('Object',$ID);
 $JSONArray = array('key'=>$dataObject->Field);
 echo json_encode($JSONArray);    
}

When the select changes, gets the DataObject and populates correctly :)

Comments