Jump to content

Fieldtype YAML


owzim
 Share

Recommended Posts

You shall not objectify people, but you could objectify Textfields!!! :biggrin:
 
Github: https://github.com/owzim/pw-fieldtype-yaml

Module page: http://modules.processwire.com/modules/fieldtype-yaml/
 
Summary
 
Field that stores YAML data and formats it as an object, when requested.
 
Setup

After installation create a new field, let's say called "people" and assign it to a template, or just edit an existing text-based field and choose Yaml for the type, save!

In the Details-Tab you have an additional option, the Texformatter option is removed, because it does not make sense in this case.
 
Parse as

Default is WireArray/WireData, the data can also be parsed as Object or Associative Array.

Associative Array is the fastest and the default output by the used Spyc parser, WireArray/WireData might be the slowest, but it's also the most feature rich. You can access properties like you are used to with pages or fields, like $page->person->get('title|name') or $page->people->find('age>30').


Usage

Now, in your just created field you can put in some YAML like this:
 

- name: Jane Doe
  occupation: Product Manager
  age: 33
  hobbies:
    - running
    - movies
- name: John Doe
  occupation: Service Worker
  age: 28
  hobbies:
    - cycling
    - fishing

In your template, or wherever you are accessing the page, you would use it like any other ProcesssWire data (if you set the parse option to either WireData or Object):
 

$out = '';
foreach ($page->people as $person) {
    $out .= "Name: {$person->name} <br>";
    $out .= "Occupation: {$person->occupation} <br>";
    $out .= "Age: {$person->age} <br>";
    $out .= "Hobbies: <br>";
    foreach ($person->hobbies as $hobby) {
        $out .= "- {$hobby} <br>";
    }
    $out .= "--- <br>";
}
echo $out;

 
More info about YAML:

Acknowledgements

Edit: updated the repo link

  • Like 17
Link to comment
Share on other sites

@ozwim - awesome module, this will make me lose sleep.

Is there any way to use get on the yaml without having to first create a new wire array and add the yaml to that..

for example, i have this YAML:

- name: address
  street: 27 Hawthorne Lane
  city: New York
  state: NY
  zip: 10982
  phones:
    main: (999) 888 9874
    fax: (555) 548-5647
- name: facebook
  url: http://www.facebook.com
- name: site_title
  value: My Awesome Site

and i'm outputting like this for now, since it works:

$settings_yaml = $pages->get(1644)->settings_yaml;
$settings = new WireArray();

foreach($settings_yaml as $sy) {	
	$settings->add($sy);
}

$site_title = $settings->get("name=site_title")->value;
$address = $settings->get("name=address");
$facebook = $settings->get("name=facebook");

echo $address->street;
echo $address->city;
echo $address->phones->main;
echo $address->phones->fax;

echo $facebook->url;
echo $site_title;

TIA!

Link to comment
Share on other sites

Macrura, thanks for testing/using the module.

The current master branch only uses WireData on object like structures and regular arrays for numeric key structures.

I renamed the module to FieldtypeDataStructrue (because it now supports more than YAML) and have a separate repo for that, what you want is all there on the dev branch.

Check it out, I added a bunch of features (including your wanted WireArray output and a couple of new input/structure types, beside YAML) and the whole thing is unit tested, so it SHOULD be pretty stable:

https://github.com/owzim/FieldtypeDataStructure/tree/dev

More detailed info on the new version: https://github.com/owzim/FieldtypeDataStructure/blob/dev/README.md

For now you should create a new field and not change the fieldtype on your existing one to the new FieldtypeDataStructrue

I think it now became pretty powerful, I am planning to make a video to cover it and all it's possible use cases.

Please (all) share your thoughts on how else it could be used.

  • Like 5
Link to comment
Share on other sites

cool.. this is all working great... will update my other post with the changes to the required code to output...

as far as uses:

- use a field for quickly importing child pages using structured data

- use for editable settings (site settings, sliders, portfolios, other jquery plugins with a lot of parameters)

thanks again for making this!

  • Like 1
Link to comment
Share on other sites

another use i just found is for rapid prototyping of repeating content, prior to committing to real fields.

for example i'm making a testimonials slider for a client, but they have been tentative about many things on their site, so i'm not setting up any fixed fields now until they commit to certain elements of the front end;

example

- author: William
  role: Client
  text: Integer eu libero sit amet nisl vestibulum semper. Fusce nec porttitor massa. In nec neque elit. Curabitur malesuada ligula vitae purus ornare onec etea magna diam varius.
- author: James
  role: Hippie
  text: Posuere erat a ante venenatis dapibus posuere velit aliquet. Duis llis, est non coeammodo luctus, nisi erat porttitor ligula, egeteas laciniato odiomo sem.
  • Like 2
Link to comment
Share on other sites

Macrura, nice.
 
Please be aware of some possible YAML parsing pifalls. It's always advised to wrap strings, that are more than just one word in quotes, or prepend them with a pipe symbol. Commas are interpreted as array separators, so your example should be looking like this instead:

- author: William
  role: Client
  text: "Integer eu libero sit amet nisl vestibulum semper. Fusce nec porttitor massa. In nec neque elit. Curabitur malesuada ligula vitae purus ornare onec etea magna diam varius."
- author: James
  role: Hippie
  text: "Posuere erat a ante venenatis dapibus posuere velit aliquet. Duis llis, est non coeammodo luctus, nisi erat porttitor ligula, egeteas laciniato odiomo sem."

or

- author: William
  role: Client
  text: |Integer eu libero sit amet nisl vestibulum semper. Fusce nec porttitor massa. In nec neque elit. Curabitur malesuada ligula vitae purus ornare onec etea magna diam varius.
- author: James
  role: Hippie
  text: |Posuere erat a ante venenatis dapibus posuere velit aliquet. Duis llis, est non coeammodo luctus, nisi erat porttitor ligula, egeteas laciniato odiomo sem.

or multi line

- author: William
  role: Client
  text: >
    Integer eu libero sit amet nisl vestibulum semper. Fusce nec
    porttitor massa. In nec neque elit. Curabitur malesuada ligula
    vitae purus ornare onec etea magna diam varius.
- author: James
  role: Hippie
  text: > 
    Posuere erat a ante venenatis dapibus posuere velit aliquet.
    Duis llis, est non coeammodo luctus, nisi erat porttitor ligula,
    egeteas laciniato odiomo sem.
  • Like 2
Link to comment
Share on other sites

  • 2 weeks later...

Thanks for the contribution.  I used YAML in past PHP projects outside of ProcessWire a lot and found it very useful. Great to see now support in PorcessWire for it.

I also used initially SpyC but found its parsing not as robust and compliant and subsequently switched to Symfony's Yaml component which I found a better parser. For example Spyc does not support correctly anchors with newline folds > (item: > &anchor). Migrating from SpyC to Symfony\Yaml is easy, just replace Spyc::YAMLLoad($sourceFile); with Symfony\Component\Yaml\Yaml::parse($sourceFile);.

Should you decide to migrate to the Symfony compnent, use the 2.0.* branch of Symfony\Yaml which still does support mixing list and associative array elements which the 2.1.* branch does not allow any more despite it being correct YAML syntax. If you use composer

    "require": {
        "symfony/yaml": "2.0.*"
    }, 
 
will pull in the correct Yaml library.
 
  • Like 2
Link to comment
Share on other sites

@owzim That would be good. I worked with both versoins of Symfony\Yaml. The 2.0.x and the newer 2.1.x branches. I found the 2.0.x (currently at 2.0.15) branch more flexible with the syntax, as it allows things like mixing list and associative array elements, for example:

- Entry 1
tag2: Entry 2
- Entry3

which is kind of nice as it allows you to create arrays where some elements have a named array index and other just anonymous numeric indexes.

Versions from 2.1.x onwards throw an exception 'You cannot define a sequence item when in a mapping' for this use case.
Refer to http://gitelephant.cypresslab.net/symfony-2/commit/a1b73887f7de2a2549a7d2606b7803edc35af61d
 

Link to comment
Share on other sites

@hwmaier despite having this might be cool (I think it's non-straight/illogical), it would result in the Array/Object not be converted to an WireArray/WireData (if that option is selected) and fallback to regular assoc array in this module, because an object can't have both numeric AND string based keys, just so you know.

I consider mixing string/numeric keys a weird practice, just my opinion. Either you have an array or you have an object, perhaps that's why the 2.1 ditched that support, with good reason.

Edit: The Spyc parser supports mixing both btw.

Link to comment
Share on other sites

Yes, it seems a bit quirky, but legal YAML syntax. And in PHP its also legal to mix numeric and associative indices in arrays.

I found it useful for long lists of about 30+ elements where most elements are "anonymous" and are just iterated, but a few required direct access, so needed to have a known key (like a tag). It would be a pain having to assign indices to all elements and would spoil the beauty and ease of YAML.

Either way, you decide with version to choose, I only want to share my experience with the various versions and the subtle differences.

Link to comment
Share on other sites

@hwmaier, I know assoc arrays in PHP support that, but plain stdClass objects don't and I also came across a use case some time ago, but I still consider this a bad practice. If I want and object, also also 'anonymous' items I usually create a sub array called items.

name: foo
title: bar
items:
  - some
  - anon
  - baz

This is clear and straight forward. Still, I'll switch to the Symfony parser, when I get the time.

Thanks for the input!

Link to comment
Share on other sites

@owzim -

is there any way to implement validation using the included parser, like for example if someone makes a mistake in a YAML field, the page throws a validation error...?

or maybe a method where you could first check to see if a YAML field is valid, or maybe even have the field return null if the YAML is invalid..

thanks, just thinking out loud here, about validation possibilities..

Link to comment
Share on other sites

@Macrura,

depends on what you actually want to be validated. YAML is pretty tolerant. It just tries to parse whatever you provide. So unfortunately there are not many errors one could catch.

If you want an array and accidentally structure it as an object, YAML doesn't care, it just builds an object then.

What you probably want is structural validation (am I right?), which is not too trivial to implement, at least not from the top of my head.

Here's how it could go:

  1. One would configure a structure blueprint in the field settings.
  2. On field change, an ajax poll has to send the data to the server, where the input is checked against the configured structure.
  3. Or, implement it client side, with a JS YAML parser, but then we have to different parser, which might act differently, no option in my opinion.
Link to comment
Share on other sites

right, i was using this parser

http://yaml-online-parser.appspot.com/

and it helped since i could see a json output and make sure it would be correctly recognized.. but i agree that it would be too much hassle to validate..

maybe a simple tidy function that would at least trim whitespace at end, and remove blank/empty lines

Link to comment
Share on other sites

  • 1 month later...

owzim, I can't believe this exists, and that I missed it before now!

I though, "Hmm, let me see if anyone has anything out there about using YAML with ProcessWire". 

….and lo and behold, I find this awesomeness.

Much appreciated.

  • Like 3
Link to comment
Share on other sites

  • 4 weeks later...

Just wanted you to know, that I deprecated FieldtypeDataStructure, the repo will still be there and the added parsing features are still on the dev branch. I will just not longer maintain or support it.

Meanwhile I merged some features into the orginal Fieldtype YAML repo, made it beta and updated the links on the module page.

So it stays focused on YAML.

  • Like 1
Link to comment
Share on other sites

  • 1 year later...
  • 1 month later...

Hi Ivan,

please file a feature request on Github so I don't forget about that, thanks. I still have not touched PW 3 ... might be my first contact.

Is there a way to make modules compatible with both PW versions? That would be great.

Link to comment
Share on other sites

2 hours ago, owzim said:

Is there a way to make modules compatible with both PW versions? That would be great.

Typically the file compiler in PW3 takes care of making modules without namespaces work in 3.x, however I have had a couple of situations where I have had to conditionally check if a class exists and if not, prefix it with \ProcessWire\

  • Like 1
Link to comment
Share on other sites

  • 4 months later...
  • 4 months later...

Just installed in PW 3.0.61 .. when add new field type YAML and save I get the following error:

Session: Warning (showIf): dependency field 'contentType' is not present in this form. (ProcessFieldEdit)

??

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...