在今天之前,我使用自定义AJAX来实现这一点。
客户:
// 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 %}
服务器:
// 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);
}
//...
}
而且
// 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));
}
// ...
}
我会尝试尽快实施sonata_type_model_reference回来这里编辑。
你是什么意思“链”两个关系?你想要更新与相关字段值相对应的字段的选项吗?示例:我们有一个带有类别的列表框,第二个带有子类别的列表框以及第一个到第二个的oneToMany。在选择类别时,我们更新子类别列表框的可用选项,仅使用具有类别=选择的条目。这是你想要的吗? – chalasr
@chalasr是的,那正是我想要的,但很久以前,我们确实已经停止了这个项目。但是,如果您有解决方案,随时为您的答案贡献! – edrian