Before today, I used custom AJAX to achieve this.
Client :
// Override of admin-bundle/Resources/Views/CRUD/base_edit.html.twig
{% block javascripts %}
{{ parent() }}
<script type="text/javascript">
$(document).ready(function() {
$('#{{ admin.uniqId }}_parent').change(function() {
var parent = $(this);
var child = $('#{{ admin.uniqId }}_child');
$.get('/admin/child/get_choices/' + parent.val(), function(data) {
child.empty().append(data);
}, 'text')
.then(function() {
var childFirstOption = child.find('option:first');
var childDisplayText = $("#field_widget_{{ admin.uniqId }}_child .select2-chosen");
childFirstOption.attr("selected", true);
childDisplayText.text(childFirstOption.text());
});
});
});
</script>
{% endblock %}
Server:
// src/App/AdminBundle/Controller/ChildAdminController.php
class ChildAdminController extends Controller
{
//...
public function getChoicesAction($parent)
{
$html = "";
$parent = $this->getDoctrine()
->getRepository('AppAdminBundle:Parent')
->find($parent)
;
$choices = $parent->getChilds();
foreach($choices as $choice) {
$html .= '<option value="' . $choice->getId() . '" >' . $choice->getLabel() . '</option>';
}
return new Response($html);
}
//...
}
And
// src/App/AdminBundle/Admin/ChildAdmin.php
//...
use Sonata\AdminBundle\Route\RouteCollection;
class ChildAdmin extends Admin
{
//...
protected function configureRoutes(RouteCollection $collection)
{
$collection->add('get_choices', 'get_choices/{parent}', array(), array(), array('expose' => true));
}
// ...
}
I will try to implement sonata_type_model_reference soon and come back here for edits.