Yii2: Validate content of a file before submitting - yii2

In my form I have a field for the user to upload an XML file. But before submitting the XML, I have to validate it. How can I create a validation function for this?
My view:
...
<?= $form->field($model, 'upload_file')->fileInput(['accept' => 'text/xml']) ?>
...
My Model:
...
['upload_file', 'validateFile'],
...
public function validateFile($attribute, $params)
{
// TODO
}
...
I can access and validate the contents of the XML file in the controller, but this validation is already after the file is submitted ... I wanted before submitting!
Exemple in controller:
if ($model->load(Yii::$app->request->post()) {
$file = UploadedFile::getInstance($model, 'upload_file');
$file = file_get_contents($file->tempName);
// xml of the upload_file
$xml = simplexml_load_string($file);
I want to pass this code that is on top, to the validation function.

Add this to your model rules:
public function rules()
{
return [
[['uploaded_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xml', 'mimeTypes' => 'text/xml, application/xml'],
];
}

Related

yii2 file required custom validation

I have a form where the required validation rules for the fields can be configures and stored in the model.
When rendering the form, I create the validation rules as follows (simplified) which works fine.
$view_parameters = $competition_article->view_parameters;
if (!empty($view_parameters) && is_array($view_parameters)) {
foreach ($view_parameters as $parameter_key => $parameter_value) {
$field_name = $parameter_value['name'];
$field_required = $parameter_value['required'];
if ($field_required) {
Validator::createValidator('required', $model, [$field_name]);
}
}
}
For the form submission, I use a custom validation rule. This works for all but the file attachment.
public function rules()
{
$rules = [
[['firstname', 'surname', 'closeststore', 'email', 'phone', 'response', 'attachment'],
'dynamicValidator',
'skipOnEmpty' => false
],
[['attachment'], 'file',
'extensions' => 'pdf, jpeg, jpg, doc, docx',
'checkExtensionByMimeType'=>false
],
];
return $rules;
}
On the custom validation method, I handle the file separately.
I tried
a) addError() and return false
b) createValidator() and validateAttribute() pair , which works for the text fields.
public function dynamicValidator($attribute, $params, $validator )
{
$view_parameters = $this->view_parameters;
if ($view_parameters[$attribute]['required'])
$validator = new Validator();
if ($attribute == 'attachment') {
if (empty($_FILES['CompetitionForm']['name']['attachment']))
[$attribute]);
$this->addError( $attribute, 'Please include your attachment to enter.');
// NOTE : Adding the validator has no effect
// $validator = $validator->createValidator('required', $this,
// $validator->validateAttribute($this, $attribute);
return false;
}
$validator = $validator->createValidator('required', $this, [$attribute]);
$validator->validateAttribute($this, $attribute);
}
}
Despite the code being reached, an error is not raised when the attachment is require and the either the addError() or createValidator() is called.
How can I fail the validation when no file is attached and the attachment is required?
You can try with this validation rules for attachment using skipOnEmpty.
[['attachment'], 'file',
'skipOnEmpty' => false,
'extensions' => 'pdf, jpeg, jpg, doc, docx',
'checkExtensionByMimeType'=>false
],

How to add custom new field in yii2 gii generated crud

I have made one CRUD in YII2 using Gii having 10 fields. In my mysql table there was logo column so Gii generated text field for it. I converted it to file field using the following code.
$form->field($model, 'manufacturer_logo')->fileInput()
Now I am not getting any clue where I can write controller side code so that I can save logo in folder and DB like other fields. There is no saving code in Gii generated controller. I tried to follow this but it also did not work.
In my model rules, I have written following line for valid image file.
public function rules()
{
return [
[['manufacturer_description', 'manufacturer_status','manufacturer_logo'], 'string'],
[['manufacturer_name','manufacturer_status','manufacturer_logo'], 'required'],
[['manufacturer_logo'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
[['created_at', 'updated_at'], 'safe'],
[['manufacturer_name'], 'string', 'max' => 255],
];
}
Now when I fill all fields and browse image as well and press submit then it gives me error "Please upload a file", here you can see so I am not able to upload image and save its name in DB column like other fields.
For further doing RND, Now image is saving in folder but not in database, Here I changed controller code.
public function actionCreate()
{
$model = new Manufacturers();
if ($model->load(Yii::$app->request->post())) {
//upload logo
$base_path = Yii::getAlias('#app');
//$model = new UploadForm();
$imageFile = UploadedFile::getInstance($model,'manufacturer_logo');
$logoName = "";
if (isset($imageFile->size)) {
$imageFile->saveAs($base_path . '/web/uploads/' . $imageFile->baseName . '.' . $imageFile->extension);
$logoName = $imageFile->baseName . '.' . $imageFile->extension;
}
if(trim($logoName)!='') {
$model->manufacturer_logo = trim($logoName);
}
$model->save(false);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}

Validation error on custom model attributes not displayed in form

I have a model with the following custom attributes topic_names, topic_details (string fields). I have also a model form with the custom attributes and custom rules. When I insert wrong data in the form fields, there is a model error, but it isn't displayed.
Model code:
......
public function rules()
{
return [
...
[['topics_names','topics_details'],'string'],
[['topics_names'],'checkCorrectAndSetTopics'],
];
}
public function checkCorrectAndSetTopics(){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError('topics_names', \Yii::t('app', 'The topics names and details sets have different sizes'));
return FALSE;
}
}
return TRUE;
}
The problem is when the second rules is violeted, the form doesn't show any error, but there is. I checked it debugging the code below.
Form code:
..........
<?php
ActiveForm::$autoIdPrefix = createRandomId();//Function which creates a random id
$form = ActiveForm::begin(
['enableAjaxValidation' => true, "options"=> ["class"=>"extra-form"]]);
?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'topics_names')->textInput()
->label(\Yii::t('app', 'Topics Names'))?>
<?= $form->field($model, 'topics_details')->textarea(['rows' => 6])
->label(\Yii::t('app', 'Topics Details'))?>
........
Controller code:
public function actionAddExtraData($id){
if(!Yii::$app->request->isAjax){
throw new ForbiddenHttpException(\Yii::t('app','Cannot access this action directly.'));
}
$event = $this->findModel($id);
$extraData = ExtraData::find()
->andWhere(['event_id'=>$id])
->one();
if(!$extraData){
$extraData = new ExtraData();
$extraData->event_id = $id;
}else{
$extraData->prePerformForm();//Insert data on custom attributes
}
if(Yii::$app->request->isPost AND Yii::$app->request->isAjax AND Yii::$app->request->post("submitting") != TRUE
AND $extraData->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
$validation = ActiveForm::validate($extraData);
return $validation;
}
if ($extraData->load(Yii::$app->request->post()) && $extraData->save()) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ["success" => TRUE];
} else {
return $this->redirect(Yii::$app->request->referrer);
}
}
return $this->renderAjax('_event_extra_form',['model'=>$extraData,'event'=>$event]);
}
First thing, pretty sure you don't need to return true or false, you just need to add error. Second thing, in your example you name the attribute, you can actually get this when defining the function, so your function could look something like this
public function checkCorrectAndSetTopics($attribute, $model){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError($attribute, \Yii::t('app', 'The topics names and details sets have different sizes'));
}
}
}

Yii2 POST image to model in API without Yii2 Naming convention

I'm creating an endpoint for a mobile application to send a image to the server. I'm posting the image with the POSTMAN extension for chrome. The image is in the $_FILES variable, and named image. How can I load this image into a model, or the UploadedFile class? The $model->load(Yii::$app->request->post()) line does not correctly load the file, as it is not in Yii2's naming convention for forms.
It's currently returning:
{
"success": false,
"message": "Required parameter 'image' is not set."
}
Code
models\Image.php
<?php
namespace api\modules\v1\models;
use yii\base\Model;
use yii\web\UploadedFile;
class Image extends Model
{
/**
* #var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
$path = dirname(dirname(__FILE__)) . '/temp/';
if ($this->validate()) {
$this->image->saveAs($path . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
die(var_dump($this->errors));
return false;
}
}
}
controllers\DefaultController.php
<?php
namespace api\modules\v1\controllers;
use api\modules\v1\models\Image;
use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
class DefaultController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new Image();
if (Yii::$app->request->isPost) {
if($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return ['success' => true, 'message' => 'File saved.'];
}
else return ['success' => false, 'message' => 'Could not save file.'];
}
else return ['success' => false, 'message' => 'Required parameter \'image\' is not set.'];
}
else return ['success' => false, 'message' => 'Not a POST request.'];
}
}
Postman
Your problem seems to be the name you are using to send the image file. Usually Yii2 uses names for form attributes like "ModelName[attributeName]" and you are sending your image file with the name "image"
There are 2 ways of fixing this:
Change the name you use to send your image file to follow the same naming conveniton. However you don't seem to want that.
Use getInstanceByName('image') method instead of getInstance($model, 'image')
The problem come here
When you send files via api they are not sent asynchronously. If you check
echo '<pre>';
print_r($_FILES); //returns nothing
print_r($_POST["image"]); //returns something
echo '</pre>';
die;
One reason is that your controller extendsyii\web\controller which is not used by rest apis, extend yii\rest\controller
The other way to go about this is by using javascript formData when sending the post request
This is a way i handled a previous ajax post of an image probably itll give you a guideline
The form
<?php $form = ActiveForm::begin(['options' => ['enctype' =>
'multipart/form-data','id'=>'slider_form']]); ?> //dont forget enctype
<?= $form->field($model, 'file')->fileInput() ?>
Then on the ajax post
var formData = new FormData($('form#slider_form')[0].files);
$.post(
href, //serialize Yii2 form
{other atributes ,formData:formData}
)
Then on the controller simply access via
$model->file =$_FILES["TblSlider"]; //here this depends on your form attributes check with var_dump($_FILES)
$file_tmp = $_FILES["TblSlider"]["tmp_name"]["file"];
$file_ext = pathinfo($_FILES['TblSlider']['name']["file"], PATHINFO_EXTENSION);
if(!empty($model->file)){
$filename = strtotime(date("Y-m-d h:m:s")).".".$file_ext;
move_uploaded_file($file_tmp, "../uploads/siteimages/slider/".$filename);
///move_uploaded_file($file_tmp, Yii::getAlias("#uploads/siteimages/slider/").$filename);
$model->image = $filename;
}
I hope this helps

How to upload files in web folder in yii2 advanced template?

I try to upload files in backend and each time i uploaded a file it was successfully uploaded and successfully saved in the DB but it wasn't save to the directory i specified so my application can't find the file, and i already gave 777 permission to the uploads folder in web directory. below is my codes
Model to handle and save the file upload...
How to upload files in root folder in yii2 advanced template?
Model responsible for the upload
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class UploadForm extends Model {
public $img;
public $randomCharacter;
public function rules(){
return[
[['img'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
];
}
public function upload(){
$path = '/uploads/';
$randomString = '';
$length = 10;
$character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
$randomString = substr(str_shuffle($character),0,$length);
$this->randomCharacter = $randomString;
if ($this->validate()){
$this->img->saveAs($path .$randomString .'.'.$this->img->extension);
return true;
}else{
return false;
}
}
}
The product model reponsible for save info into database
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class Products extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'products';
}
public function rules()
{
return [
[['name'], 'string', 'max' => 100],
[['descr', 'img', 'reviews'], 'string', 'max' => 255],
// [['file'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'img' => 'Img',
];
}
}
my controller and the action
public function actionCreate()
{
$time = time();
$model = new Products();
$upload = new UploadForm();
if ($model->load(Yii::$app->request->post()) ) {
//get instance of the uploaded file
$model->img = UploadedFile::getInstance($model, 'img');
//define the file path
$upload->upload();
//save the path in the db
$model->img = 'uploads/' .$upload->randomCharacter .'.'.$model->img->extension;
$model->addtime = $time;
$model->save();
return $this->redirect(['view', 'product_id' => $model->product_id]);
}else {
return $this->render('create', [
'model' => $model,
]);
}
}
and my view file has been modified too thanks for any help
$path = '/uploads/';
That means you are uploading files to /uploads, the top level folder in the system.
Run cd /uploads in your terminal and check, most likely files were uploaded there.
To fix that, you need to specify correct full path. The recommended way to do it is using aliases.
In case of advanced application, you already have #backend alias, so you can use it:
$this->img->saveAs(\Yii::getAlias("#backend/web/uploads/{$randomString}.{$this->img->extension}");
Or create your own alias in common/config/bootstrap.php:
Yii::setAlias('uploads', dirname(dirname(__DIR__)) . '/backend/web/uploads');
And then use it like this:
Yii::getAlias('#uploads');
Don't forget to include use Yii if you are not in root namespace or use \Yii;
If you want your images to be accessible on frontend, you can create symlink between frontend and backend images folders.