admin-on-rest

BooleanField with FunctionField change number to Boolean


I have question and I'm sure it will help other developers. I have field "is_active" which is Boolean in my API side but it return 0 or 1 and not TRUE or FALSE. I want to use <FunctionField/> to wrap the <BooleanField/> but it didn't work. Someone can help please.

This is my code:

<FunctionField source="is_active" label="is_active" render={(record) => record.is_active ? true : false}>
  <BooleanField/>
</FunctionField>

The column is still blank.

Thanks.


Solution

  • I think you misunderstood the FunctionField component. It renders the result of the render prop. What you are trying to achieve is:

    <FunctionField source="is_active" label="is_active" render={(record,source) => 
        <BooleanField record={{...record,is_active:!!record.is_active}} source={source}/>}/>
    

    But this is not very nice. Better is to wrap your dataProvider/restClient and ensure the data is a boolean.

    // In FixMyDataFeature.js
    export default restClient => (type, resource, params) => restClient(type,resource,params).then(response=>
       if(resource === 'Resource_with_numeric_is_active_field`){
          return {
             data: mutateIsActiveFieldToBoolean(response.data)
          }
       }
       else{
          return response;
       }
    );
    

    And call it with Admin:

    <Admin dataProvider={FixMyDataFeature(dataProvider)}... />