Bixie / pagekit-portfolio

Portfolio extension for Pagekit
12 stars 5 forks source link

Auto-create URL from data fields? #40

Open humantex opened 7 years ago

humantex commented 7 years ago

When I'm using overrides to portfolio's templates/files, is there a way to recognize a custom data field value as a proper URL and render it as a standard 'href' link in the page's datafield panel - or - does it need to be coded into the extension's core files?

pagekit-portfolio-datafields

I'm using overrides with copies of both project.php and portfolio.php, plus the 2 template files for changes to styling and that's working really well. There's the foreach loop for 'datafields' at lines 112-120 in project.php that seems the most likely place to do it, but I don't know portfolio's or pagekit's workings well enough to assume it will leave the link as-is without sanitizing the string back to plain text before output.

Before I jump in and start experimenting, I thought I would ask if it's possible.

humantex commented 7 years ago

After no response for a couple of days, I figured I might as well take a stab at finding a solution. In case anyone else stumbles on this and needs something similar... this works, but it may not be the greatest fix possible.

Operating on the block of code from lines 112-120 in project.php, I modified my override copy to use PHP's built-in filters to validate and sanitize a URL for whatever strings might be included as a custom datafield. There's nothing fancy here - just a check to see if the string contains a valid url first, and if it does, to sanitize it before rendering it into a 'href' tag. I also added a unique CSS class for styling it.

This replaces the entire 112-120 block...

<?php if (count($config['datafields'])) : ?>
   <dl class="uk-description-list">
      <?php foreach ($config['datafields'] as $datafield) :
         if (!$value = $project->get($datafield['name'])) continue; ?>
         <dt><?= $datafield['label'] ?></dt>
         <?php if (filter_var($value, FILTER_VALIDATE_URL)) {
           $value = filter_var($value, FILTER_SANITIZE_URL);
           echo "<dd><a class='portfolio-data-link' href='".$value."'>$value</a></dd>";
         } else {
           echo "<dd>$value</dd>";
         }
        ?>
      <?php endforeach; ?>
   </dl>
<?php endif; ?>

pagekit-portfolio-datafields2

There's the possibility that some strange URL's entered as strings won't get properly parsed with PHP's filters, but I figured it's better than using an overly complex regex - that I really don't comprehend too well - to run an 'every-odd-case' checking routine that might slow things to a crawl when used.