KnowledgeSeeker
KnowledgeSeeker

Reputation: 107

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

Upvotes: 1

Views: 528

Answers (2)

PsychoMo
PsychoMo

Reputation: 699

You don't have to use Ajax for this, when you setup the form on your controller you can use loadDataFrom (http://api.silverstripe.org/3.3/class-Form.html#_loadDataFrom) to load the member directly into the form.

An example implementation could be (I haven't tested this, but it should work):

class Page_Controller extends ContentController
{

  public function index()
  {
    $member = Member::currentUser();

    $this->customise(array(
      "Form" => $this->Form()->loadDataFrom($member)
    ));
  }

  public function Form() {
    return Form::create(
      $this,
      "Form",
      $fields, // Add your own fields here
      $actions // Add your own actions here
    );
  }
}

Upvotes: 1

KnowledgeSeeker
KnowledgeSeeker

Reputation: 107

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 :)

Upvotes: 0

Related Questions