Jump to content
owzim

Fieldtype YAML

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

Share this post


Link to post
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!

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

@owzim - thanks for the tips; good to know and i'll add that to the KB... oddly i'm using that code now and it works perfectly... but i do wonder what would happen if there was a colon in the string..

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

@hwmaier thanks for the info. I'll consider switching to the Symfony parser, the huge community around Symfony makes it a better candidate anyway.

Share this post


Link to post
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
 

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
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!

Share this post


Link to post
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..

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Hey, owzim!

Thank you for your wonderful module! Any chance making in PW 3 compatible in WireArray mode? Seems to be not so hard - just reference ProcessWIre classes with namespace. But I may be underestimating it, of course.

  • Like 1

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Good day, @owzim! I have a (maybe rare) need to pass the FieldtypeYAML textarea contents through a textformatter before objectifying it. It seems to be not possible in the field settings (or I am missing something). Can I hook somewhere to do it?

Share this post


Link to post
Share on other sites

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)

??

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By eelkenet
      Hi! I've created a small Inputfield module called InputfieldFloatRange which allows you to use an HTML5 <input type="range" ../> slider as an InputField. I needed something like this for a project where the client needs to be able to tweak this value more based on 'a feeling' than just entering a boring old number. Maybe more people can use this so I'm hereby releasing it into the wild. 
      EDIT: You can now install it directly from the Modules directory: http://modules.processwire.com/modules/inputfield-float-range/
       
      What is it?
      The missing range slider Inputfield for Processwire. 
      What does it do?
      This module extends InputfieldFloat and allows you to use HTML5 range sliders for number fields in your templates.
      It includes a visible and editable value field, to override/tweak the value if required.  
      Features
      Min/max values Precision (number of decimals) Optional step value (Read more) Optional manual override of the selected value (will still adhere to the rules above) Configurable rounding of manually entered values (floor, round, ceil, disable) Usage
      Clone / zip repo Install FieldtypeFloatRange, this automatically installs the Inputfield Create new field of type `Float (range)` or convert an existing `Float`, `Integer` or `Text` field. To render the field's value simply echo `$page->field` Demo
      A field with Min=0, Max=1, Step=0.2, Precision=2

      Field with settings Min=0, Max=200, Step=0.25, Precision=2

       
      Todo
      Make the display-field's size configurable (will use the Input Size field setting)  Hopefully become redundant  
      Changelog
      005 (current version)
      - Fix bug where the Inputfield would not work properly within repeaters / repeater matrices
      004
      - Make rounding of manually entered values configurable (floor, round, ceil or disable)
      - Fix small JS bug when the value-display field was not displayed
      - Update README
      003
      - Code cleanup, add some ModuleInfo data & LICENSE
      - Submit to PW Modules directory (http://modules.processwire.com/modules/inputfield-float-range/)
      002
      - Fix issue where setting the step value to an empty value created problem with validation
      - Make the display-field optional
      001
      - Initial release
       
      Thanks!
       
       
    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      2019-10-18
      2019-08-08
      2019-06-15
      2019-06-02
      2019-05-25
      If you are interested, you can test the current state of development:
      https://github.com/gadgetto/SnipWire
      Please note that the software is not yet intended for use in a production system (alpha version).
      If you like, you can also submit feature requests and suggestions for improvement. I also accept pull requests.
      ---- INITIAL POST FROM 2019-05-25 ----
      I wanted to let you know that I am currently working on a new ProcessWire module that fully integrates the Snipcart Shopping Cart System into ProcessWire. (this is a customer project, so I had to postpone the development of my other module GroupMailer).
      The new module SnipWire offers full integration of the Snipcart Shopping Cart System into ProcessWire.
      Here are some highlights:
      simple setup with (optional) pre-installed templates, product fields, sample products (quasi a complete shop system to get started immediately) store dashboard with all data from the snipcart system (no change to the snipcart dashboard itself required) Integrated REST API for controlling and querying snipcart data webhooks to trigger events from Snipcart (new order, new customer, etc.) multi currency support self-defined/configurable tax rates etc. Development is already well advanced and I plan to release the module in the next 2-3 months.
      I'm not sure yet if this will be a "Pro" module or if it will be made available for free.
      I would be grateful for suggestions and hints!
      (please have a look at the screenshots to get an idea what I'm talking about)
       




    • By Robin S
      Another little admin helper module...
      Template Field Widths
      Adds a "Field widths" field to Edit Template that allows you to quickly set the widths of inputfields in the template.

      Why?
      When setting up a new template or trying out different field layouts I find it a bit slow and tedious to have to open each field individually in a modal just to set the width. This module speeds up the process.
      Installation
      Install the Template Field Widths module.
      Config options
      You can set the default presentation of the "Field widths" field to collapsed or open. Field widths entered into the Template Field Widths inputfield are only applied if the Edit Template form is submitted with the Template Field Widths inputfield in an opened state. "Collapsed" is the recommended setting if you think you might also use core inputs for setting field widths in a template context. You can choose Name or Label as the primary identifier shown for the field. The unchosen alternative will become the title attribute shown on hover. You can choose to show the original field width next to the template context field width.  
      https://github.com/Toutouwai/TemplateFieldWidths
      https://modules.processwire.com/modules/template-field-widths/
    • By adrian
      Tracy Debugger for ProcessWire
      The ultimate “swiss army knife” debugging and development tool for the ProcessWire CMF/CMS

       
      Integrates and extends Nette's Tracy debugging tool and adds 35+ custom tools designed for effective ProcessWire debugging and lightning fast development
      The most comprehensive set of instructions and examples is available at: https://adrianbj.github.io/TracyDebugger
      Modules Directory: http://modules.processwire.com/modules/tracy-debugger/
      Github: https://github.com/adrianbj/TracyDebugger
      A big thanks to @tpr for introducing me to Tracy and for the idea for this module and for significant feedback, testing, and feature suggestions.
×
×
  • Create New...