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 joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="optin" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="optin" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: PrivacyWire Git Repo
      Download as .zip
      I would love to hear your feedback 🙂
      CHANGELOG
      0.0.5 Multi-language support included completely (also in TextFormatter). Added possibility to async load other assets (e.g. <img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">) 0.0.4 Added possibility to add an imprint link to the banner 0.0.3 Multi-language support for module config (still in development) 0.0.2 First release 0.0.1 Early development
    • By MoritzLost
      This is a new module that 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) 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.
      Beta release
      Note that I consider this a Beta release. Since the module is relatively aggressive in deleting some caches, I would advise you to install in on a test environment before using it on a live site.
      Let me know if you're getting any errors, have trouble using the module or if you have suggestions for improvement!
      In particular, can someone let me know if this module causes any problems with the ProCache module? I don't own or use it, so I can't check. As far as I can tell, ProCache uses a folder inside the cache directory to cache static pages, so my module should be able to clear the ProCache site cache as well, I'd appreciate it if someone can test that for me.
      Future plans
      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

    • By David Karich
      Admin Page Tree Multiple Sorting
      ClassName: ProcessPageListMultipleSorting
      Extend the ordinary sort of children of a template in the admin page tree with multiple properties. For each template, you can define your own rule. Write each template (template-name) in a row, followed by a colon and then the additional field names for sorting.
      Example: All children of the template "blog" to be sorted in descending order according to the date of creation, then descending by modification date, and then by title. Type:
      blog: -created, -modified, title  Installation
      Copy the files for this module to /site/modules/ProcessPageListMultipleSorting/ In admin: Modules > Check for new modules. Install Module "Admin Page Tree Multible Sorting". Alternative in ProcessWire 2.4+
      Login to ProcessWire backend and go to Modules Click tab "New" and enter Module Class Name: "ProcessPageListMultipleSorting" Click "Download and Install"   Compatibility   I have currently tested the module only under PW 2.6+, but think that it works on older versions too. Maybe someone can give a feedback.     Download   PW-Repo: http://modules.processwire.com/modules/process-page-list-multiple-sorting/ GitHub: https://github.com/FlipZoomMedia/Processwire-ProcessPageListMultipleSorting     I hope someone can use the module. Have fun and best regards, David
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version (has been tested up to v3.3), add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "https://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


×
×
  • Create New...