1

I want to show some input fields on frontend template form.

Type of input is dependent on the type of fields selected on the backend.

For example, if the text field is selected in the backend I will create a field of type="text". If a number field is selected I will show an input type="number" in the template.

I am trying to get the field type in my plugin.

$fields = Craft::$app->fields->getAllFields();
        foreach ($fields as $field) {
             $output[(int) $field->id] = array(
                'id'            => (int) $field->id,
                'handle'        => $field->handle,
                'name'          => $field->name,
                'instructions'  => $field->instructions
            );
        }

I checked the /vendor/craftcms/cms/src/services/Fields.php but not found any method.

Update: I checked a few files and i found a method which returns the string.

$field->displayName();
  1. Number
  2. Lightswitch

Is it the only way to get the type of field.

2

Making sure you include use craft\db\Query; at the top of your Class, you can do something like this:

$fields = (new Query())
    ->select(['id','handle','name','instructions','type'])
    ->from(['{{%fields}}'])
    ->all();

foreach ($fields as $field) {
    $output[(int) $field['id']] = array(
        'id'            => (int) $field['id'],
        'handle'        => $field['handle'],
        'name'          => $field['name'],
        'instructions'  => $field['instructions'],
        'type'          => $field['type']
    );
}
  • @Oil I tried the direct query as you suggested and i got the array pastebin.com/DW4D0pRE, so i still need to pregmatch on type . – inrsaurabh Jun 1 at 13:37
  • I'm not sure I understand what you are trying to do? – Oli Jun 1 at 13:56
  • As per field type I will show input of same type in frontend. – inrsaurabh Jun 1 at 13:58
  • I'm confused. Do you mean field type or input type? Field type for me would be something like craft\fields\PlainText which the above gives you..? – Oli Jun 1 at 14:03
  • @Oil I tried to update my question.By the way, your custom query is still helpful for me, as i don't think of query directly. +1 – inrsaurabh Jun 1 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.