Search code examples
phpimagegenericsuploadsymfony1

Symfony 1.4 sfWidgetFormInputFileEditable customization


I am using the sfWidgetFormInputFileEditable widget for my users to upload images.

I would like to see if there's a way to alter the way it works be default. When a user is adding a "new" object, I would like for it to show a generic picture, and when it's an "edit" then it can show the existing pic. I tried writing a PHP conditional statement but that's not working for me because when it's a "new" item I can't pull the parameter "getPicture1" because it doesn't exist.

My widget currently:

$this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
    'label' => ' ',
    'file_src' => '/uploads/car/'.$this->getObject()->getPicture1(),
    'is_image' => true,
    'edit_mode' => true,
    'template' => '<div>%file%<br />%input%</div>',
));

Solution

  • You have two options (the second one is more easy).

    First option: create your own sfWidgetFormInputFileEditable and extends the original.

    In a file lib/widget/myWidgetFormInputFileEditable.class.php:

    class myWidgetFormInputFileEditable extends sfWidgetFormInputFileEditable
    {
      protected function getFileAsTag($attributes)
      {
        if ($this->getOption('is_image'))
        {
          if (false !== $src = $this->getOption('file_src'))
          {
            // check if the given src is empty of image (like check if it has a .jpg at the end)
            if ('/uploads/car/' === $src)
            {
              $src = '/uploads/car/default_image.jpg';
            }
            $this->renderTag('img', array_merge(array('src' => $src), $attributes))
          }
        }
        else
        {
          return $this->getOption('file_src');
        }
      }
    }
    

    Then you need to call it:

    $this->widgetSchema['picture1'] = new myWidgetFormInputFileEditable(array(
      'label'     => ' ',
      'file_src'  => '/uploads/car/'.$this->getObject()->getPicture1(),
      'is_image'  => true,
      'edit_mode' => true,
      'template'  => '<div>%file%<br />%input%</div>',
    ));
    

    Second option: check if the object is new then use the default image.

    $file_src = $this->getObject()->getPicture1();
    if ($this->getObject()->isNew())
    {
      $file_src = 'default_image.jpg';
    }
    
    $this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
      'label'     => ' ',
      'file_src'  => '/uploads/car/'.$file_src,
      'is_image'  => true,
      'edit_mode' => true,
      'template'  => '<div>%file%<br />%input%</div>',
    ));