postEntity method
Sends a POST request to create a record in a Dynamics 365 entity.
Parameters:
- entity: the entity name (e.g., SalesOrderHeaders, SalesOrderLines)
- payload: a map of field names and values to create
- filterByField / filterValue: optional, not usually used with POST
- mainField: optional, the field to return from the response (like salesOrderId)
Returns:
- the value of mainField if provided and returned by D365
- null if failed or mainField not set
Implementation
Future<String?> postEntity(String entity,
Map<String, dynamic> payload, {
String? filterByField,
String? filterValue,
String? mainField,
/// like salesOrderId
}) async {
final token = await getAccessToken();
if (token == null) return null;
final url = (filterByField != null &&
filterByField.isNotEmpty &&
filterValue != null &&
filterValue.isNotEmpty)
? Uri.parse(
"$resource/data/$entity?\$filter=$filterByField eq '$filterValue'")
: Uri.parse("$resource/data/$entity");
final response = await http.post(
url,
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: json.encode(payload),
);
if (response.statusCode == 201 || response.statusCode == 200) {
if (mainField != null) {
final data = jsonDecode(response.body);
return data[mainField];
}
else {
return null;
}
} else {
print("❌ Failed to post $entity: ${response.statusCode} - ${response
.body}");
return null;
}
}