feat: allow async relationship filter options (#2951)

* chore: improving relationship filter options;

Updating prop filterOptions from field type "relationship" to allow async functions;

* chore: add failing test case

* fix: translation followingFieldsInvalid_many not getting triggered

* docs: improve documentation

---------

Co-authored-by: Alessio Gravili <alessio@gravili.de>
This commit is contained in:
Jordy Alcides
2023-08-14 12:29:29 -03:00
committed by GitHub
parent 20a6ce8823
commit bad363882c
33 changed files with 103 additions and 73 deletions

View File

@@ -74,7 +74,7 @@ Set to `false` if you'd like to disable the ability to create new documents from
Options can be dynamically limited by supplying a [query constraint](/docs/queries/overview), which will be used both for validating input and filtering available relationships in the UI.
The `filterOptions` property can either be a `Where` query directly, or a function that returns one. When using a function, it will be called with an argument object with the following properties:
The `filterOptions` property can either be a `Where` query directly, or a function (synchronous or asynchronous) that returns one. When using a function, it will be called with an argument object containing the following properties:
| Property | Description |
| ------------- | ------------------------------------------------------------------------------------ |

View File

@@ -1,14 +1,14 @@
import { Where } from '../../../../types';
import { FilterOptions, FilterOptionsProps } from '../../../../fields/config/types';
export const getFilterOptionsQuery = (filterOptions: FilterOptions, options: Omit<FilterOptionsProps, 'relationTo'> & { relationTo: string | string[] }): {[collection: string]: Where } => {
export const getFilterOptionsQuery = async (filterOptions: FilterOptions, options: Omit<FilterOptionsProps, 'relationTo'> & { relationTo: string | string[] }): Promise<{[collection: string]: Where }> => {
const { relationTo } = options;
const relations = Array.isArray(relationTo) ? relationTo : [relationTo];
const query = {};
if (typeof filterOptions !== 'undefined') {
relations.forEach((relation) => {
query[relation] = typeof filterOptions === 'function' ? filterOptions({ ...options, relationTo: relation }) : filterOptions;
});
await Promise.all(relations.map(async (relation) => {
query[relation] = typeof filterOptions === 'function' ? await filterOptions({ ...options, relationTo: relation }) : filterOptions;
}));
}
return query;
};

View File

@@ -32,17 +32,20 @@ export const GetFilterOptions = ({
const data = reduceFieldsToValues(fields, true);
const siblingData = getSiblingData(fields, path);
const newFilterOptionsResult = getFilterOptionsQuery(filterOptions, {
id,
data,
relationTo,
siblingData,
user,
});
const getFilterOptions = async () => {
const newFilterOptionsResult = await getFilterOptionsQuery(filterOptions, {
id,
data,
relationTo,
siblingData,
user,
});
if (!equal(newFilterOptionsResult, filterOptionsResult)) {
setFilterOptionsResult(newFilterOptionsResult);
}
if (!equal(newFilterOptionsResult, filterOptionsResult)) {
setFilterOptionsResult(newFilterOptionsResult);
}
};
getFilterOptions();
}, [
fields,
filterOptions,

View File

@@ -56,7 +56,7 @@ export type FilterOptionsProps<T = any> = {
relationTo: string,
}
export type FilterOptions<T = any> = Where | ((options: FilterOptionsProps<T>) => Where);
export type FilterOptions<T = any> = Where | ((options: FilterOptionsProps<T>) => (Where | Promise<Where>));
type Admin = {
position?: 'sidebar';

View File

@@ -211,7 +211,7 @@ const validateFilterOptions: Validate = async (value, { t, filterOptions, id, us
const values = Array.isArray(value) ? value : [value];
await Promise.all(collections.map(async (collection) => {
const optionFilter = typeof filterOptions === 'function' ? filterOptions({
const optionFilter = typeof filterOptions === 'function' ? await filterOptions({
id,
data,
siblingData,

View File

@@ -63,7 +63,7 @@
"deletingFile": "حدث خطأ أثناء حذف الملف.",
"deletingTitle": "حدث خطأ أثناء حذف {{title}}. يرجى التحقق من الاتصال الخاص بك والمحاولة مرة أخرى.",
"emailOrPasswordIncorrect": "البريد الإلكتروني أو كلمة المرور المقدمة غير صحيحة.",
"followingFieldsInvalid_many": "الحقول التالية غير صالحة:",
"followingFieldsInvalid_other": "الحقول التالية غير صالحة:",
"followingFieldsInvalid_one": "الحقل التالي غير صالح:",
"incorrectCollection": "مجموعة غير صحيحة",
"invalidFileType": "نوع ملف غير صالح",
@@ -346,4 +346,4 @@
"viewingVersions": "عرض النسخ لـ {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "عرض النسخ للـ {{entityLabel}} العام"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Имаше грешка при изтриването на файла.",
"deletingTitle": "Имаше проблем при изтриването на {{title}}. Моля провери връзката си и опитай отново.",
"emailOrPasswordIncorrect": "Имейлът или паролата не са правилни.",
"followingFieldsInvalid_many": "Следните полета са некоректни:",
"followingFieldsInvalid_other": "Следните полета са некоректни:",
"followingFieldsInvalid_one": "Следното поле е некоректно:",
"incorrectCollection": "Некоректно събиране",
"invalidFileType": "Невалиден тип на файл",
@@ -346,4 +346,4 @@
"viewingVersions": "Гледане на версии за {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Гледане на версии за глобалния документ {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Při mazání souboru došlo k chybě.",
"deletingTitle": "Při mazání {{title}} došlo k chybě. Zkontrolujte své připojení a zkuste to znovu.",
"emailOrPasswordIncorrect": "Zadaný email nebo heslo není správné.",
"followingFieldsInvalid_many": "Následující pole jsou neplatná:",
"followingFieldsInvalid_other": "Následující pole jsou neplatná:",
"followingFieldsInvalid_one": "Následující pole je neplatné:",
"incorrectCollection": "Nesprávná kolekce",
"invalidFileType": "Neplatný typ souboru",
@@ -346,4 +346,4 @@
"viewingVersions": "Zobrazuji verze pro {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Zobrazuji verze pro globální {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Beim Löschen der Datei ist ein Fehler aufgetreten.",
"deletingTitle": "Es gab ein Problem während der Löschung von {{title}}. Bitte überprüfe deine Verbindung und versuche es erneut.",
"emailOrPasswordIncorrect": "Die E-Mail-Adresse oder das Passwort sind nicht korrekt.",
"followingFieldsInvalid_many": "Die folgenden Felder sind nicht korrekt:",
"followingFieldsInvalid_other": "Die folgenden Felder sind nicht korrekt:",
"followingFieldsInvalid_one": "Das folgende Feld ist nicht korrekt:",
"incorrectCollection": "Falsche Sammlung",
"invalidFileType": "Ungültiger Datei-Typ",
@@ -346,4 +346,4 @@
"viewingVersions": "Betrachte Versionen für {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Betrachte Versionen für das Globale Dokument {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "There was an error deleting file.",
"deletingTitle": "There was an error while deleting {{title}}. Please check your connection and try again.",
"emailOrPasswordIncorrect": "The email or password provided is incorrect.",
"followingFieldsInvalid_many": "The following fields are invalid:",
"followingFieldsInvalid_other": "The following fields are invalid:",
"followingFieldsInvalid_one": "The following field is invalid:",
"incorrectCollection": "Incorrect Collection",
"invalidFileType": "Invalid file type",
@@ -346,4 +346,4 @@
"viewingVersions": "Viewing versions for the {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Viewing versions for the global {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Ocurrió un error al eliminar el archivo.",
"deletingTitle": "Ocurrió un error al eliminar {{title}}. Por favor revisa tu conexión y vuelve a intentarlo.",
"emailOrPasswordIncorrect": "El correo o la contraseña introducida es incorrecta.",
"followingFieldsInvalid_many": "Los siguientes campos son inválidos:",
"followingFieldsInvalid_other": "Los siguientes campos son inválidos:",
"followingFieldsInvalid_one": "El siguiente campo es inválido:",
"incorrectCollection": "Colección Incorrecta",
"invalidFileType": "Tipo de archivo inválido",
@@ -346,4 +346,4 @@
"viewingVersions": "Viendo versiones para {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Viendo versiones para el global {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "هنگام حذف فایل خطایی روی داد.",
"deletingTitle": "هنگام حذف {{title}} خطایی رخ داد. لطفاً وضعیت اتصال اینترنت خود را بررسی کنید.",
"emailOrPasswordIncorrect": "رایانامه یا گذرواژه ارائه شده نادرست است.",
"followingFieldsInvalid_many": "کادرهای زیر نامعتبر هستند:",
"followingFieldsInvalid_other": "کادرهای زیر نامعتبر هستند:",
"followingFieldsInvalid_one": "کادر زیر نامعتبر است:",
"incorrectCollection": "مجموعه نادرست",
"invalidFileType": "نوع رسانه نامعتبر است",
@@ -346,4 +346,4 @@
"viewingVersions": "مشاهده نگارش‌ها برای {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "مشاهده نگارش‌های کلی {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Une erreur s'est produite lors de la suppression du fichier.",
"deletingTitle": "Une erreur s'est produite lors de la suppression de {{title}}. Veuillez vérifier votre connexion puis réessayer.",
"emailOrPasswordIncorrect": "L'adresse e-mail ou le mot de passe fourni est incorrect.",
"followingFieldsInvalid_many": "Les champs suivants ne sont pas valides :",
"followingFieldsInvalid_other": "Les champs suivants ne sont pas valides :",
"followingFieldsInvalid_one": "Le champ suivant n'est pas valide :",
"incorrectCollection": "Collection incorrecte",
"invalidFileType": "Type de fichier invalide",
@@ -346,4 +346,4 @@
"viewingVersions": "Affichage des versions de ou du {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Affichage des versions globales de ou du {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Dogodila se pogreška pri brisanju datoteke.",
"deletingTitle": "Dogodila se pogreška pri brisanju {{title}}. Molim provjerite svoju internetsku vezu i pokušajte ponovno.",
"emailOrPasswordIncorrect": "Email ili lozinka netočni.",
"followingFieldsInvalid_many": "Ova polja su nevaljana:",
"followingFieldsInvalid_other": "Ova polja su nevaljana:",
"followingFieldsInvalid_one": " Ovo polje je nevaljano:",
"incorrectCollection": "Nevaljana kolekcija",
"invalidFileType": "Nevaljan tip datoteke",
@@ -346,4 +346,4 @@
"viewingVersions": "Pregled verzija za {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Pregled verzije za globalni {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Hiba történt a fájl törlésekor.",
"deletingTitle": "Hiba történt a {{title}} törlése közben. Kérjük, ellenőrizze a kapcsolatot, és próbálja meg újra.",
"emailOrPasswordIncorrect": "A megadott e-mail-cím vagy jelszó helytelen.",
"followingFieldsInvalid_many": "A következő mezők érvénytelenek:",
"followingFieldsInvalid_other": "A következő mezők érvénytelenek:",
"followingFieldsInvalid_one": "A következő mező érvénytelen:",
"incorrectCollection": "Helytelen gyűjtemény",
"invalidFileType": "Érvénytelen fájltípus",
@@ -346,4 +346,4 @@
"viewingVersions": "A {{entityLabel}} {{documentTitle}} verzióinak megtekintése",
"viewingVersionsGlobal": "A globális {{entityLabel}} verzióinak megtekintése"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Si è verificato un errore durante l'eleminazione del file.",
"deletingTitle": "Si è verificato un errore durante l'eliminazione di {{title}}. Per favore controlla la tua connessione e riprova.",
"emailOrPasswordIncorrect": "L'email o la password fornita non è corretta.",
"followingFieldsInvalid_many": "I seguenti campi non sono validi:",
"followingFieldsInvalid_other": "I seguenti campi non sono validi:",
"followingFieldsInvalid_one": "Il seguente campo non è valido:",
"incorrectCollection": "Collezione non corretta",
"invalidFileType": "Tipo di file non valido",
@@ -346,4 +346,4 @@
"viewingVersions": "Visualizzazione delle versioni per {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Visualizzazione delle versioni per {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "ファイルの削除中にエラーが発生しました。",
"deletingTitle": "{{title}} を削除する際にエラーが発生しました。接続を確認してからもう一度お試しください。",
"emailOrPasswordIncorrect": "メールアドレス、または、パスワードが正しくありません。",
"followingFieldsInvalid_many": "次のフィールドは無効です:",
"followingFieldsInvalid_other": "次のフィールドは無効です:",
"followingFieldsInvalid_one": "次のフィールドは無効です:",
"incorrectCollection": "不正なコレクション",
"invalidFileType": "無効なファイル形式",
@@ -340,4 +340,4 @@
"viewingVersions": "表示バージョン: {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "表示バージョン: グローバルな {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "ဖိုင်ကိုဖျက်ရာတွင် အမှားအယွင်းရှိနေသည်။",
"deletingTitle": "{{title}} ကို ဖျက်ရာတွင် အမှားအယွင်းရှိခဲ့သည်။ သင့် အင်တာနက်လိုင်းအား စစ်ဆေးပြီး ထပ်မံကြို့စားကြည့်ပါ။",
"emailOrPasswordIncorrect": "ထည့်သွင်းထားသော အီးမေးလ် သို့မဟုတ် စကားဝှက်သည် မမှန်ပါ။",
"followingFieldsInvalid_many": "ထည့်သွင်းထားသော အချက်အလက်များသည် မမှန်ကန်ပါ။",
"followingFieldsInvalid_other": "ထည့်သွင်းထားသော အချက်အလက်များသည် မမှန်ကန်ပါ။",
"followingFieldsInvalid_one": "ထည့်သွင်းထားသော အချက်အလက်သည် မမှန်ကန်ပါ။",
"incorrectCollection": "မှားယွင်းသော စုစည်းမှု",
"invalidFileType": "မမှန်ကန်သော ဖိုင်အမျိုးအစား",
@@ -346,4 +346,4 @@
"viewingVersions": "{{entityLabel}} {{documentTitle}} အတွက် ဗားရှင်းများကို ကြည့်ရှုခြင်း",
"viewingVersionsGlobal": "`ဂလိုဘယ်ဆိုင်ရာ {{entityLabel}} အတွက် ဗားရှင်းများကို ကြည့်ရှုနေသည်"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Det oppstod en feil under sletting av filen.",
"deletingTitle": "Det oppstod en feil under sletting av {{title}}. Sjekk tilkoblingen og prøv igjen.",
"emailOrPasswordIncorrect": "E-postadressen eller passordet er feil.",
"followingFieldsInvalid_many": "Følgende felter er ugyldige:",
"followingFieldsInvalid_other": "Følgende felter er ugyldige:",
"followingFieldsInvalid_one": "Følgende felt er ugyldig:",
"incorrectCollection": "Ugyldig samling",
"invalidFileType": "Ugyldig filtype",
@@ -346,4 +346,4 @@
"viewingVersions": "Viser versjoner for {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Viser versjoner for den globale variabelen {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Er is een fout opgetreden bij het verwijderen van dit bestand.",
"deletingTitle": "Er is een fout opgetreden tijdens het verwijderen van {{title}}. Controleer uw verbinding en probeer het opnieuw.",
"emailOrPasswordIncorrect": "Het opgegeven e-mailadres of wachtwoord is onjuist.",
"followingFieldsInvalid_many": "De volgende velden zijn ongeldig:",
"followingFieldsInvalid_other": "De volgende velden zijn ongeldig:",
"followingFieldsInvalid_one": "Het volgende veld is ongeldig:",
"incorrectCollection": "Ongeldige collectie",
"invalidFileType": "Ongeldig bestandstype",
@@ -346,4 +346,4 @@
"viewingVersions": "Bekijk versies voor {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Bekijk versies voor global {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "",
"deletingTitle": "Wystąpił błąd podczas usuwania {{title}}. Proszę, sprawdź swoje połączenie i spróbuj ponownie.",
"emailOrPasswordIncorrect": "Podany adres e-mail lub hasło jest nieprawidłowe.",
"followingFieldsInvalid_many": "Następujące pola są nieprawidłowe:",
"followingFieldsInvalid_other": "Następujące pola są nieprawidłowe:",
"followingFieldsInvalid_one": "To pole jest nieprawidłowe:",
"incorrectCollection": "Nieprawidłowa kolekcja",
"invalidFileType": "Nieprawidłowy typ pliku",
@@ -346,4 +346,4 @@
"viewingVersions": "Przeglądanie wersji {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Przeglądanie wersji dla globalnej kolekcji {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Ocorreu um erro ao excluir o arquivo.",
"deletingTitle": "Ocorreu um erro ao excluir {{title}}. Por favor, verifique sua conexão e tente novamente.",
"emailOrPasswordIncorrect": "O email ou senha fornecido está incorreto.",
"followingFieldsInvalid_many": "Os campos a seguir estão inválidos:",
"followingFieldsInvalid_other": "Os campos a seguir estão inválidos:",
"followingFieldsInvalid_one": "O campo a seguir está inválido:",
"incorrectCollection": "Coleção Incorreta",
"invalidFileType": "Tipo de arquivo inválido",
@@ -346,4 +346,4 @@
"viewingVersions": "Visualizando versões para o/a {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Visualizando versões para o global {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "S-a produs o eroare la ștergerea fișierului.",
"deletingTitle": "S-a produs o eroare în timpul ștergerii {{title}}. Vă rugăm să verificați conexiunea și să încercați din nou.",
"emailOrPasswordIncorrect": "Adresa de e-mail sau parola este incorectă.",
"followingFieldsInvalid_many": "Următoarele câmpuri nu sunt valabile:",
"followingFieldsInvalid_other": "Următoarele câmpuri nu sunt valabile:",
"followingFieldsInvalid_one": "Următorul câmp nu este valid:",
"incorrectCollection": "Colecție incorectă",
"invalidFileType": "Tip de fișier invalid",
@@ -346,4 +346,4 @@
"viewingVersions": "Vizualizarea versiunilor pentru {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Vizualizarea versiunilor pentru globala {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Произошла ошибка при удалении файла.",
"deletingTitle": "При удалении {{title}} произошла ошибка. Пожалуйста, проверьте соединение и повторите попытку.",
"emailOrPasswordIncorrect": "Указанный email или пароль неверен.",
"followingFieldsInvalid_many": "Следующие поля недействительны:",
"followingFieldsInvalid_other": "Следующие поля недействительны:",
"followingFieldsInvalid_one": "Следующее поле недействительно:",
"incorrectCollection": "Неправильная Коллекция",
"invalidFileType": "Недопустимый тип файла",
@@ -346,4 +346,4 @@
"viewingVersions": "Просмотр версий для {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Просмотр версии для глобальной Коллекции {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Det gick inte att ta bort filen.",
"deletingTitle": "Det uppstod ett fel vid borttagningen av {{title}}. Vänligen kontrollera din anslutning och försök igen.",
"emailOrPasswordIncorrect": "E-postadressen eller lösenordet som angivits är felaktigt.",
"followingFieldsInvalid_many": "Följande fält är ogiltiga:",
"followingFieldsInvalid_other": "Följande fält är ogiltiga:",
"followingFieldsInvalid_one": "Följande fält är ogiltigt:",
"incorrectCollection": "Felaktig Samling",
"invalidFileType": "Ogiltig filtyp",
@@ -346,4 +346,4 @@
"viewingVersions": "Visar versioner för {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Visa versioner för den globala {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "เกิดปัญหาระหว่างการลบไฟล์",
"deletingTitle": "เกิดปัญหาระหว่างการลบ {{title}} โปรดตรวจสอบการเชื่อมต่อของคุณแล้วลองอีกครั้ง",
"emailOrPasswordIncorrect": "อีเมลหรือรหัสผ่านไม่ถูกต้อง",
"followingFieldsInvalid_many": "ช่องต่อไปนี้ไม่ถูกต้อง:",
"followingFieldsInvalid_other": "ช่องต่อไปนี้ไม่ถูกต้อง:",
"followingFieldsInvalid_one": "ช่องต่อไปนี้ไม่ถูกต้อง:",
"incorrectCollection": "Collection ไม่ถูกต้อง",
"invalidFileType": "ประเภทของไฟล์ไม่ถูกต้อง",
@@ -346,4 +346,4 @@
"viewingVersions": "กำลังดูเวอร์ชันของ {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "กำลังดูเวอร์ชันของ global {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Dosya silinirken bir hatayla karşılaşıldı.",
"deletingTitle": "{{title}} silinirken bir sorun yaşandı. Lütfen internet bağlantınızı kontrol edip tekrar deneyin.",
"emailOrPasswordIncorrect": "Girilen e-posta veya parola hatalı",
"followingFieldsInvalid_many": "Lütfen geçersiz alanları düzeltin:",
"followingFieldsInvalid_other": "Lütfen geçersiz alanları düzeltin:",
"followingFieldsInvalid_one": "Lütfen geçersiz alanı düzeltin:",
"incorrectCollection": "Hatalı koleksiyon",
"invalidFileType": "Geçersiz dosya türü",
@@ -346,4 +346,4 @@
"viewingVersions": "{{entityLabel}} {{documentTitle}} için sürümler gösteriliyor",
"viewingVersionsGlobal": "`Global {{entityLabel}} için sürümler gösteriliyor"
}
}
}

View File

@@ -252,7 +252,7 @@
"emailOrPasswordIncorrect": {
"type": "string"
},
"followingFieldsInvalid_many": {
"followingFieldsInvalid_other": {
"type": "string"
},
"followingFieldsInvalid_one": {
@@ -344,7 +344,7 @@
"deletingFile",
"deletingTitle",
"emailOrPasswordIncorrect",
"followingFieldsInvalid_many",
"followingFieldsInvalid_other",
"followingFieldsInvalid_one",
"incorrectCollection",
"invalidFileType",
@@ -1401,4 +1401,4 @@
"validation",
"version"
]
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Виникла помилка під час видалення файлу",
"deletingTitle": "Виникла помилка під час видалення {{title}}, Будь ласка, перевірте ваше з'єднання та спробуйте ще раз.",
"emailOrPasswordIncorrect": "Вказаний email або пароль не є вірними",
"followingFieldsInvalid_many": "Наступні поля не є вірними",
"followingFieldsInvalid_other": "Наступні поля не є вірними",
"followingFieldsInvalid_one": "Наступне поле не є вірним:",
"incorrectCollection": "Неправильна колекція",
"invalidFileType": "Невіртий тип файлу",
@@ -346,4 +346,4 @@
"viewingVersions": "Огляд версій для {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "Огляд версій для глобальної колекції {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "Lỗi - Đã xảy ra vấn đề khi xóa tệp này.",
"deletingTitle": "Lỗi - Đã xảy ra vấn đề khi xóa {{title}}. Hãy kiểm tra kết nối mạng và thử lại.",
"emailOrPasswordIncorrect": "Lỗi - Email hoặc mật khẩu không chính xác.",
"followingFieldsInvalid_many": "Lỗi - Những fields sau không hợp lệ:",
"followingFieldsInvalid_other": "Lỗi - Những fields sau không hợp lệ:",
"followingFieldsInvalid_one": "Lỗi - Field sau không hợp lệ:",
"incorrectCollection": "Lỗi - Collection không hợp lệ.",
"invalidFileType": "Lỗi - Định dạng tệp không hợp lệ.",
@@ -346,4 +346,4 @@
"viewingVersions": "Xem những phiên bản của {{entityLabel}} {{documentTitle}}",
"viewingVersionsGlobal": "`Xem những phiên bản toàn thể (global) của {{entityLabel}}"
}
}
}

View File

@@ -63,7 +63,7 @@
"deletingFile": "删除文件时出现了错误。",
"deletingTitle": "删除{{title}}时出现了错误。请检查您的连接并重试。",
"emailOrPasswordIncorrect": "提供的电子邮件或密码不正确。",
"followingFieldsInvalid_many": "以下字段是无效的:",
"followingFieldsInvalid_other": "以下字段是无效的:",
"followingFieldsInvalid_one": "下面的字段是无效的:",
"incorrectCollection": "不正确的集合",
"invalidFileType": "无效的文件类型",
@@ -346,4 +346,4 @@
"viewingVersions": "正在查看{{entityLabel}} {{documentTitle}}的版本",
"viewingVersionsGlobal": "正在查看全局{{entityLabel}}的版本"
}
}
}

View File

@@ -91,6 +91,18 @@ export default buildConfigWithDefaults({
});
},
},
{
type: 'relationship',
name: 'relationshipFilteredAsync',
relationTo: relationOneSlug,
filterOptions: async (args: FilterOptionsProps<FieldsRelationship>) => {
return ({
id: {
equals: args.data.relationship,
},
});
},
},
{
type: 'relationship',
name: 'relationshipManyFiltered',

View File

@@ -188,7 +188,7 @@ describe('fields - relationship', () => {
await expect(field).toHaveText(relationOneDoc.id);
});
test('should allow dynamic filterOptions', async () => {
async function runFilterOptionsTest(fieldName: string) {
await page.goto(url.edit(docWithExistingRelations.id));
// fill the first relation field
@@ -199,7 +199,7 @@ describe('fields - relationship', () => {
await expect(field).toContainText(relationOneDoc.id);
// then verify that the filtered field's options match
let filteredField = page.locator('#field-relationshipFiltered .react-select');
let filteredField = page.locator(`#field-${fieldName} .react-select`);
await filteredField.click({ delay: 100 });
const filteredOptions = filteredField.locator('.rs__option');
await expect(filteredOptions).toHaveCount(1); // one doc
@@ -211,12 +211,27 @@ describe('fields - relationship', () => {
await options.nth(1).click();
await expect(field).toContainText(anotherRelationOneDoc.id);
// Now, save the document. This should fail, as the filitered field doesn't match the selected relationship value
await page.locator('#action-save').click();
await expect(page.locator('.Toastify')).toContainText(`is invalid: ${fieldName}`);
// then verify that the filtered field's options match
filteredField = page.locator('#field-relationshipFiltered .react-select');
filteredField = page.locator(`#field-${fieldName} .react-select`);
await filteredField.click({ delay: 100 });
await expect(filteredOptions).toHaveCount(2); // two options because the currently selected option is still there
await filteredOptions.nth(1).click();
await expect(filteredField).toContainText(anotherRelationOneDoc.id);
// Now, saving the document should succeed
await saveDocAndAssert(page);
}
test('should allow dynamic filterOptions', async () => {
await runFilterOptionsTest('relationshipFiltered');
});
test('should allow dynamic async filterOptions', async () => {
await runFilterOptionsTest('relationshipFilteredAsync');
});
test('should allow usage of relationTo in filterOptions', async () => {