GithubHelp home page GithubHelp logo

sjaakp / yii2-illustrated-behavior Goto Github PK

View Code? Open in Web Editor NEW
43.0 11.0 16.0 48 KB

Adds image to ActiveRecord

Home Page: http://www.sjaakpriester.nl/software/illustrated

License: MIT License

PHP 100.00%

yii2-illustrated-behavior's Introduction

Illustrated

Behavior for Yii2 ActiveRecord

With associated upload-widget

Latest Stable Version Total Downloads License

Illustrated is a Behavior for the Yii2 framework that makes any ActiveRecord, well, illustrated. It links the ActiveRecord to one or more image files. The images have strict proportions, allowing for a clean layout of views and other pages. The uploaded images may have several resolutions.

The Illustrated behavior co-operates with the enclosed Uploader widget. This lets the user crop the image, before uploading it to the server.

Here are some demo's of the Illustrated behavior and its associated Uploader widget.

Note that the current version (1.1.0) is changed considerably from the previous versions. It should be far easier to use. Please consult this document carefully.


Installation

Install Illustrated with Composer. Either add the following to the require section of your composer.json file:

"sjaakp/yii2-illustrated-behavior": "*"

Or run:

composer require sjaakp/yii2-illustrated-behavior "*"

You can manually install Illustrated by downloading the source in ZIP-format.


Usage of Illustrated

Illustrated is used like any Behavior of an ActiveRecord. The code should look something like this:

<?php

use sjaakp\illustrated\Illustrated;

class <model> extends \yii\db\ActiveRecord { 
	... 
	public function behaviors(){
		return [
			[
				"class" => Illustrated::class,
				"attributes" => [
					"picture" => [	// attribute name of the illustration
						...		// options for 'picture'
					],
					...		// other illustrations
				],
				... 	// other Illustrated options
			],
 			...		// other behaviors
		];
	}
	...
}  

An ActiveRecord with Illustrated behavior can have one or more illustrations.

Each illustration has it's own, fixed proportions, so that views of the ActiveRecord will have a consistent layout.

Each illustration is associated with one attribute in the ActiveRecord and a corresponding field in the database table. This attribute stores the filename of the uploaded image. Illustrated uses its own naming scheme. An uploaded image file name is never longer than ten characters.

In its basic operation, Illustrated stores one version of the uploaded file for each illustration. However, it is possible to make it store several versions, with different resolutions.

The proportions of an illustration are defined by two options: cropSize and aspectRatio. As an option, aspectRatio can be selected from a list of options. In that case, aspectOptions is saved in an extra ActiveRecord attribute.


Usage of Uploader

Uploader is an input widget. It is intended to upload an illustration. It can be used in an ActiveForm like this:

use sjaakp\illustrated\Uploader;
 
<?php $form = ActiveForm::begin([
		'options' => ['enctype' => 'multipart/form-data']	// important, needed for file upload
	]); ?>

	...		// other form fields

	<?= $form->field($model, 'picture')->widget(Uploader::class, [
		   ...		// Uploader options
    	]) ?>

	...

<?php ActiveForm::end(); ?>

Uploader displays a control for file upload, a control to crop the image, a checkbox to delete an uploaded image, and optionally a list of aspect ratios to choose from.

Note that the ActiveForm must have the option 'enctype' set to 'multipart/form-data'.


Illustrated functions

These functions become methods of the ActiveRecord that owns the Illustrated Behavior.

getImgHtml()

function getImgHtml( $attribute, $size = 0, $forceSize = true, $options = [] )

Gets a complete HTML img element of the uploaded and cropped illustration.

  • attribute: the attribute name of the illustration.
  • size: the length of largest side in pixels. If the option sizeSteps > 0, getImgHtml() returns the smallest crop variant possible. If size = 0 (default) the biggest crop variant is returned.
  • forceSize: if true (default), the element CSS is set to size.
  • options: HTML options of the img tag. See yii\helpers\Html::img. Default: [] (empty array).

The easiest way to display the illustration stored in the attribute 'picture' in a view is:

...	
<?= $model->getImgHtml('picture') ?>
...

getImgSrc()

function getImgSrc( $attribute, $size = 0 )

Gets the source URL of the uploaded and cropped illustration. Returns false if not set.

  • attribute: the attribute name of the illustration.
  • size: the length of largest side in pixels. If the option sizeSteps > 0, getImgHtml() returns the smallest crop variant possible. If size = 0 (default) the biggest crop variant is returned.

deleteFiles()

function deleteFiles( $attribute )

Deletes the image file(s) and clears attribute.

  • attribute: the attribute name of the illustration.

Illustrated options

attributes

array List of illustration properties key => value.

Array member key is the name of the attribute that stores the file name of the resulting cropped image.

Value is an array with the following properties (all are optional):

  • cropSize: int - Size of the largest side of the cropped image, in pixels. For portrait format (aspect ratio < 1.0) it is the height, for landscape format the width.
    • If not set, the default is taken. Default: 240.
  • aspectRatio: float|string
    • If float: the fixed aspect ratio of the image; it is not saved in the database.
    • If string: name of aspect attribute in the model. The aspect ratio is saved in this database field.
    • If not set, the default is taken Default: 1.0.
  • sizeSteps: int - Number of size variants of the cropped image. Each variant has half the size of the previous one.
    • Example: if cropSize = 1280, and sizeSteps = 5, variants will be saved with sizes 1280, 640, 320, 160, and 80 pixels, each in it's own subdirectory.
    • If sizeSteps = 0 (default) or is not set, only one cropped image is saved, with size cropSize.
  • allowTooSmall: bool - If true, images which are too small to crop are accepted. They will be sized to fit in the target size, defined by cropSize and aspectRatio.
  • tooSmallMsg: string - Error message template for images that are too small to crop. Parameters: original file name, width, and height. Default: 'Image "%s" is too small (%d×%d).'.

Value can also be a string. Then it is the name of the attribute. The properties all revert to default.

directory

Directory (or alias) where cropped images are saved.

If null (default), the directory will be '@webroot/<$illustrationDirectory>/<table name>', where <table name> is the table name of the ActiveRecord.

baseUrl

URL (or alias) where cropped images reside.

If null (default), the URL will be '@web/<$illustrationDirectory>/<table name>', where <table name> is the table name of the ActiveRecord.

illustrationDirectory

Name of subdirectory under '@webroot' where cropped images are stored. Default: 'illustrations'. If directory is anything else than null, illustrationDirectory is ignored

noImage

HTML returned if no image is available, i.e. $imgAttribute is empty. Default: '' (empty text).

fileValidation

Array with extra parameters for the validation of the file attribute. By default, only the file types and the number of files are tested.

You may add things like maximum file size here. See FileValidator. Default: [] (empty array).


Uploader options

aspectOptions

  • If false (default): aspect ratio is fixed, and given by aspectRatio in the attributes option of Illustrated.

  • If array: list of available aspect ratios. Keys are aspect ratios multiplied by 1000, values are descriptions of aspect ratios.

Example of aspectOptions value:

 $uploader->aspectOptions = [     // 1000 times real aspect ratio
           429 => 'tower (9×21)',      // aspect ratio is 0.429
           563 => 'high (9×16)',
           750 => 'portrait (3×4)',
           1000 => 'square (1×1)',      // aspect ratio is 1.0
           1333 => 'landscape (4×3)',
           1778 => 'wide (16×9)',
           2333 => 'cinema (21×9)'     // aspect ratio is 2.333
      ];

defaultAspect

Default selection of the aspect options. Note that there should be a corresponding key in the aspectOptions array. Example: if defaultAspect is 0.75, one of the keys in the array should be 1000 × .75 = 750.

If aspectOptions is false, defaultAspect is ignored.

Default: 1.0.

radio

  • If false: the aspect ratio can be chosen from a drop down list.

  • If true: the aspect ratio can be chosen in a radio button list.

Only applies when aspectOptions != false.

Default: false.

stylefileOptions

Extra client options for the stylefile file input control. See: https://github.com/sjaakp/stylefile.

cropperOptions

Extra client options for the cropper control. See: https://github.com/sjaakp/cropper.

deleteOptions

Options for delete checkbox. See activeCheckbox

  • If false, no delete chekbox is rendered.

Default: [ 'label' => 'Delete image' ].


Note: in many cases, if the illustration has a fixed aspect ratio, it won't be necessary to set any option for Uploader, and it can be rendered simply with:

	<?= $form->field($model, 'picture')->widget(Uploader::class) ?>

FAQ

I'm getting an error like 'Trying to get property of non-object'

  • You probably didn't give the form the option 'enctype' => 'multipart/form-data'.

yii2-illustrated-behavior's People

Contributors

philippfrenzel avatar sjaakp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-illustrated-behavior's Issues

Negative y value resulting in exception

Hi, when uploading attached image

1464255380_11

it crashes with below debug info. Any advice on how to fix this?

Thanks

exception 'Imagine\Exception\InvalidArgumentException' with message 'A coordinate cannot be positioned outside of a bounding box' in .../vendor/imagine/imagine/lib/Imagine/Image/Point.php:42
Stack trace:
#0 .../vendor/sjaakp/yii2-illustrated-behavior/Illustration.php(146): Imagine\Image\Point->__construct(100, -1.1165101928418E-13)
#1 .../vendor/sjaakp/yii2-illustrated-behavior/Illustrated.php(202): sjaakp\illustrated\Illustration->beforeValidate(Object(yii\base\ModelEvent))
#2 [internal function]: sjaakp\illustrated\Illustrated->beforeValidate(Object(yii\base\ModelEvent))
#3 .../vendor/yiisoft/yii2/base/Component.php(545): call_user_func(Array, Object(yii\base\ModelEvent))
#4 .../vendor/yiisoft/yii2/base/Model.php(376): yii\base\Component->trigger('beforeValidate', Object(yii\base\ModelEvent))
#5 .../vendor/yiisoft/yii2/base/Model.php(343): yii\base\Model->beforeValidate()
#6 .../backend/controllers/TalentsController.php(139): yii\base\Model->validate()
#7 [internal function]: backend\controllers\TalentsController->actionCreate()
#8 .../vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#9 .../vendor/yiisoft/yii2/base/Controller.php(156): yii\base\InlineAction->runWithParams(Array)
#10 .../vendor/yiisoft/yii2/base/Module.php(523): yii\base\Controller->runAction('create', Array)
#11 .../vendor/yiisoft/yii2/web/Application.php(102): yii\base\Module->runAction('talents/create', Array)
#12 .../vendor/yiisoft/yii2/base/Application.php(380): yii\web\Application->handleRequest(Object(yii\web\Request))
#13 .../backend/web/index.php(18): yii\base\Application->run()
#14 {main}

Error in demo example code

Here:

<?= $form->field($model, 'img')->widget(Uploader::className([
        'deleteOptions' => false    // suppress rendering of delete checkbox
    ])) ?>

Should be:

<?= $form->field($model, 'img')->widget(Uploader::className(), [
    'deleteOptions' => false, // Suppress rendering of delete checkbox
]) ?>

Class 'sjaakp\illustrated\Uploader' not found

Hello, here are my problems
First, In my view I am getting this error and I don't know what is the problem.

Second, I have an model to which I want to attach more than 2 images(each image must be stored in it normal size and small sizes(32x32,96x96,110x140)); how can I do that?
Third, seeing the imgAttribute,sizeAttribute,cropeSize I really don't understand how should I use them an d, I would like to know how illustrated store these link (it generates).

fileValidation does not work. can upload any type file resulting in errors

Not sure if i'm doing something wrong but the extension does not validate for images. It allows all other extensions resulting in errors below
Imagine\Exception\RuntimeException

Unable to open image /tmp/php7Bv8a7

Caused by: Imagine\Exception\InvalidArgumentException

An image could not be created from the given input

Could i be doing this wrong. I tried it again with a new active record model with and without fileValidation and both allow all types of extensions (sql files archives etc )

<--model-->
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors[] = [
"class" => Illustrated::className(),
'attributes' => [
'avatar' => [
'aspectRatio' => 1,
'cropSize' => 200,
'tooSmallMsg'=> 'The Image uploaded "%s" is too small (%d×%d) to crop or scale to an appropriate picture.'
],
],
'directory' => '@images',
'baseUrl' => '@imagesurl',
'noImage'=>'Not a valid image',
'fileValidation'=>[
'extensions' => ['png', 'jpg', 'gif'],
'maxSize' => 1024*1024,
],

    ];

    return $behaviors;
}

<--View-->

field($model, 'avatar')->widget(Uploader::className(), [ 'stylefileOptions' => [ 'btnClass' => 'btn btn-default', 'btnText' => 'Please, browse for image' ], 'cropperOptions' => [ 'diagonal' => 240, 'margin' => 5, 'sliderPosition' => 'right', 'sliderOptions' => [ 'animate' => 'slow' ] ], 'deleteOptions' => [ 'label' => '', // Font Awesome icon 'title' => 'Delete image' ], ], ``` )->label(false) ?>

I am getting error;Undefined index: photo

Is there any complete example of how to use the behavior(configuration in model,view,controller) and what are requirements to use the extension(which libraries are need). I am confused I don't know what to do things that I am trying are not working:
In my model:

public $photo;//The file attributes
public function behaviors(){
return [
[
"class" => "sjaakp\illustrated\Illustrated",
"attributes"=>[
'img'=>[
'aspectRatio'=>1.0,
'cropSize'=>90,]
]
],
];
}
//rules : $rules[] = ['photo','file'];

In my view
use sjaakp\illustrated\Uploader;

    <div id="partiechargee" class="panel panel-default center-block">
        <?php if($titre==true){
         echo '<p class="well-sm">';
       $this->render('/_alert', ['module' => $module,]);
        echo '</p>';}?>

        <h3 class="panel-title panel-heading text-center" style="margin-bottom:5px;"><strong><?= Html::encode($this->title)?></strong></h3>
            <?php $form = ActiveForm::begin([
                 'id'=> 'form-registration',
                'enableAjaxValidation'   => true,
                'enableClientValidation' => false,
                'method'=>'post',
                'action'=>\Yii::$app->urlManager->createUrl(['settings/profilephoto']),
            'options'=>['class'=>'well-sm text-center',
                'enctype'=>'multipart/form-data']]); ?>
field($model, 'photo')->widget(Uploader::className([ 'deleteOptions' => [ 'label' => '', // Font Awesome icon 'title' => 'Delete image' ] ])) ?>

'btn btn-danger cancel btn-block']) ?>

With that I am getting errror : Undefined index: photo

how to?

I don't understand how to upload the image.
there is a completed example please?

all images end up on 240x240

Hi,

looks like I can upload the images, I manage to get the dimensions to set, but everytime I save, it converts the image to be 240x240:( And even "scales" them down, so proportions (aspect) get's lost:(

Thanks for your help!

crop not applied

Hi,
I'm using 1.1.0 on a very basic case copied from the README. The upload is ok, but the crop is not applied. I've noticed that even if the POST request does include the JSON crop hash, it is no assigned to $crop which remains NULL.

any idead how to fix this ?

Thanks

Not saving image

Image "10715978_10202499115833537_813859873_n.jpg" is too small (704×960).

it says to every image I try to upload

composer problem, manually not work

Hello I try to download from composer:

Problem 1
- The requested package sjaakp/yii2-illustrated-behavior could not be found in any version, there may be a typo in the package name.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

Installation failed, reverting ./composer.json to its original content.

And if i try to install manually in folder:
vendor/sjaakp/illustrated
then, i will back this error

ReflectionException
Class sjaakp\illustrated\Illustrated does not exist

Image not being saved

when I click the submit button of the form it is sending an ajax request to the server but it not saving the file here is my code in the controller(what am I missing in the action so that it saves the image) :

public function actionphoto(){
$model = Profile::findOne(Yii::$app->user->identity->getId());
$model->scenario='photo';
if(\Yii::$app->request->post() && $model->save()){
var_dump('Image Saved');
}

      if(\Yii::$app->request->isAjax){
          var_dump('ajax request');
          \yii::$app->end();
          return $this->renderAjax('photo',array('model'=>$model));
      }else{
          return $this->render('photo',array('model'=>$model));
      }
} 

Please add a getImgUrl() method

Though getImgHtml is very useful I think this could be enhanced adding a getImgUrl method for common linked thumbnails to a bigger image such as:

Html::a($model->getImgHtml($size=100), $model->getImgUrl(), ['title' => $model->nombre, 'target' => '_blank']);

Thanks a lot for your excellent work!

No mention about adding image property in the docs

I found no mention about adding:

public $img;

as a property of model.

Without that exception is thrown:

Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: common\models\User::img

Allow define custom attributes paths

Allow define custom 'directory' and 'baseUrl' options for each attributes separately, not olny one global for all attributes.
Cancel adding automatically attribute name folder at the end of 'directory' and 'baseUrl' options, allow full customizable paths.

Update scenario

Hello,
The extension works fine in a "create" scenario, but how to display the image in the uploader widget in an update scenario ?

Thanks

xavier

Coding standarts

It will be better if the code will follow PSR-2. Yii2 follows it and recommends to follow it in extensions. Among the errors I saw for example extra spaces before curly braces, wrong placement of the curly braces in methods, just to name a few.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.