Надеюсь, что это имеет какой-то смысл!

аюсь создать страницу, которая очень похожа на страницу создания формы Google.

Вот как я пытаюсь смоделировать его, используя инфраструктуру GWT MVP (Места и Действия) и Редакторы.

CreateFormActivity (Активность и ведущий)

CreateFormView (интерфейс для просмотра, с вложенным интерфейсом Presenter)

CreateFormViewImpl (реализует CreateFormView и редактор <FormProxy>

CreateFormViewImpl имеет следующие подредакторы:

Заголовок TextBoxОписание текстового поляQuestionListEditor questionList

QuestionListEditor реализует IsEditor <ListEditor <QuestionProxy, QuestionEditor >>

QuestionEditor реализует редактор <QuestionProxy> QuestionEditor имеет следующие подредакторы:

TextBox questionTitleTextBox helpTextValueListBox questionTypeНеобязательный подредактор для каждого типа вопроса ниже.

Редактор для каждого типа вопроса:

TextQuestionEditor

ParagraphTextQuestionEditor

MultipleChoiceQuestionEditor

CheckboxesQuestionEditor

ListQuestionEditor

ScaleQuestionEditor

GridQuestionEditor

Конкретные вопросы:Как правильно добавить / удалить вопросы из формы.(видетьдополнительный вопрос)Как мне создать редактор для каждого типа вопроса? Я попытался прослушать изменения значения questionType, я не уверен, что делать после.(отвечает BobV)Должен ли каждый редактор, относящийся к конкретному типу вопроса, быть оберткой с необязательным элементом FieldEditor? Поскольку только один из может быть использован одновременно.(отвечает BobV)Как лучше всего управлять созданием / удалением объектов глубоко в иерархии объектов. Пример) Указание ответов на вопрос № 3 типа вопроса с множественным выбором.(видетьдополнительный вопрос)Можно ли использовать редактор OptionalFieldEditor для переноса ListEditor?(отвечает BobV)Реализация на основе ответа

Редактор вопросов

public class QuestionDataEditor extends Composite implements
CompositeEditor<QuestionDataProxy, QuestionDataProxy, Editor<QuestionDataProxy>>,
LeafValueEditor<QuestionDataProxy>, HasRequestContext<QuestionDataProxy> {

interface Binder extends UiBinder<Widget, QuestionDataEditor> {}

private CompositeEditor.EditorChain<QuestionDataProxy, Editor<QuestionDataProxy>> chain;

private QuestionBaseDataEditor subEditor = null;
private QuestionDataProxy currentValue = null;
@UiField
SimplePanel container;

@UiField(provided = true)
@Path("dataType")
ValueListBox<QuestionType> dataType = new ValueListBox<QuestionType>(new Renderer<QuestionType>() {

    @Override
    public String render(final QuestionType object) {
        return object == null ? "" : object.toString();
    }

    @Override
    public void render(final QuestionType object, final Appendable appendable) throws IOException {
        if (object != null) {
            appendable.append(object.toString());
        }
    }
});

private RequestContext ctx;

public QuestionDataEditor() {
    initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this));
    dataType.setValue(QuestionType.BooleanQuestionType, true);
    dataType.setAcceptableValues(Arrays.asList(QuestionType.values()));

    /*
     * The type drop-down UI element is an implementation detail of the
     * CompositeEditor. When a question type is selected, the editor will
     * call EditorChain.attach() with an instance of a QuestionData subtype
     * and the type-specific sub-Editor.
     */
    dataType.addValueChangeHandler(new ValueChangeHandler<QuestionType>() {
        @Override
        public void onValueChange(final ValueChangeEvent<QuestionType> event) {
            QuestionDataProxy value;
            switch (event.getValue()) {

            case MultiChoiceQuestionData:
                value = ctx.create(QuestionMultiChoiceDataProxy.class);
                setValue(value);
                break;

            case BooleanQuestionData:
            default:
                final QuestionNumberDataProxy value2 = ctx.create(BooleanQuestionDataProxy.class);
                value2.setPrompt("this value doesn't show up");
                setValue(value2);
                break;

            }

        }
    });
}

/*
 * The only thing that calls createEditorForTraversal() is the PathCollector
 * which is used by RequestFactoryEditorDriver.getPaths().
 * 
 * My recommendation is to always return a trivial instance of your question
 * type editor and know that you may have to amend the value returned by
 * getPaths()
 */
@Override
public Editor<QuestionDataProxy> createEditorForTraversal() {
    return new QuestionNumberDataEditor();
}

@Override
public void flush() {
    //XXX this doesn't work, no data is returned
    currentValue = chain.getValue(subEditor);
}

/**
 * Returns an empty string because there is only ever one sub-editor used.
 */
@Override
public String getPathElement(final Editor<QuestionDataProxy> subEditor) {
    return "";
}

@Override
public QuestionDataProxy getValue() {
    return currentValue;
}

@Override
public void onPropertyChange(final String... paths) {
}

@Override
public void setDelegate(final EditorDelegate<QuestionDataProxy> delegate) {
}

@Override
public void setEditorChain(final EditorChain<QuestionDataProxy, Editor<QuestionDataProxy>> chain) {
    this.chain = chain;
}

@Override
public void setRequestContext(final RequestContext ctx) {
    this.ctx = ctx;
}

/*
 * The implementation of CompositeEditor.setValue() just creates the
 * type-specific sub-Editor and calls EditorChain.attach().
 */
@Override
public void setValue(final QuestionDataProxy value) {

    // if (currentValue != null && value == null) {
    chain.detach(subEditor);
    // }

    QuestionType type = null;
    if (value instanceof QuestionMultiChoiceDataProxy) {
        if (((QuestionMultiChoiceDataProxy) value).getCustomList() == null) {
            ((QuestionMultiChoiceDataProxy) value).setCustomList(new ArrayList<CustomListItemProxy>());
        }
        type = QuestionType.CustomList;
        subEditor = new QuestionMultipleChoiceDataEditor();

    } else {
        type = QuestionType.BooleanQuestionType;
        subEditor = new BooleanQuestionDataEditor();
    }

    subEditor.setRequestContext(ctx);
    currentValue = value;
    container.clear();
    if (value != null) {
        dataType.setValue(type, false);
        container.add(subEditor);
        chain.attach(value, subEditor);
    }
}

}

Редактор базы данных вопросов

public interface QuestionBaseDataEditor extends HasRequestContext<QuestionDataProxy>,                         IsWidget {


}

Пример подтипа

public class BooleanQuestionDataEditor extends Composite implements QuestionBaseDataEditor {
interface Binder extends UiBinder<Widget, BooleanQuestionDataEditor> {}

@Path("prompt")
@UiField
TextBox prompt = new TextBox();

public QuestionNumberDataEditor() {
    initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this));
}

@Override
public void setRequestContext(final RequestContext ctx) {

}
}

Осталась только одна проблема - данные, относящиеся к подтипу QuestionData, не отображаются и не сбрасываются. Я думаю, что это связано с настройкой редактора, который я использую.

Например, значение для приглашения вBooleanQuestionDataEditor не установлен и не очищен, и является нулевым в полезной нагрузке rpc.

Я предполагаю: поскольку QuestionDataEditor реализует LeafValueEditor, драйвер не будет посещать подредактор, даже если он был присоединен.

Большое спасибо всем, кто может помочь !!!

Ответы на вопрос(4)

Ваш ответ на вопрос