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

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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MoritzLost
      TrelloWire
      This is a module that allows you to automatically create Trello cards for ProcessWire pages and update them when the pages are updated. This allows you to setup connected workflows. Card properties and change handling behaviour can be customized through the extensive module configuration. Every action the module performs is hookable, so you can modify when and how cards are created as much as you need to. The module also contains an API-component that makes it easy to make requests to the Trello API and build your own connected ProcessWire-Trello workflows.
      Features
      All the things the module can do for you without any custom code: Create a new card on Trello whenever a page is added or published (you can select applicable templates). Configure the target board, target list, name and description for new cards. Add default labels and checklists to the card. Update the card whenever the page is updated (optional). When the status of the card changes (published / unpublished, hidden / unhidden, trashed / restored or deleted), move the card to a different list or archive or delete it (configurable). You can extend this through hooks in many ways: Modifiy when and how cards are created. Modify the card properties (Target board & list, title, description, et c.) before they are sent to Trello. Create your own workflows by utilizing an API helper class with many convenient utility methods to access the Trello API directly. Feedback & Future Plans
      Let me know what you think! In particular:
      If you find any bugs report them here or on Github, I'll try to fix them. This module was born out of a use-case for a client project where we manage new form submissions through Trello. I'm not sure how many use-cases there are for this module. If you do use it, tell me about it! The Trello API is pretty extensive, I'll try to add some more helper methods to the TrelloWireApi class (let me know if you need anything in particular). I'll think about how the module can support different workflows that include Twig – talk to me if you have a use-case! Next steps could be a dashboard to manage pages that are connected to a Trello card, or a new section in the settings tab to manage the Trello connection. But it depends on whether there is any interest in this 🙂 Links
      Repository on Github Complete module documentation (getting started, configuration & API documentation) [Module directory pending approval] Module configuration

    • By MoritzLost
      Process Cache Control
      This module provides a simple solution to clearing all your cache layers at once, and an extensible interface to perform various cache-related actions.
      The simple motivation behind this module was that I was tired of manually clearing caches in several places after deploying a change on a live site. The basic purpose of this module is a simple Clear all caches link in the Setup menu which clears out all caches, no matter where they hide. You can customize what exactly the module does through it's configuration menu:
      Expire or delete all cache entries in the database, or selectively clear caches by namespace ($cache API) Clear the the template render cache. Clear out specific folders inside your site's cache directory (/site/assets/cache) Clear the ProCache page render cache (if your site is using ProCache) Refresh version strings for static assets to bust client-side browser caches (this requires some setup, see the full documentation for details). This is the basic function of the module. However, you can also add different cache management action through the API and execute them through the module's interface. For this advanced usage, the module provides:
      An interface to see all available cache actions and execute them. A system log and logging output on the module page to see verify what the module is doing. A CacheControlTools class with utility functions to clear out different caches. An API to add cache actions, execute them programmatically and even modify the default action. Permission management, allowing you granular control over which user roles can execute which actions. The complete documentation can be found in the module's README.
      Plans for improvements
      If there is some interest in this, I plan to expand this to a more general cache management solution. I particular, I would like to add additional cache actions. Some ideas that came to mind:
      Warming up the template render cache for publicly accessible pages. Removing all active user sessions. Let me know if you have more suggestions!
      Links
      https://github.com/MoritzLost/ProcessCacheControl ProcessCacheControl in the Module directory CHANGELOG in the repository Screenshots


    • By Macrura
      PrevNextTabs Module
      Github: https://github.com/outflux3/PrevNextTabs
      Processwire helper modules for adding page navigation within the editor.
      Overview
      This is a very simple module that adds Previous and Next links inline with the tabs on the page editor. Hovering over the tab shows the title of the previous or next page (using the admin's built in jqueryUI tooltips.)
      Usage
      This module is typically used during development where you or your editors need to traverse through pages for the purpose of proofing, flagging and/or commenting. Rather than returning to the page tree or lister, they can navigate with these links.
      Warnings
      If you are using PW version 2.6.1 or later, the system will prevent you from leaving the page if you have unsaved edits.
      For earlier versions, to avoid accidentally losing changes made to a page that might occur if a user accidentally clicks on one of these, make sure to have the Form Save Reminder module installed.
      http://modules.processwire.com/modules/prev-next-tabs/
    • By Gadgetto
      SnipWire - Snipcart integration for ProcessWire
      Snipcart is a powerful 3rd party, developer-first HTML/JavaScript shopping cart platform. SnipWire is the missing link between Snipcart and the content management framework ProcessWire.
      With SnipWire, you can quickly turn any ProcessWire site into a Snipcart online shop. The SnipWire plugin helps you to get your store up and running in no time. Detailed knowledge of the Snipcart system is not required.
      SnipWire is free and open source licensed under Mozilla Public License 2.0! A lot of work and effort has gone into development. It would be nice if you could donate an amount to support further development:

      Status update links (inside this thread) for SnipWire development
      2020-03-21 -- SnipWire 0.8.5 (beta) released! Improves SnipWires webhooks interface and provides some other fixes and additions 2020-03-03 -- SnipWire 0.8.4 (beta) released! Improves compatibility for Windows based Systems. 2020-03-01 -- SnipWire 0.8.3 (beta) released! The installation and uninstallation process has been heavily revised. 2020-02-08 -- SnipWire 0.8.2 (beta) released! Added a feature to change the cart and catalogue currency by GET, POST or SESSION param 2020-02-03 -- SnipWire 0.8.1 (beta) released! All custom classes moved into their own namespaces. 2020-02-01 -- SnipWire is now available via ProcessWire's module directory! 2020-01-30 -- SnipWire 0.8.0 (beta) first public release! (module just submitted to the PW modules directory) 2020-01-28 -- added Custom Order Fields feature (first SnipWire release version is near!) 2020-01-21 -- Snipcart v3 - when will the new cart system be implemented? 2020-01-19 -- integrated taxes provider finished (+ very flexible shipping taxes handling) 2020-01-14 -- new date range picker, discount editor, order notifiactions, order statuses, and more ... 2019-11-15 -- orders filter, order details, download + resend invoices, refunds 2019-10-18 -- list filters, REST API improvements, new docs platform, and more ... 2019-08-08 -- dashboard interface, currency selector, managing Orders, Customers and Products, Added a WireTabs, refinded caching behavior 2019-06-15 -- taxes provider, shop templates update, multiCURL implementation, and more ... 2019-06-02 -- FieldtypeSnipWireTaxSelector 2019-05-25 -- SnipWire will be free and open source Plugin Key Features
      Fast and simple store setup Full integration of the Snipcart dashboard into the ProcessWire backend (no need to leave the ProcessWire admin area) Browse and manage orders, customers, discounts, abandoned carts, and more Multi currency support Custom order and cart fields Process refunds and send customer notifications from within the ProcessWire backend Process Abandoned Carts + sending messages to customers from within the ProcessWire backend Complete Snipcart webhooks integration (all events are hookable via ProcessWire hooks) Integrated taxes provider (which is more flexible then Snipcart own provider) Useful Links
      SnipWire in PW modules directory SnipWire Docs (please note that the documentation is a work in progress) SnipWire @GitHub (feature requests and suggestions for improvement are welcome - I also accept pull requests) Snipcart Website  
      ---- INITIAL POST FROM 2019-05-25 ----
       
×
×
  • Create New...