How to check field type

Is there a way to check the type of field programmatically before using it? I see that there are methods for a field that are intended to be used with a certain type of field, but I can’t seem to find a way to actually check the type before using it.

for instance, when I use below code,

foreach($page->content()->fields() as $key => $field){
  // how to check if this field is type "files"?
  $files = $field->toFiles();
}

I want check first whether a given $field is a structure or files type. Is it possible to do this?

This information is only available via the page blueprint, see Accessing blueprints | Kirby CMS.

Is there a reason why you loop through all fields, rather than calling fields specifically?

Oh so I guess this would be a bit complicated.
Thank you for your help.

In my use case, I was using a route plugin to get all the fields in a page when requested from the frontend via a single GET request. I am trying use kirby as a headless cms, and I am trying to use the values of the fields in the frontend with javascript, so I needed structure fields and files fields to return data differently.

If there were just few of fields, I would have just called them one by one by their name like you mentioned. But there were over 50 different fields involved, and I thought it would be nice to loop through the fields and simplify my code.

From what I understand, It seems like I should have had sent the name and types of fields from the frontend in the first place and iterate through this data on the route action function when requested.

But from my current state that I have worked so far, I think it would be easier for me to check the key name of a field in the forloop because I have set the name of the fields with some rules, like below. (although I guess this would not be a general solution)

foreach($page->content()->fields() as $key => $field){
  if(str_contains($key, 'some-name-rule')){
    $files = $field->toFiles();
  }
}

Not really, you can load the blueprint fields once before your loop, then get all the data you need from that.

1 Like

@texnixe I thought about this the wrong way the first time. It was actually really easy to do what I wanted with the link you shared me. Thank you!

So I ended up fixing my code like below.

$page_fields = $page->blueprint()->fields();
foreach($page_fields as $page_field){
  $field_type = $page_field['type'];
  $field_name = $page_field['name'];
  $field = $page->content()->get($field_name);
  if($field_type == 'structure'){
    $structure = $field->toStructure();
  }else if($field_type == 'file'){
    $files = $field->toFiles();
  }
}

It turned out for my use, just using the forloop with the blueprint fields once was enough!