v2.15.0

Form

Компонент формы для валидации и обработки отправки.

Использование

Компонент Form проверяет данные формы любой библиотекой валидации, поддерживающей Standard Schema, например Valibot, Zod, Regle, Yup, Joi или Superstruct, либо вашей собственной логикой.

Вместе с компонентом FormField он автоматически показывает сообщения об ошибках рядом с элементами формы.

Валидация по схеме

Нужны два пропса:

  • state — реактивный объект с состоянием формы.
  • schema — любая схема Standard Schema или Superstruct.
Библиотека валидации по умолчанию не входит в поставку, установите нужную вам.
<script setup lang="ts">
import * as v from 'valibot'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = v.object({
  email: v.pipe(v.string(), v.email('Некорректный email')),
  password: v.pipe(v.string(), v.minLength(8, 'Минимум 8 символов'))
})

type Schema = v.InferOutput<typeof schema>

const state = reactive({
  email: '',
  password: ''
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import * as v from 'valibot'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = v.object({
  email: v.pipe(v.string(), v.email('Некорректный email')),
  password: v.pipe(v.string(), v.minLength(8, 'Минимум 8 символов'))
})

type Schema = v.InferOutput<typeof schema>

const state = reactive({
  email: '',
  password: ''
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>

Собственная валидация

Пропс validate подключает вашу логику валидации.

Функция валидации должна вернуть список ошибок с атрибутами:

  • message — сообщение об ошибке.
  • name — name поля FormField, которому адресована ошибка.
Её можно использовать вместе с пропсом schema в сложных случаях.
<script setup lang="ts">
import type { FormError, FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Обязательное поле' })
  if (!state.password) errors.push({ name: 'password', message: 'Обязательное поле' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :validate="validate" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import type { FormError, FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Обязательное поле' })
  if (!state.password) errors.push({ name: 'password', message: 'Обязательное поле' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :validate="validate" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>

Отображение ошибок

Ошибки сопоставляются с нужным FormField по его пропсу name. Ошибка поля email показывается в <FormField name="email">.

Вложенные поля сопоставляются через точку. Схема вида { user: z.object({ email: z.string() }) } применится к <FormField name="user.email">.

Имя ошибки у элемента массива включает индекс (например, tags.0, tags.1), поэтому только по name она не совпадёт с <FormField name="tags">. Чтобы их перехватить, передайте в пропс error-pattern регулярное выражение вроде /^tags\..+/. Это особенно полезно для компонентов вроде InputTags.
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  email: z.email('Некорректный email'),
  tags: z.array(z.string().regex(/^[a-z-]+$/, 'Только строчные буквы и дефисы')).min(1, 'Добавьте хотя бы один тег')
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  email: undefined,
  tags: []
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Теги" name="tags" :error-pattern="/^tags\..+/">
      <B24InputTags v-model="state.tags" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  email: z.email('Некорректный email'),
  tags: z.array(z.string().regex(/^[a-z-]+$/, 'Только строчные буквы и дефисы')).min(1, 'Добавьте хотя бы один тег')
})

type Schema = z.output<typeof schema>

const state = reactive<Partial<Schema>>({
  email: undefined,
  tags: []
})

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Теги" name="tags" :error-pattern="/^tags\..+/">
      <B24InputTags v-model="state.tags" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>

События ввода

Form автоматически запускает валидацию, когда элемент ввода генерирует событие input, change или blur.

  • Валидация по input происходит по мере ввода.
  • Валидация по change происходит, когда вы фиксируете значение.
  • Валидация по blur происходит, когда элемент теряет фокус.

Когда выполнять валидацию, определяет пропс validate-on.

При отправке форма проверяется всегда.
дд
мм
гггг
––
––
Вариант 1
Вариант 2
Вариант 3
Вариант 1
Вариант 2
Вариант 3
Перетащите изображение сюда
PNG (не более 1 МБ)
Отметьте меня
CheckboxGroup
Вариант 1
Вариант 2
Вариант 3
RadioGroup
Чтобы реализовать то же внутри собственных компонентов, используйте композабл useFormField.
Событие change у этих элементов — синтетическоеEvent, его target равен null: значения оно не несёт. @change="e => e.target.value" выбросит ошибку.Оно нужно, чтобы реагировать на фиксацию значения; значение через него не передаётся, и Form узнаёт о нём не так: валидацию запускает отдельный внутренний вызов. Читайте значение из @update:model-value или из v-model:
<template>
  <B24Select v-model="value" :items="items" @update:model-value="onCommit" />
</template>
Это относится ко всем элементам, которые генерируют change без нативного события: Select, SelectMenu, InputMenu, InputDate, InputTime, InputTags, InputNumber, InputRating, PinInput, Listbox, Range, Checkbox, CheckboxGroup, RadioGroup, Switch и FileUpload. Input и Textarea пробрасывают собственное событие change браузера, поэтому их target — настоящий элемент.

Событие error

На событие @error можно подписаться, чтобы обрабатывать ошибки. Оно срабатывает при отправке формы и содержит массив объектов FormError с полями:

  • id — id элемента ввода.
  • name — name поля FormField.
  • message — сообщение об ошибке.

Пример: после отправки формы фокус переходит на первый элемент с ошибкой:

<script setup lang="ts">
import type { FormError, FormErrorEvent, FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Обязательное поле' })
  if (!state.password) errors.push({ name: 'password', message: 'Обязательное поле' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}

async function onError(event: FormErrorEvent) {
  if (event?.errors?.[0]?.id) {
    const element = document.getElementById(event.errors[0].id)
    element?.focus()
    element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}
</script>

<template>
  <B24Form :validate="validate" :state="state" class="space-y-4" @submit="onSubmit" @error="onError">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import type { FormError, FormErrorEvent, FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  password: undefined
})

type Schema = typeof state

function validate(state: Partial<Schema>): FormError[] {
  const errors = []
  if (!state.email) errors.push({ name: 'email', message: 'Обязательное поле' })
  if (!state.password) errors.push({ name: 'password', message: 'Обязательное поле' })
  return errors
}

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}

async function onError(event: FormErrorEvent) {
  if (event?.errors?.[0]?.id) {
    const element = document.getElementById(event.errors[0].id)
    element?.focus()
    element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }
}
</script>

<template>
  <B24Form :validate="validate" :state="state" class="space-y-4" @submit="onSubmit" @error="onError">
    <B24FormField label="Email" name="email">
      <B24Input v-model="state.email" />
    </B24FormField>

    <B24FormField label="Пароль" name="password">
      <B24Input v-model="state.password" type="password" />
    </B24FormField>

    <B24Button color="air-primary" type="submit">
      Отправить
    </B24Button>
  </B24Form>
</template>

HTML5-валидация

При программном вызове form.submit() Form перед отправкой автоматически запускает нативную HTML5-валидацию.

Это особенно полезно, когда кнопка отправки находится вне элемента формы, например в футере модального окна.
<script setup lang="ts">
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  age: undefined
})

type Schema = typeof state

const form = useTemplateRef('form')

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <div class="space-y-4">
    <B24Form ref="form" :state="state" class="space-y-4" @submit="onSubmit">
      <B24FormField label="Email" name="email">
        <B24Input v-model="state.email" type="email" required class="w-full" />
      </B24FormField>

      <B24FormField label="Возраст" name="age">
        <B24InputNumber v-model="state.age" :min="18" :max="100" required class="w-full" />
      </B24FormField>
    </B24Form>

    <B24Button color="air-primary" @click="form?.submit()">
      Отправить
    </B24Button>
  </div>
</template>
<script setup lang="ts">
import { reactive, useTemplateRef } from 'vue'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const state = reactive({
  email: undefined,
  age: undefined
})

type Schema = typeof state

const form = useTemplateRef('form')

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <div class="space-y-4">
    <B24Form ref="form" :state="state" class="space-y-4" @submit="onSubmit">
      <B24FormField label="Email" name="email">
        <B24Input v-model="state.email" type="email" required class="w-full" />
      </B24FormField>

      <B24FormField label="Возраст" name="age">
        <B24InputNumber v-model="state.age" :min="18" :max="100" required class="w-full" />
      </B24FormField>
    </B24Form>

    <B24Button color="air-primary" @click="form?.submit()">
      Отправить
    </B24Button>
  </div>
</template>

Вложенные формы

Пропс nested позволяет вкладывать несколько компонентов Form друг в друга и связывать их функции валидации. Тогда валидация родительской формы автоматически проверяет и все вложенные.

Вложенные формы напрямую наследуют состояние родителя, отдельное состояние для них задавать не нужно. Пропс name указывает на вложенный атрибут в состоянии родителя.

Так можно динамически добавлять поля по вводу пользователя:

Подписаться на нашу рассылку
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  name: z.string().min(2),
  news: z.boolean().default(false)
})

type Schema = z.output<typeof schema>

const nestedSchema = z.object({
  email: z.email()
})

type NestedSchema = z.output<typeof nestedSchema>

const state = reactive<Partial<Schema & NestedSchema>>({ })

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form
    ref="form"
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <B24FormField label="Имя" name="name">
      <B24Input v-model="state.name" placeholder="John Lennon" />
    </B24FormField>

    <div>
      <B24Checkbox v-model="state.news" name="news" label="Подписаться на нашу рассылку" @update:model-value="state.email = undefined" />
    </div>

    <B24Form v-if="state.news" :schema="nestedSchema" nested>
      <B24FormField label="Email" name="email">
        <B24Input v-model="state.email" placeholder="john@lennon.com" />
      </B24FormField>
    </B24Form>

    <div>
      <B24Button color="air-primary" type="submit">
        Отправить
      </B24Button>
    </div>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  name: z.string().min(2),
  news: z.boolean().default(false)
})

type Schema = z.output<typeof schema>

const nestedSchema = z.object({
  email: z.email()
})

type NestedSchema = z.output<typeof nestedSchema>

const state = reactive<Partial<Schema & NestedSchema>>({ })

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form
    ref="form"
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <B24FormField label="Имя" name="name">
      <B24Input v-model="state.name" placeholder="John Lennon" />
    </B24FormField>

    <div>
      <B24Checkbox v-model="state.news" name="news" label="Подписаться на нашу рассылку" @update:model-value="state.email = undefined" />
    </div>

    <B24Form v-if="state.news" :schema="nestedSchema" nested>
      <B24FormField label="Email" name="email">
        <B24Input v-model="state.email" placeholder="john@lennon.com" />
      </B24FormField>
    </B24Form>

    <div>
      <B24Button color="air-primary" type="submit">
        Отправить
      </B24Button>
    </div>
  </B24Form>
</template>

Или проверять списки полей:

<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  customer: z.string().min(2)
})

type Schema = z.output<typeof schema>

const itemSchema = z.object({
  description: z.string().min(1),
  price: z.number().min(0)
})

type ItemSchema = z.output<typeof itemSchema>

const state = reactive<Partial<Schema & { items: Partial<ItemSchema>[] }>>({ })

function addItem() {
  if (!state.items) {
    state.items = []
  }
  state.items.push({})
}

function removeItem() {
  if (state.items) {
    state.items.pop()
  }
}

const toast = useToast()

async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <B24FormField label="Клиент" name="customer">
      <B24Input v-model="state.customer" placeholder="ООО «Ромашка»" />
    </B24FormField>

    <B24Form
      v-for="(item, count) in state.items"
      :key="count"
      :name="`items.${count}`"
      :schema="itemSchema"
      class="flex gap-2"
      nested
    >
      <B24FormField :label="!count ? 'Описание' : undefined" name="description">
        <B24Input v-model="item.description" />
      </B24FormField>
      <B24FormField :label="!count ? 'Цена' : undefined" name="price" class="w-20">
        <B24Input v-model="item.price" type="number" />
      </B24FormField>
    </B24Form>

    <div class="flex gap-2">
      <B24Button size="sm" @click="addItem()">
        Добавить элемент
      </B24Button>

      <B24Button size="sm" @click="removeItem()">
        Удалить элемент
      </B24Button>
    </div>
    <div>
      <B24Button color="air-primary" type="submit">
        Отправить
      </B24Button>
    </div>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'

const schema = z.object({
  customer: z.string().min(2)
})

type Schema = z.output<typeof schema>

const itemSchema = z.object({
  description: z.string().min(1),
  price: z.number().min(0)
})

type ItemSchema = z.output<typeof itemSchema>

const state = reactive<Partial<Schema & { items: Partial<ItemSchema>[] }>>({ })

function addItem() {
  if (!state.items) {
    state.items = []
  }
  state.items.push({})
}

function removeItem() {
  if (state.items) {
    state.items.pop()
  }
}

const toast = useToast()

async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Успешно', description: 'Форма отправлена.', color: 'air-primary-success' })
  console.log(event.data)
}
</script>

<template>
  <B24Form
    :state="state"
    :schema="schema"
    class="gap-4 flex flex-col w-60"
    @submit="onSubmit"
  >
    <B24FormField label="Клиент" name="customer">
      <B24Input v-model="state.customer" placeholder="ООО «Ромашка»" />
    </B24FormField>

    <B24Form
      v-for="(item, count) in state.items"
      :key="count"
      :name="`items.${count}`"
      :schema="itemSchema"
      class="flex gap-2"
      nested
    >
      <B24FormField :label="!count ? 'Описание' : undefined" name="description">
        <B24Input v-model="item.description" />
      </B24FormField>
      <B24FormField :label="!count ? 'Цена' : undefined" name="price" class="w-20">
        <B24Input v-model="item.price" type="number" />
      </B24FormField>
    </B24Form>

    <div class="flex gap-2">
      <B24Button size="sm" @click="addItem()">
        Добавить элемент
      </B24Button>

      <B24Button size="sm" @click="removeItem()">
        Удалить элемент
      </B24Button>
    </div>
    <div>
      <B24Button color="air-primary" type="submit">
        Отправить
      </B24Button>
    </div>
  </B24Form>
</template>

Примеры

Раздел редактирования записи

Типичный шаблон редактирования записи (UF placement, контекст слайдера): раздел с заголовком и полями с вертикальными подписями, двухколоночная строка «сумма + валюта», вложенный подраздел «Клиент» и набор дополнительных полей. Целиком собран из B24Form, B24FormField, B24Input, B24Select, B24InputNumber, B24InputDate, B24Popover и B24Calendar, без собственных компонентов.

Полный набор полей: стадия (B24Select), сумма и валюта (B24InputNumber + B24Select в двухколоночной строке), группа «Клиент» (компания и контакт в B24Input и ссылка «Добавить участника»), затем обращение (B24Select), фамилия и имя (B24Input), тип услуги (B24Select) и запланированная дата (B24InputDate с выпадающим B24Calendar в B24Popover).

Подраздел «Клиент» — это обычный <div> с подписью сверху и контейнером с рамкой (rounded-md border ... p-3 sm:p-4 space-y-4), в который вложены B24FormField; role="group" и aria-labelledby связывают подпись с группой. Двухколоночная строка «Сумма и валюта» использует grid-cols-1 sm:grid-cols-[1fr_auto], поэтому на узком экране валюта переносится под сумму. B24InputDate работает со значением @internationalized/date (не с нативным Date), поэтому в схеме это поле типизируется свободно.

Детали заказа

Клиент
дд
мм
гггг
<script setup lang="ts">
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'
import SettingsIcon from '@bitrix24/b24icons-vue/outline/SettingsIcon'
import CalendarIcon from '@bitrix24/b24icons-vue/outline/CalendarIcon'
import CirclePlusIcon from '@bitrix24/b24icons-vue/main/CirclePlusIcon'
import UserCompanyIcon from '@bitrix24/b24icons-vue/common-b24/UserCompanyIcon'
import PersonIcon from '@bitrix24/b24icons-vue/main/PersonIcon'

const stages = [
  'Проверка контактных данных',
  'Проектирование решения',
  'Ожидание комплектующих',
  'Запланировано',
  'Завершено'
]

const currencies = ['USD', 'EUR', 'RUB'] as const

const salutations = ['Г-н', 'Г-жа', 'Д-р', 'Не выбрано']

const serviceTypes = [
  'Монтаж на месте',
  'Удалённая настройка',
  'Консультация',
  'Договор обслуживания'
]

const schema = z.object({
  stage: z.string().min(1, 'Выберите стадию'),
  amount: z.number().nonnegative('Сумма должна быть не меньше 0'),
  currency: z.enum(currencies),
  company: z.string().optional(),
  contact: z.string().optional(),
  salutation: z.string().optional(),
  lastName: z.string().min(1, 'Укажите фамилию'),
  firstName: z.string().min(1, 'Укажите имя'),
  serviceType: z.string().min(1, 'Выберите тип услуги'),
  // B24InputDate работает с DateValue из @internationalized/date, а не с нативной датой Date,
  // поэтому поле здесь типизировано свободно, а не через z.date().
  scheduledAt: z.any().optional()
})

type Schema = z.output<typeof schema>

function defaultState(): Partial<Schema> {
  return {
    stage: 'Проверка контактных данных',
    amount: 0,
    currency: 'USD',
    company: undefined,
    contact: undefined,
    salutation: 'Не выбрано',
    lastName: 'Сидоров',
    firstName: 'Иван',
    serviceType: undefined,
    scheduledAt: undefined
  }
}

const state = reactive<Partial<Schema>>(defaultState())

const clientGroupId = useId()
const scheduledAtInput = useTemplateRef('scheduledAtInput')

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Заказ сохранён', description: 'Данные заказа отправлены.', color: 'air-primary-success' })
  console.log(event.data)
}

function onCancel() {
  Object.assign(state, defaultState())
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4 w-full max-w-lg" @submit="onSubmit">
    <div class="flex items-center justify-between gap-2 pb-2 border-b border-(--ui-color-divider-vibrant-default)">
      <h3 class="min-w-0 truncate text-(length:--ui-font-size-lg) font-(--ui-font-weight-semi-bold) uppercase tracking-wide">
        Детали заказа
      </h3>
      <B24Button color="air-tertiary-no-accent" size="sm" :icon="SettingsIcon" aria-label="Изменить раздел" class="shrink-0" />
    </div>

    <B24FormField label="Стадия" name="stage">
      <!-- У Select `class` относится к триггеру, а `b24ui.root` — к внешней обёртке, поэтому для элемента на всю ширину нужны оба. -->
      <B24Select v-model="state.stage" :items="stages" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Сумма и валюта" name="amount">
      <div class="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-2">
        <B24InputNumber v-model="state.amount" :min="0" class="w-full" />
        <!-- Строка проверяется в рамках поля `amount`; валюта — фиксированный enum со значением по умолчанию, отдельный слот ошибки ей не нужен. -->
        <B24Select v-model="state.currency" :items="[...currencies]" class="w-full sm:w-32" :b24ui="{ root: 'w-full sm:w-32' }" />
      </div>
    </B24FormField>

    <!-- Внутренний раздел «Клиент»: группа с подписью и рамкой из обычных элементов
         (в b24ui нет отдельного примитива fieldset). role/aria-labelledby связывают
         heading to the group for screen readers. -->
    <div class="space-y-1.5">
      <span :id="clientGroupId" class="block text-(length:--ui-font-size-sm) text-(--ui-color-typography-secondary)">
        Клиент
      </span>
      <div
        role="group"
        :aria-labelledby="clientGroupId"
        class="rounded-md border border-(--ui-color-design-outline-stroke) p-3 sm:p-4 space-y-4"
      >
        <B24FormField label="Компания" name="company">
          <B24Input
            v-model="state.company"
            :icon="UserCompanyIcon"
            placeholder="Название компании, телефон или email"
            class="w-full"
          />
        </B24FormField>

        <B24FormField label="Контакт" name="contact">
          <B24Input
            v-model="state.contact"
            :icon="PersonIcon"
            placeholder="Имя контакта, телефон или email"
            class="w-full"
          />
        </B24FormField>

        <B24Button color="air-tertiary-no-accent" size="sm" :icon="CirclePlusIcon" label="Добавить участника" />
      </div>
    </div>

    <B24FormField label="Обращение" name="salutation">
      <B24Select v-model="state.salutation" :items="salutations" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Фамилия" name="lastName">
      <B24Input v-model="state.lastName" class="w-full" />
    </B24FormField>

    <B24FormField label="Имя" name="firstName">
      <B24Input v-model="state.firstName" class="w-full" />
    </B24FormField>

    <B24FormField label="Тип услуги" name="serviceType">
      <B24Select v-model="state.serviceType" :items="serviceTypes" placeholder="Выберите услугу" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Запланированная дата" name="scheduledAt">
      <!-- Ввод даты текстом с выпадающим B24Calendar в слоте trailing; у обоих общий v-model. -->
      <B24InputDate ref="scheduledAtInput" v-model="state.scheduledAt" class="w-full">
        <template #trailing>
          <B24Popover :reference="scheduledAtInput?.inputsRef[3]?.$el">
            <B24Button
              color="air-tertiary-no-accent"
              size="sm"
              :icon="CalendarIcon"
              aria-label="Выберите дату"
              class="px-0"
            />

            <template #content>
              <B24Calendar v-model="state.scheduledAt" class="p-2" />
            </template>
          </B24Popover>
        </template>
      </B24InputDate>
    </B24FormField>

    <div class="flex flex-wrap justify-end gap-2 pt-2">
      <B24Button color="air-tertiary" label="Отмена" @click="onCancel" />
      <B24Button color="air-primary" type="submit" label="Сохранить" />
    </div>
  </B24Form>
</template>
<script setup lang="ts">
import { reactive, useTemplateRef, useId } from 'vue'
import * as z from 'zod'
import type { FormSubmitEvent } from '@bxshefby/b24ui-nuxt'
import SettingsIcon from '@bitrix24/b24icons-vue/outline/SettingsIcon'
import CalendarIcon from '@bitrix24/b24icons-vue/outline/CalendarIcon'
import CirclePlusIcon from '@bitrix24/b24icons-vue/main/CirclePlusIcon'
import UserCompanyIcon from '@bitrix24/b24icons-vue/common-b24/UserCompanyIcon'
import PersonIcon from '@bitrix24/b24icons-vue/main/PersonIcon'

const stages = [
  'Проверка контактных данных',
  'Проектирование решения',
  'Ожидание комплектующих',
  'Запланировано',
  'Завершено'
]

const currencies = ['USD', 'EUR', 'RUB'] as const

const salutations = ['Г-н', 'Г-жа', 'Д-р', 'Не выбрано']

const serviceTypes = [
  'Монтаж на месте',
  'Удалённая настройка',
  'Консультация',
  'Договор обслуживания'
]

const schema = z.object({
  stage: z.string().min(1, 'Выберите стадию'),
  amount: z.number().nonnegative('Сумма должна быть не меньше 0'),
  currency: z.enum(currencies),
  company: z.string().optional(),
  contact: z.string().optional(),
  salutation: z.string().optional(),
  lastName: z.string().min(1, 'Укажите фамилию'),
  firstName: z.string().min(1, 'Укажите имя'),
  serviceType: z.string().min(1, 'Выберите тип услуги'),
  // B24InputDate работает с DateValue из @internationalized/date, а не с нативной датой Date,
  // поэтому поле здесь типизировано свободно, а не через z.date().
  scheduledAt: z.any().optional()
})

type Schema = z.output<typeof schema>

function defaultState(): Partial<Schema> {
  return {
    stage: 'Проверка контактных данных',
    amount: 0,
    currency: 'USD',
    company: undefined,
    contact: undefined,
    salutation: 'Не выбрано',
    lastName: 'Сидоров',
    firstName: 'Иван',
    serviceType: undefined,
    scheduledAt: undefined
  }
}

const state = reactive<Partial<Schema>>(defaultState())

const clientGroupId = useId()
const scheduledAtInput = useTemplateRef('scheduledAtInput')

const toast = useToast()
async function onSubmit(event: FormSubmitEvent<Schema>) {
  toast.add({ title: 'Заказ сохранён', description: 'Данные заказа отправлены.', color: 'air-primary-success' })
  console.log(event.data)
}

function onCancel() {
  Object.assign(state, defaultState())
}
</script>

<template>
  <B24Form :schema="schema" :state="state" class="space-y-4 w-full max-w-lg" @submit="onSubmit">
    <div class="flex items-center justify-between gap-2 pb-2 border-b border-(--ui-color-divider-vibrant-default)">
      <h3 class="min-w-0 truncate text-(length:--ui-font-size-lg) font-(--ui-font-weight-semi-bold) uppercase tracking-wide">
        Детали заказа
      </h3>
      <B24Button color="air-tertiary-no-accent" size="sm" :icon="SettingsIcon" aria-label="Изменить раздел" class="shrink-0" />
    </div>

    <B24FormField label="Стадия" name="stage">
      <!-- У Select `class` относится к триггеру, а `b24ui.root` — к внешней обёртке, поэтому для элемента на всю ширину нужны оба. -->
      <B24Select v-model="state.stage" :items="stages" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Сумма и валюта" name="amount">
      <div class="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-2">
        <B24InputNumber v-model="state.amount" :min="0" class="w-full" />
        <!-- Строка проверяется в рамках поля `amount`; валюта — фиксированный enum со значением по умолчанию, отдельный слот ошибки ей не нужен. -->
        <B24Select v-model="state.currency" :items="[...currencies]" class="w-full sm:w-32" :b24ui="{ root: 'w-full sm:w-32' }" />
      </div>
    </B24FormField>

    <!-- Внутренний раздел «Клиент»: группа с подписью и рамкой из обычных элементов
         (в b24ui нет отдельного примитива fieldset). role/aria-labelledby связывают
         heading to the group for screen readers. -->
    <div class="space-y-1.5">
      <span :id="clientGroupId" class="block text-(length:--ui-font-size-sm) text-(--ui-color-typography-secondary)">
        Клиент
      </span>
      <div
        role="group"
        :aria-labelledby="clientGroupId"
        class="rounded-md border border-(--ui-color-design-outline-stroke) p-3 sm:p-4 space-y-4"
      >
        <B24FormField label="Компания" name="company">
          <B24Input
            v-model="state.company"
            :icon="UserCompanyIcon"
            placeholder="Название компании, телефон или email"
            class="w-full"
          />
        </B24FormField>

        <B24FormField label="Контакт" name="contact">
          <B24Input
            v-model="state.contact"
            :icon="PersonIcon"
            placeholder="Имя контакта, телефон или email"
            class="w-full"
          />
        </B24FormField>

        <B24Button color="air-tertiary-no-accent" size="sm" :icon="CirclePlusIcon" label="Добавить участника" />
      </div>
    </div>

    <B24FormField label="Обращение" name="salutation">
      <B24Select v-model="state.salutation" :items="salutations" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Фамилия" name="lastName">
      <B24Input v-model="state.lastName" class="w-full" />
    </B24FormField>

    <B24FormField label="Имя" name="firstName">
      <B24Input v-model="state.firstName" class="w-full" />
    </B24FormField>

    <B24FormField label="Тип услуги" name="serviceType">
      <B24Select v-model="state.serviceType" :items="serviceTypes" placeholder="Выберите услугу" class="w-full" :b24ui="{ root: 'w-full' }" />
    </B24FormField>

    <B24FormField label="Запланированная дата" name="scheduledAt">
      <!-- Ввод даты текстом с выпадающим B24Calendar в слоте trailing; у обоих общий v-model. -->
      <B24InputDate ref="scheduledAtInput" v-model="state.scheduledAt" class="w-full">
        <template #trailing>
          <B24Popover :reference="scheduledAtInput?.inputsRef[3]?.$el">
            <B24Button
              color="air-tertiary-no-accent"
              size="sm"
              :icon="CalendarIcon"
              aria-label="Выберите дату"
              class="px-0"
            />

            <template #content>
              <B24Calendar v-model="state.scheduledAt" class="p-2" />
            </template>
          </B24Popover>
        </template>
      </B24InputDate>
    </B24FormField>

    <div class="flex flex-wrap justify-end gap-2 pt-2">
      <B24Button color="air-tertiary" label="Отмена" @click="onCancel" />
      <B24Button color="air-primary" type="submit" label="Сохранить" />
    </div>
  </B24Form>
</template>

Собрать раздел формы редактирования записи (панель редактирования в слайдере или UF placement).

Раскладка формы задачи

Практический пример: форма задачи в стиле Битрикс24 из одних стандартных компонентов — Input для названия, Editor (с минимальной строкой панели) для описания, Card, Avatar и InputDate для блока ответственных и перенос строки с кнопками Button. Везде одна колонка, без собственного CSS сверх пропсов компонентов.

Постановщик
Джейн Купер
Исполнитель
Не назначен
Крайний срок
30
06
2026
Наблюдатели
<script setup lang="ts">
import type { EditorToolbarItem, IconComponent } from '@bxshefby/b24ui-nuxt'
import { CalendarDate } from '@internationalized/date'
import FileUploadIcon from '@bitrix24/b24icons-vue/main/FileUploadIcon'
import GoToLIcon from '@bitrix24/b24icons-vue/outline/GoToLIcon'
import PersonIcon from '@bitrix24/b24icons-vue/main/PersonIcon'
import MentionIcon from '@bitrix24/b24icons-vue/outline/MentionIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarIcon from '@bitrix24/b24icons-vue/outline/CalendarIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'
import TaskListIcon from '@bitrix24/b24icons-vue/outline/TaskListIcon'
import FolderPlusIcon from '@bitrix24/b24icons-vue/outline/FolderPlusIcon'
import UserGroupIcon from '@bitrix24/b24icons-vue/common-b24/UserGroupIcon'
import NotificationIcon from '@bitrix24/b24icons-vue/outline/NotificationIcon'
import BusinesProcessStagesIcon from '@bitrix24/b24icons-vue/outline/BusinesProcessStagesIcon'
import PinIcon from '@bitrix24/b24icons-vue/outline/PinIcon'
import BellIcon from '@bitrix24/b24icons-vue/main/BellIcon'
import ItemIcon from '@bitrix24/b24icons-vue/crm/ItemIcon'
import ArrowTopLIcon from '@bitrix24/b24icons-vue/outline/ArrowTopLIcon'
import ArrowDownLIcon from '@bitrix24/b24icons-vue/outline/ArrowDownLIcon'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import LayersIcon from '@bitrix24/b24icons-vue/outline/LayersIcon'
import ClockIcon from '@bitrix24/b24icons-vue/outline/ClockIcon'
import SettingsIcon from '@bitrix24/b24icons-vue/outline/SettingsIcon'

const title = ref('Разработать интерфейс новой формы задачи')
const description = ref('')
const deadline = shallowRef<CalendarDate | undefined>(new CalendarDate(2026, 6, 30))
const deadlineInput = useTemplateRef('deadlineInput')

const toolbarItems: EditorToolbarItem[][] = [[
  { kind: 'mention', icon: MentionIcon, tooltip: { text: 'Упоминание' } },
  { kind: 'bulletList', icon: BulletedListIcon, tooltip: { text: 'Маркированный список' } },
  { kind: 'orderedList', icon: NumberedListIcon, tooltip: { text: 'Нумерованный список' } }
]]

const actionButtons: { label: string, icon: IconComponent, active?: boolean }[] = [
  { label: 'Результаты', icon: CircleCheckIcon, active: true },
  { label: 'Файлы', icon: FileUploadIcon, active: true },
  { label: 'Чек-листы', icon: TaskListIcon },
  { label: 'Проект', icon: FolderPlusIcon },
  { label: 'Соисполнители', icon: UserGroupIcon },
  { label: 'Наблюдатели', icon: NotificationIcon },
  { label: 'Поток', icon: BusinesProcessStagesIcon },
  { label: 'Теги', icon: PinIcon, active: true },
  { label: 'Напоминания', icon: BellIcon },
  { label: 'Элементы CRM', icon: ItemIcon },
  { label: 'Родительская задача', icon: ArrowTopLIcon },
  { label: 'Подзадачи', icon: ArrowDownLIcon },
  { label: 'Связанные задачи', icon: LinkIcon },
  { label: 'Gantt', icon: LayersIcon },
  { label: 'Планирование по шкале времени', icon: CalendarIcon },
  { label: 'Учёт времени', icon: ClockIcon },
  { label: 'Пользовательские поля', icon: SettingsIcon }
]
</script>

<template>
  <div class="flex flex-col gap-4 p-4 w-full">
    <B24Input
      v-model="title"
      placeholder="Название задачи"
      size="xl"
      no-border
      :b24ui="{ base: 'font-(--ui-font-weight-semi-bold)' }"
    />

    <B24Card :b24ui="{ body: 'p-0' }">
      <B24Editor
        v-slot="{ editor }"
        v-model="description"
        content-type="markdown"
        placeholder="Добавьте описание задачи..."
        :b24ui="{ base: 'min-h-48 px-4 py-3' }"
      >
        <div class="flex items-center gap-1 px-2 py-1.5 border-b border-(--ui-color-divider-default)">
          <B24Button :icon="FileUploadIcon" color="air-tertiary" variant="ghost" size="sm" aria-label="Прикрепить файл" />
          <B24EditorToolbar :editor="editor" :items="toolbarItems" />
          <div class="ms-auto">
            <B24Button :icon="GoToLIcon" color="air-tertiary" variant="ghost" size="sm" aria-label="Развернуть редактор" />
          </div>
        </div>
      </B24Editor>
    </B24Card>

    <B24Card :b24ui="{ body: 'p-0' }">
      <div class="divide-y divide-(--ui-color-divider-default)">
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Постановщик</span>
          <div class="flex items-center gap-2 min-w-0">
            <B24Avatar :icon="PersonIcon" color="air-secondary-accent-2" size="xs" />
            <span class="text-sm truncate">Джейн Купер</span>
          </div>
        </div>
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Исполнитель</span>
          <div class="flex items-center gap-2 min-w-0">
            <B24Avatar :icon="PersonIcon" color="air-secondary-alert" size="xs" />
            <span class="text-sm truncate">Не назначен</span>
          </div>
        </div>
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Крайний срок</span>
          <B24InputDate ref="deadlineInput" v-model="deadline" size="sm" no-border class="flex-1">
            <template #trailing>
              <B24Popover :reference="deadlineInput?.inputsRef[3]?.$el">
                <B24Button
                  color="air-tertiary-no-accent"
                  size="sm"
                  :icon="CalendarIcon"
                  aria-label="Выберите дату"
                  class="px-0"
                />
                <template #content>
                  <B24Calendar v-model="deadline" class="p-2" />
                </template>
              </B24Popover>
            </template>
          </B24InputDate>
        </div>
      </div>
    </B24Card>

    <B24Card>
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-sm font-(--ui-font-weight-medium)">Наблюдатели</span>
          <B24Button :icon="PlusLIcon" color="air-tertiary" variant="ghost" size="xs" aria-label="Добавить наблюдателя" />
        </div>
      </template>
      <div class="flex flex-wrap gap-2">
        <B24Avatar :icon="PersonIcon" color="air-secondary-accent-2" size="xs" />
        <B24Avatar :icon="PersonIcon" color="air-secondary-alert" size="xs" />
        <B24Avatar :icon="PersonIcon" color="air-secondary" size="xs" />
      </div>
    </B24Card>

    <div class="flex flex-wrap gap-2">
      <B24Button
        v-for="btn in actionButtons"
        :key="btn.label"
        :icon="btn.icon"
        :label="btn.label"
        :color="btn.active ? 'air-secondary-accent-2' : 'air-secondary-no-accent'"
        :aria-pressed="btn.active ? 'true' : 'false'"
        size="sm"
      />
    </div>

    <div class="flex gap-2 justify-end">
      <B24Button label="Сохранить" color="air-primary" />
      <B24Button label="Отмена" color="air-tertiary" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, shallowRef, useTemplateRef } from 'vue'
import type { EditorToolbarItem, IconComponent } from '@bxshefby/b24ui-nuxt'
import { CalendarDate } from '@internationalized/date'
import FileUploadIcon from '@bitrix24/b24icons-vue/main/FileUploadIcon'
import GoToLIcon from '@bitrix24/b24icons-vue/outline/GoToLIcon'
import PersonIcon from '@bitrix24/b24icons-vue/main/PersonIcon'
import MentionIcon from '@bitrix24/b24icons-vue/outline/MentionIcon'
import BulletedListIcon from '@bitrix24/b24icons-vue/outline/BulletedListIcon'
import NumberedListIcon from '@bitrix24/b24icons-vue/outline/NumberedListIcon'
import PlusLIcon from '@bitrix24/b24icons-vue/outline/PlusLIcon'
import CalendarIcon from '@bitrix24/b24icons-vue/outline/CalendarIcon'
import CircleCheckIcon from '@bitrix24/b24icons-vue/outline/CircleCheckIcon'
import TaskListIcon from '@bitrix24/b24icons-vue/outline/TaskListIcon'
import FolderPlusIcon from '@bitrix24/b24icons-vue/outline/FolderPlusIcon'
import UserGroupIcon from '@bitrix24/b24icons-vue/common-b24/UserGroupIcon'
import NotificationIcon from '@bitrix24/b24icons-vue/outline/NotificationIcon'
import BusinesProcessStagesIcon from '@bitrix24/b24icons-vue/outline/BusinesProcessStagesIcon'
import PinIcon from '@bitrix24/b24icons-vue/outline/PinIcon'
import BellIcon from '@bitrix24/b24icons-vue/main/BellIcon'
import ItemIcon from '@bitrix24/b24icons-vue/crm/ItemIcon'
import ArrowTopLIcon from '@bitrix24/b24icons-vue/outline/ArrowTopLIcon'
import ArrowDownLIcon from '@bitrix24/b24icons-vue/outline/ArrowDownLIcon'
import LinkIcon from '@bitrix24/b24icons-vue/outline/LinkIcon'
import LayersIcon from '@bitrix24/b24icons-vue/outline/LayersIcon'
import ClockIcon from '@bitrix24/b24icons-vue/outline/ClockIcon'
import SettingsIcon from '@bitrix24/b24icons-vue/outline/SettingsIcon'

const title = ref('Разработать интерфейс новой формы задачи')
const description = ref('')
const deadline = shallowRef<CalendarDate | undefined>(new CalendarDate(2026, 6, 30))
const deadlineInput = useTemplateRef('deadlineInput')

const toolbarItems: EditorToolbarItem[][] = [[
  { kind: 'mention', icon: MentionIcon, tooltip: { text: 'Упоминание' } },
  { kind: 'bulletList', icon: BulletedListIcon, tooltip: { text: 'Маркированный список' } },
  { kind: 'orderedList', icon: NumberedListIcon, tooltip: { text: 'Нумерованный список' } }
]]

const actionButtons: { label: string, icon: IconComponent, active?: boolean }[] = [
  { label: 'Результаты', icon: CircleCheckIcon, active: true },
  { label: 'Файлы', icon: FileUploadIcon, active: true },
  { label: 'Чек-листы', icon: TaskListIcon },
  { label: 'Проект', icon: FolderPlusIcon },
  { label: 'Соисполнители', icon: UserGroupIcon },
  { label: 'Наблюдатели', icon: NotificationIcon },
  { label: 'Поток', icon: BusinesProcessStagesIcon },
  { label: 'Теги', icon: PinIcon, active: true },
  { label: 'Напоминания', icon: BellIcon },
  { label: 'Элементы CRM', icon: ItemIcon },
  { label: 'Родительская задача', icon: ArrowTopLIcon },
  { label: 'Подзадачи', icon: ArrowDownLIcon },
  { label: 'Связанные задачи', icon: LinkIcon },
  { label: 'Gantt', icon: LayersIcon },
  { label: 'Планирование по шкале времени', icon: CalendarIcon },
  { label: 'Учёт времени', icon: ClockIcon },
  { label: 'Пользовательские поля', icon: SettingsIcon }
]
</script>

<template>
  <div class="flex flex-col gap-4 p-4 w-full">
    <B24Input
      v-model="title"
      placeholder="Название задачи"
      size="xl"
      no-border
      :b24ui="{ base: 'font-(--ui-font-weight-semi-bold)' }"
    />

    <B24Card :b24ui="{ body: 'p-0' }">
      <B24Editor
        v-slot="{ editor }"
        v-model="description"
        content-type="markdown"
        placeholder="Добавьте описание задачи..."
        :b24ui="{ base: 'min-h-48 px-4 py-3' }"
      >
        <div class="flex items-center gap-1 px-2 py-1.5 border-b border-(--ui-color-divider-default)">
          <B24Button :icon="FileUploadIcon" color="air-tertiary" variant="ghost" size="sm" aria-label="Прикрепить файл" />
          <B24EditorToolbar :editor="editor" :items="toolbarItems" />
          <div class="ms-auto">
            <B24Button :icon="GoToLIcon" color="air-tertiary" variant="ghost" size="sm" aria-label="Развернуть редактор" />
          </div>
        </div>
      </B24Editor>
    </B24Card>

    <B24Card :b24ui="{ body: 'p-0' }">
      <div class="divide-y divide-(--ui-color-divider-default)">
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Постановщик</span>
          <div class="flex items-center gap-2 min-w-0">
            <B24Avatar :icon="PersonIcon" color="air-secondary-accent-2" size="xs" />
            <span class="text-sm truncate">Джейн Купер</span>
          </div>
        </div>
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Исполнитель</span>
          <div class="flex items-center gap-2 min-w-0">
            <B24Avatar :icon="PersonIcon" color="air-secondary-alert" size="xs" />
            <span class="text-sm truncate">Не назначен</span>
          </div>
        </div>
        <div class="flex items-center gap-3 px-5 py-3">
          <span class="text-description text-sm w-28 shrink-0">Крайний срок</span>
          <B24InputDate ref="deadlineInput" v-model="deadline" size="sm" no-border class="flex-1">
            <template #trailing>
              <B24Popover :reference="deadlineInput?.inputsRef[3]?.$el">
                <B24Button
                  color="air-tertiary-no-accent"
                  size="sm"
                  :icon="CalendarIcon"
                  aria-label="Выберите дату"
                  class="px-0"
                />
                <template #content>
                  <B24Calendar v-model="deadline" class="p-2" />
                </template>
              </B24Popover>
            </template>
          </B24InputDate>
        </div>
      </div>
    </B24Card>

    <B24Card>
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-sm font-(--ui-font-weight-medium)">Наблюдатели</span>
          <B24Button :icon="PlusLIcon" color="air-tertiary" variant="ghost" size="xs" aria-label="Добавить наблюдателя" />
        </div>
      </template>
      <div class="flex flex-wrap gap-2">
        <B24Avatar :icon="PersonIcon" color="air-secondary-accent-2" size="xs" />
        <B24Avatar :icon="PersonIcon" color="air-secondary-alert" size="xs" />
        <B24Avatar :icon="PersonIcon" color="air-secondary" size="xs" />
      </div>
    </B24Card>

    <div class="flex flex-wrap gap-2">
      <B24Button
        v-for="btn in actionButtons"
        :key="btn.label"
        :icon="btn.icon"
        :label="btn.label"
        :color="btn.active ? 'air-secondary-accent-2' : 'air-secondary-no-accent'"
        :aria-pressed="btn.active ? 'true' : 'false'"
        size="sm"
      />
    </div>

    <div class="flex gap-2 justify-end">
      <B24Button label="Сохранить" color="air-primary" />
      <B24Button label="Отмена" color="air-tertiary" />
    </div>
  </div>
</template>

Собрать форму задачи в стиле Битрикс24 из стандартных компонентов b24ui.

API

Пропсы

Prop Default Type
id string | number
schema S

Schema to validate the form state. Supports Standard Schema objects, Yup, Joi, and Superstructs.

state N extends false ? FormState<S> : never

An object representing the current state of the form.

validate (state: Partial<InferInput<S>>): FormError<string>[] | Promise<FormError<string>[]>

Custom validation function to validate the form state.

validateOn`['blur', 'change', 'input']` FormInputEvents[]

The list of input events that trigger the form validation.

disabledboolean

Disable all inputs inside the form.

name string

The name attribute of the form element. For nested forms (nested is true), this is also used as the path of the form's state within its parent form.

validateOnInputDelay300 number

Delay in milliseconds before validating the form on input events.

transformtrue as T T

If true, applies schema transformations on submit.

nested`false` N

If true, this form will attach to its parent Form and validate at the same time.

loadingAutotrueboolean

When true, all form elements will be disabled on @submit event. This will cause any focused input elements to lose their focus state.

acceptcharset string
action string
autocomplete string
enctype string
method string
novalidate false | true | "true" | "false"
target string
b24ui { base?: any; }
Компонент поддерживает и все нативные HTML-атрибуты <form>.

Слоты

Slot Type
default{ errors: FormErrorWithId[]; loading: boolean; }

События

Event Type
submit[event: FormSubmitEvent<FormData<S, T>>]
error[event: FormErrorEvent]

Доступ через ref

Типизированный экземпляр компонента доступен через useTemplateRef.

<script setup lang="ts">
const form = useTemplateRef('form')
</script>

<template>
  <B24Form ref="form" />
</template>

Так вы получите доступ к следующему:

ИмяТип
submit()Promise<void>

Запускает отправку формы с HTML5-валидацией.

validate(opts: { name?: keyof T | (keyof T)[], silent?: boolean, nested?: boolean, transform?: boolean })Promise<T>

Запускает валидацию формы. Показывает ошибки, если не передан opts.silent со значением true.

clear(path?: keyof T | RegExp)void

Очищает ошибки формы по указанному пути. Без пути очищает все ошибки.

getErrors(path?: keyof T | RegExp)FormErrorWithId[]

Возвращает ошибки формы по указанному пути. Без пути возвращает все ошибки.

setErrors(errors: FormError[], name?: keyof T | RegExp)void

Задаёт ошибки формы для указанного пути. Без пути заменяет все ошибки.

errorsRef<FormErrorWithId[]>

Ссылка на массив с ошибками валидации. Через неё можно читать и изменять сведения об ошибках.

disabledRef<boolean>
dirtyRef<boolean> true, если пользователь изменил хотя бы одно поле формы.
dirtyFieldsReadonlySet<DeepReadonly<keyof T>> Отслеживает поля, изменённые пользователем.
touchedFieldsReadonlySet<DeepReadonly<keyof T>> Отслеживает поля, с которыми взаимодействовал пользователь.
blurredFieldsReadonlySet<DeepReadonly<keyof T>> Отслеживает поля, потерявшие фокус.

Тема

https://github.com/bx-shef/b24-ui/tree/main/src/theme/form.ts
export default {
  base: ''
}