Jump to content
Martijn Geerts

FieldtypeSelectFile & InputfieldSelectFile

Recommended Posts

FieldtypeSelectFile & InputfieldSelectFile

Inputfield Select File is an Inputfield & Fieldtype to select a single file or folder and stores the name and / or use the selected file as page template. The last option enables the editor to use multiple views for a page, depending on the selected template.

Settings

  • The folder containing the files and/or folders.
    • A relative path relative to the /site/templates/ folder.
  • Hide file extensions
  • Hide files
  • Hide folders
  • Natural Sort (Select options)
    • Sort files and folders in natural ordering (PHP >= 5.4.0)
  • Change Page Template

    • Just before the Page::loaded event the selected file is set as template file for the page. This setting can only be applied once per a page and folders are exluded from the select inputfield.

      Note that a page with no associated template file will render with the selected file.

When to use ?

Let editors select a file and base your own logic upon this. With the change page template setting you're able to use the selected file as template file. This could reduce the amount of normal templates needed and let editors choose how the page get rendered. There are plenty of use cases for this Inputfield.

In the examples I call the field selected_file.

// let the editor choose a CSS file
$config->styles->append($config->urls->templates . "styles/" . $page->selected_file);

/**
 * advanced usage example
 *
 * You need multiple ways to render your markup. Let the site editor choose which
 * file the page need to render.
 *
 */

$tpl = new TemplateFile($config->paths->templates . "includes/" . $page->selected_file);
$tpl->set('current', $page);
$markup = $tpl->render();

(It could be a real good companion with InputfieldSelector)

Download at GitHub

Modules directory

Edited by Martijn Geerts
  • Like 18

Share this post


Link to post
Share on other sites

this is great...! i was trying to write this module about 2 months ago and couldn't figure out how to do it..

edit: brilliant, works perfectly, and even works using ../ to get out of the templates folder... this is going to be extremely useful for html5 video, selecting files to be used instead of uploading to processwire page.... and in other situations where we want to store large media assets somewhere else in the filesystem..

many thanks for this.

  • Like 4

Share this post


Link to post
Share on other sites

having an issue with this, the select works fine, but the field doesn't save... any idea what might be causing that?

cheers!

Share this post


Link to post
Share on other sites

@Macrura, tnx for the report.

Are you  absolutely sure the value is not stored or is the value not pre-selected ?

I'll take a closer look, as soon if I have some little time.

Share this post


Link to post
Share on other sites

hi Martijn - i'm pretty sure the value is not stored; i ran a quick selector and the field is showing as empty...

  • Like 1

Share this post


Link to post
Share on other sites

Tnx for the followup !

Gonna test this weekend. 


I didn't thought people would use this fieldtype with ../ in the field settings, so I cleaned the values when I discovered this behaviour.

Normal users can't set those settings so I removed this checking and clearing of the data in the update. (can't think of doing real harm)

Thanks for finding this Macrura. The module is updated on Github.

Edited by Martijn Geerts
  • Like 1

Share this post


Link to post
Share on other sites

Sorry to hijack this thread, but if you are working with HTML5 video, have you seen my draft video fieldtype module:

https://processwire.com/talk/topic/4580-video-fieldtype/

@Adrian - looks really good! In the use case i have, my video page has options for youtube, vimeo or local video; with the local video, some of them were very large sizes so i didn't feel like bothering with the uploader; for the html5 video, i have mp4 and webm versions of both, plus the poster image...so i have a media folder in /site/ for all of those things.. having the ability to let the user select the video file makes this whole thing possible.. but i will look into your module for sure on future stuff and i'm redoing a site now and will probably upgrade my system to use your module... will comment on that thread soon!

  • Like 1

Share this post


Link to post
Share on other sites

@martijn, thanks for that update! this works for sure now with regular pages, only issue is that i can't seem to get it to work with repeaters, i looked at the code but nothing popped out at me as to why this would be the case..

Share this post


Link to post
Share on other sites

@Macrura

I don't see any issues here regarding using the field inside a repeater. Can you provide me with more information so I could replicate your situation ?

post-577-0-94317300-1402132451_thumb.png

Share this post


Link to post
Share on other sites

@Martijn, thanks, i'm not sure what the problem is, just can't get values to save in these repeaters i have;

i will keep testing/troubleshooting this; i tried changing the path, checking/unchecking the hide file extension, and i checked the database.. they just don't save..

thanks for you help.. nothing urgent...

Share this post


Link to post
Share on other sites

You may want to also check other modules that you may have installed recently. I had an issue where repeaters wouldn't save and it turned out to be an issue with a recently installed module.  I only figured it out by retracing my steps and uninstalling modules.

  • Like 1

Share this post


Link to post
Share on other sites

ok, figured it out, sorry for posting an error that wasn't really this module... it was something to do with the conditional visibility of fields that was breaking my repeater...

thanks again.. this is all sorted!

  • Like 2

Share this post


Link to post
Share on other sites

Little update on the module.

You can choose to list folders and or files. If you already had this module installed, be sure you check Hide folders and and save the field settings. Updated the first post in this thread.

  • Like 4

Share this post


Link to post
Share on other sites

@Martijn,

I was researching how to get this module to return an alphabetically sorted file list;

found some stuff on stack exchange and php about reading the files into an array and sorting...

$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
sort($files);

just wondering if you might be up to being 'sponsored' to add that feature... can send beer $

Share this post


Link to post
Share on other sites

@Macrura:

I like your suggestion so updated the module with an option to use SORT_NATURAL on the options of the select. 

// Natural Sort (NOT checked)
image_1.jpg
image_12.jpg
image_21.jpg
image_4.jpg
 
// Natural Sort (checked)
image_1.jpg
image_4.jpg
image_12.jpg
image_21.jpg
 
 
  • Like 5

Share this post


Link to post
Share on other sites

@martijn, wow can't thank you enough; this module has come in handy so many times; this is a great enhancement to it.. thanks!!

BTW - just tested and it works perfectly!

  • Like 1

Share this post


Link to post
Share on other sites
Just pushed a (major) update which adds a new feature: Change Page Template.

Change Page Template:

Just before the Page::loaded event the selected file is set as template file for the page. This enables you to have multiple file templates for the same page, selectable by the editor. This setting can only be applied once per a page and folders are exluded from the select inputfield. Note that a page with no associated template file will render fine with a selected file. :-)

+ Changed the sorting from SORT_NATURAL flag to the natcasesort function because the flag requires PHP 5.4.0 or higher.

First post is modified & please report issues.

  • Like 2

Share this post


Link to post
Share on other sites

I am currently using this field for the first time and I love it! Really a useful little time saver!

One minor issue I found: I configured the folder path without a trailing slash. When editing a template i could see the files in the folder, but the field never saved the selected value. After adding a trailing slash to the foldername everything worked as expected. I did not see any warnings or errors on screen or in my logs.

Another thing I still could not figure out is, how to use this field with showIf field dependencies. Is this even possible? I would like to show some other fields only if a certain file is selected. 

Share this post


Link to post
Share on other sites

Could you change the line in the sanitizeValue method in The fieldtype to:

$file = $this->config->paths->templates . trim(trim($field->folderPath, '/')) . '/' . $value;

Then the first 'issue' should be fixed. (although it was mentioned in the notes below the setting)

For the second issue, I have no time to invest now... will look at it this weekend. (Could be related to the first.)

Share this post


Link to post
Share on other sites

Thanks Martijn! After changing the sanitizeValue method the trailing slash is no longer needed. 

Field dependencies still don't work, but I did not expect it either :) Thanks for looking into it, but in my current project I can totally live without it. It's just a "nice to have", and I wanted to give you some feedback.

  • Like 1

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
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory (pending approval) Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
    • 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="text/plain" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="text/plain" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="text/plain" 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.1.1 Debugging: fixed error during uninstall 0.1.0 Added new detection of async scripts for W3C Validation 0.0.6 CSS-Debugging for hiding unused buttons, added ProCache support for the JavaScript tag 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 bernhard
      --- Please use RockFinder3 ---
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory (pending approval) If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By Craig
      I've been using Fathom Analytics for a while now and on a growing number of sites, so thought it was about time there was a PW module for it.
      WayFathomAnalytics
      WayFathomAnalytics is a group of modules which will allow you to view your Fathom Analytics dashboard in the PW admin panel and (optionally) automatically add and configure the tracking code on front-end pages.
      Links
      GitHub Readme & documentation Download Zip Modules directory Module settings screenshot What is Fathom Analytics?
      Fathom Analytics is a simple, privacy-focused website analytics tool for bloggers and businesses.

      Stop scrolling through pages of reports and collecting gobs of personal data about your visitors, both of which you probably don't need. Fathom is a simple and private website analytics platform that lets you focus on what's important: your business.
      Privacy focused Fast-loading dashboards, all data is on a single screen Easy to get what you need, no training required Unlimited email reports Private or public dashboard sharing Cookie notices not required (it doesn't use cookies or collect personal data) Displays: top content, top referrers, top goals and more
×
×
  • Create New...