PHP code example of rikcage / yii2-import

1. Go to this page and download the library: Download rikcage/yii2-import library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rikcage / yii2-import example snippets


class Post extends Model
{
	const STATUS_NEW = 0;
	const STATUS_APPROVED = 1;
	
	public $title;
	public $status;
	public $content;
	
	public static function getStatusList()
	{
		return [
			self::STATUS_NEW = 'New',
			self::STATUS_APPROVED = 'Approved',
		];
	}
}

class ImportForm extends Model
{
	public $file;
	
	public function rules()
	{
		return [
			['file', 'file', 'skipOnEmpty' => false, 'extensions' => 'xlsx'],
		];
	}
}

 $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); 

$uploadFile = UploadedFile::getInstance($model, 'file');
$importer = new Importer([
	'file' => $uploadFile,
	'modelClass' => Post::className(),
	'skipRowsCount' => 3, // description lines and header lines should be skipped
	'columnMappings' => [
		[
			'attribute' => 'title',
			'his attribute to true, importer will help you validate the models and report the validation errors by $importer->validationErrors
]);

try {
	$posts = $importer->import();
} catch (InvalidFileException $e) {
	$model->addError('file', 'Invalid import file.');
}

[
	4 => Post{title='Post 1', status=0, content='Content 1'},
	5 => Post{title='Post 2', status=1, content='Content 2'},
	7 => Post{title='Post 3', status=0, content='Content 4'},
]

Yii::$app->session->setFlash("success", count($importer->getImportRows()) . ' rows had been imported');
foreach ($importer->getValidationErrors() as $lineno => $errors) {
	foreach ($errors as $attribute => $errorMessages) {
		$error = $errorMessages[0];
		break;
	}
	Yii::$app->session->addFlash("error", 'Line ' . $lineno . ' has error: ' . $error);
}