Struct FormControl

Source
pub struct FormControl { /* private fields */ }
Expand description

§Form Control field

Global form control for most Bootstrap form fields. See:

  • FormControlType to define the type of input
  • FormControlProps to list the properties for the component. Note that some fields are ignored or may not work correctly depending on the type of input (See Bootstrap documentation for details)

§Examples

Basic text field:

use yew::prelude::*;
use yew_bootstrap::component::form::*;
fn test() -> Html {
  html! {
    <FormControl
        id="input-text"
        ctype={FormControlType::Text}
        class="mb-3"
        label="Text"
        value="Initial text"
    />
  }
}

Some input types need parameters for the ctype enum. Optional parameters use Option enums.

use yew::prelude::*;
use yew_bootstrap::component::form::*;
fn test() -> Html {
  html! {
    <FormControl
        id="input-number"
        ctype={
            FormControlType::Number {
                min: Some(10),
                max: Some(20)
            }
        }
        class="mb-3"
        label="Number in range 10-20"
        value="12"
    />
  }
}

Almost all properties are AttrValue type, and need to be converted into the correct format, as required by the input. For example for a DateTime with range input:

use yew::prelude::*;
use yew_bootstrap::component::form::*;
fn test() -> Html {
  html! {
    <FormControl
        id="input-datetime2"
        ctype={
            FormControlType::DatetimeMinMax {
                min: Some(AttrValue::from("2023-01-01T12:00")),
                max: Some(AttrValue::from("2023-01-01T18:00"))
            }
        }
        class="mb-3"
        label="Date and time (1st Jan 2023, 12:00 to 18:00)"
        value="2023-01-01T15:00"
    />
  }
}

Select input is the only input that can receive children, of type SelectOption or SelectOptgroup. For example:

use yew::prelude::*;
use yew_bootstrap::component::form::*;
fn test() -> Html {
  html! {
    <FormControl
        id="input-select-feedback"
        ctype={ FormControlType::Select}
        class="mb-3"
        label={ "Form control invalid" }
        validation={
            FormControlValidation::Invalid(AttrValue::from("Select an option"))
        }
    >
      <SelectOption key=0 label="Select an option" selected=true />
      <SelectOption key=1 label="Option 1" value="1"/>
      <SelectOption key=2 label="Option 2" value="2"/>
      <SelectOption key=3 label="Option 3" value="3"/>
    </FormControl>
  }
}

onclick, oninput and onchange events are available. onchange should be preferred for most inputs, but for text inputs (Text, TextArea, Number, etc), onchange is only called when the input looses focus, while oninput is called each time a key is pressed.

In the callback, the target needs to be converted to a descendent of HtmlElement to access the fields (Like type, name and value). All inputs can be converted to HtmlInputElement but Select and TextArea. This is an example of callback function to convert to the correct type; checkbox is special as the checked property should be used.

Note: HtmlTextAreaElement and HtmlSelectElement are not enabled by default and need the feature to be required:

web-sys = { version = "0.3.*", features = ["HtmlTextAreaElement", "HtmlSelectElement"] }
use wasm_bindgen::JsCast;
use web_sys::{EventTarget, HtmlTextAreaElement, HtmlSelectElement, HtmlInputElement};
use yew::prelude::*;

enum Msg {
  None,
  InputStrChanged { name: String, value: String },
  InputBoolChanged { name: String, value: bool },
}

let onchange = Callback::from(move |event: Event| -> Msg {
  let target: Option<EventTarget> = event.target();

  // Input element
  let input = target.clone().and_then(|t| t.dyn_into::<HtmlInputElement>().ok());
  if let Some(input) = input {
      let value = match &input.type_()[..] {
          "checkbox" => Msg::InputBoolChanged { name: input.name(), value: input.checked() },
          _ => Msg::InputStrChanged { name: input.name(), value: input.value() }
      };
      return value;
  }

  // Select element
  let input = target.clone().and_then(|t| t.dyn_into::<HtmlSelectElement>().ok());
  if let Some(input) = input {
      return Msg::InputStrChanged { name: input.name(), value: input.value() }
  }

  // TextArea element
  let input = target.and_then(|t| t.dyn_into::<HtmlTextAreaElement>().ok());
  if let Some(input) = input {
      return Msg::InputStrChanged { name: input.name(), value: input.value() }
  }

  Msg::None
});

Trait Implementations§

Source§

impl BaseComponent for FormControl
where Self: 'static,

Source§

type Message = ()

The Component’s Message.
Source§

type Properties = FormControlProps

The Component’s Properties.
Source§

fn create(ctx: &Context<Self>) -> Self

Creates a component.
Source§

fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool

Updates component’s internal state.
Source§

fn changed( &mut self, _ctx: &Context<Self>, _old_props: &Self::Properties, ) -> bool

React to changes of component properties.
Source§

fn view(&self, ctx: &Context<Self>) -> HtmlResult

Returns a component layout to be rendered.
Source§

fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool)

Notified after a layout is rendered.
Source§

fn destroy(&mut self, _ctx: &Context<Self>)

Notified before a component is destroyed.
Source§

fn prepare_state(&self) -> Option<String>

Prepares the server-side state.
Source§

impl Debug for FormControl

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FunctionProvider for FormControl

Source§

type Properties = FormControlProps

Properties for the Function Component.
Source§

fn run(ctx: &mut HookContext, props: &Self::Properties) -> HtmlResult

Render the component. This function returns the Html to be rendered for the component. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoPropValue<Option<T>> for T

Source§

fn into_prop_value(self) -> Option<T>

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<T> for T

Source§

fn into_prop_value(self) -> T

Convert self to a value of a Properties struct.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<Token, Builder, How> AllPropsFor<Builder, How> for Token
where Builder: Buildable<Token>, <Builder as Buildable<Token>>::WrappedToken: HasAllProps<<Builder as Buildable<Token>>::Output, How>,

Source§

impl<T> HasAllProps<(), T> for T