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 teppo
      This module tracks changes, additions, removals etc. of public (as in "not under admin") pages of your site. Like it's name says, it doesn't attempt to be a version control system or anything like that - just a log of what's happened.
      At the moment it's still a work in progress and will most likely be a victim of many ruthless this-won't-work-let's-try-that-instead cycles, but I believe I've nailed basic functionality well enough to post it here.. so, once again, I'll be happy to hear any comments you folks can provide
      https://modules.processwire.com/modules/process-changelog/
      https://github.com/teppokoivula/ProcessChangelog
      How does it work?
      Exactly like it's (sort of) predecessor, Process Changelog actually consists of two modules: Process Changelog and Process Changelog Hooks. Hooks module exists only to serve main module by hooking into various functions within Pages class, collecting data of performed operations, refining it and keeping up a log of events in it's own custom database table (process_changelog.) Visible part is managed by Process Changelog, which provides users a (relatively) pretty view of the contents of said log table.
      How do you use it?
      When installed this module adds new page called Changelog under Admin > Setup which provides you with a table view of collected data and basic filtering tools See attached screenshots to get a general idea about what that page should look like after a while.
      For detailed installation instructions etc. see README.md.
       


    • By Gadgetto
      Status update links (inside this thread) for SnipWire development will be always posted here:
      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 apeisa
      Update 31.7.2019: AdminBar is now maintained by @teppo. Modules directory entry has been updated, as well as the "grab the code" link below.
      ***
      Latest screencast: http://www.screencas...73-ab3ba1fea30c
      Grab the code: https://github.com/teppokoivula/AdminBar
      ***
      I put this Adminbar thingy (from here: http://processwire.c...topic,50.0.html) to modules section and to it's own topic.
      I recorded quick and messy screencast (really, my first screencast ever) to show what I have made so far. You can see it from here: http://www.screencas...18-1bc0d49841b4
      When the modal goes off, I click on the "dark side". I make it so fast on screencast, so it might seem a little bit confusing. Current way is, that you can edit, go back to see the site (without saving anything), continue editing and save. After that you still have the edit window, but if you click "dark side" after saving, then the whole page will be reloaded and you see new edits live.
      I am not sure if that is best way: there are some strengths in this thinking, but it is probably better that after saving there shouldn't be a possibility to continue editing. It might confuse because then if you make edits, click on dark side -> *page refresh* -> You lose your edits.
      ***
      When I get my "starting module" from Ryan, I will turn this into real module. Now I had to make some little tweaks to ProcessPageEdit.module (to keep modal after form submits). These probably won't hurt anything:
      if($this->redirectUrl) $this->session->redirect($this->redirectUrl); if(!empty($_GET['modal'])) $this->session->redirect("./?id={$this->page->id}&modal=true"); // NEW LINE else $this->session->redirect("./?id={$this->page->id}");   and...
      if(!empty($_GET['modal'])) { $form->attr('action', './?id=' . $this->id . '&modal=true'); } else { $form->attr('action', './?id=' . $this->id); // OLD LINE }  
    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.54
      Composer: rockett/jumplinks
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy! :)
×
×
  • Create New...