Jump to content

Use Field Value or Placeholder Failing


onionradish
 Share

Recommended Posts

I want to make a general-purpose function to return either the text of a field or its placeholder value if the text is blank. I'm getting errors that I don't understand.

I've enabled the "_init.php" pre-processor from config.php with the intent to use it as a general controller to intialize variables that will be used by page templates. I've added the "global" keyword to the function to access the ProcessWire objects. I'm getting errors when it attempts to access page/field values. What am I doing wrong?

_init.php:

<?php
function text_or_placeholder($fieldname){
    global $page, $fields;
    $text = $page->get($fieldname);  # error here
    if (!$text){
        $text = $fields->get($fieldname)->placeholder;
    }
    return $text;
}
echo $page->get('jumbotron_headline');  # this works
echo $fields->get('jumbotron_headline')->placeholder;  # this works
echo text_or_placeholder('jumbotron_headline');  # this errors
?>
Link to comment
Share on other sites

Thanks for the info -- I'd have never found it anywhere else. For reference to others, this is what worked:

_init.php

function text_or_placeholder($fieldname){
    $text = wire('page')->get($fieldname);
    if (!$text){
        $text = wire('fields')->get($fieldname)->placeholder;
    }
    return $text;
}
Is there somewhere I should have found it?
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...