Search code examples
javascriptrestadmin-on-restelixir

How to separate edit and update contexts (admin-on-rest, dot notation)


I am using npm package admin-on-rest to build react back-office for my elixir/phoenix REST API backend.

My questions/:id (show action) returns the following flat JSON structure:

{
  id: 7
  content: "<p> Question content here</p>"
  points: 300
  title: "Question title"
}

And my update action expects the following nested JSON as an input to update question:

{
  id: 7
  question: {
    content: "<p>New question content</p>"
    points: 400
    title: "New question title"
  }
}

My problem is related to dot notation used in admin-on-rest

If I use the following JS code to represent edit action within my back-office

export const QuestionEdit = (props) => (
  <Edit title={<QuestionTitle />} {...props}>
    <SimpleForm>
      <DisabledInput source="question.id" />
      <TextInput source="question.title" />
      <LongTextInput source="question.content"/>
      <TextInput source="question.points" />
    </SimpleForm>
  </Edit>
)

then I have correct data within PUT request payload, but there is no values rendered in "edit" form inputs (see screenshot 1)

enter image description here enter image description here

And if I use another variant of JS code (with flat source values):

export const QuestionEdit = (props) => (
  <Edit title={<QuestionTitle />} {...props}>
    <SimpleForm>
      <DisabledInput source="id" />
      <TextInput source="title" />
      <LongTextInput source="content"/>
      <TextInput source="points" />
    </SimpleForm>
  </Edit>
)

then all previous input values in "edit" form represented correctly, but PUT request payload cannot be parsed by my update action (see screenshot 2)

enter image description here enter image description here


Assuming that I don't want to change my backend API (because it is auto-generated by phoenix code generators), how can I edit my JS code to achieve 2 goals - previous values should be rendered correctly (edit page) and nested JSON structure should be provided for update action

Many thanks in advance for your attention!


Solution

  • Take a look at using a custom action. Basically your form is rendering with data that is flattened, hence why it will show correctly when you use (id, title, etc.). Then you need to transform that data before you PUT it to your server.