An " if statement " (or something similar) for a textfield

7 posts by 3 authors in: Forums > CMS Builder
Last Post: October 6, 2013   (RSS)

By CarlosPinedo - October 5, 2013 - edited: October 6, 2013

Hi,

In an editor, I have a textfield to enter urls. This textfield it's not required, so, users of the cmsb may leave it blank.

This is the code in the frontend:

<p><span> Website: </span><a href="<?php echo htmlencode($record['info_map_link']) ?>" target="_blank"> click here </a></p>

When they enter the urls there's no problem. The problem appears when they don´t write an URL. Because, when the website visitors see the text "click here " and they click it, obviously, nothing happens.

I want the text "click here" to appear only if the cmsb user writes an url.

How can i do this?

Carlos

By jenolan - October 6, 2013

<p><span> Website: </span> <?php if( ! empty( trim( $record['info_map_link'] ) ) : ?><a href="<?php echo 
htmlencode($record['info_map_link']) ?>" target="_blank"> click 
here </a><?php endif ?></p>

---
<?= "Jenolan(Larry) :: Coding Since 1973" ?>
Peace and Long Life

By CarlosPinedo - October 6, 2013

Hi Larry , i´m getting this error: Fatal error: Can't use function return value in write context in /home/observat/public_html/test.php on line 320

 At line 320 is your code:

<p><span> Website: </span> <?php if( ! empty( trim( $record['info_map_link'] ) ) : ?><a href="<?php echo 
htmlencode($record['info_map_link']) ?>" target="_blank"> click 
here </a><?php endif ?></p>

By CarlosPinedo - October 6, 2013

Great, that works!, thanks a lot!

Carlos

By jenolan - October 6, 2013

Blargh I always forget that trim aint allowed.

<p><span> Website: </span> <?php if( ! empty(  $record['info_map_link'] ) : ?><a href="<?php echo 
htmlencode($record['info_map_link']) ?>" target="_blank"> click 
here </a><?php endif ?></p>here </a><?php endif ?></p>

Try thsi to use trim alone to make sure someone putting a few spaces in doesn't break it...

<?php
$record['info_map_link'] = trim( $record['info_map_link'] );
?>
<p>
    <span> Website: </span> 
        <?php if( ! empty(  $record['info_map_link'] ) ) : ?>
            <a href="<?php echo htmlencode( $record['info_map_link'] ) ?>" target="_blank"> click here </a>
        <?php endif ?>
</p>

That should be better, but this one will 'validate' a url, assuming your server allows it...

<?php
$record['info_map_link'] = trim( $record['info_map_link'] );
if( $record['info_map_link'] )
{
    $array = get_headers( $record['info_map_link'] );
    if( ! strpos( $array[0], "200" ) ) $record['info_map_link'] = '';
?>
<p>
    <span> Website: </span> 
        <?php if( $record['info_map_link'] ) : ?>
            <a href="<?php echo htmlencode( $record['info_map_link'] ) ?>" target="_blank"> click here </a>
        <?php endif ?>
</p>

---
<?= "Jenolan(Larry) :: Coding Since 1973" ?>
Peace and Long Life

By CarlosPinedo - October 6, 2013

Thanks Larry, I´ll give it a try. Thanks for your time.