how to create directory on field name cakephp - php

I would like to get object by id from database inside Controller then use its name to create directory with that name.
public function album($id = null) {
$dirname = $this->Dog->query('SELECT * from dogs WHERE id='$id'');
$dir = new Folder(WWW_ROOT . 'albums' . DS . 'files' . DS . $dirname->name , true, 0755);
$this->layout = 'edit';
if (!$id) {
throw new NotFoundException(__('Zły post'));
}
$Dog = $this->Dog->findById($id);
if (!$Dog) {
throw new NotFoundException(__('Zły post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Dog->id = $id;
if ($this->Dog->save($this->request->data)) {
$this->Session->setFlash(__('Edycja zakończona sukcesem.'));
$this->redirect(array('action' => 'index_psy'));
} else {
$this->Session->setFlash(__('Spróbuj ponownie.'));
}
}
}
I have tried a few other solutions but none of them seems to work.
Thanks for help

public function album($id) {
//if id doesn't exist Exit
if (!$this->Dog->exists($id)) {
throw new NotFoundException(__('Invalid album'));
}
$dog = $this->Dog->findById($id);
//create a folder with directory name
$path = 'files' . DS . $dog['Dog']['name'];
$folder = new Folder($path , true, 0755);
$this->layout = 'edit';
}
}
look at here just to get an idea

Related

Import CSV file to Database using Yii2

I'm trying to import CSV file to the database using yii2 framework.
Controller
public function actionIndex($message=””)
{
// $model = new ProjectDocument;
//error_reporting(E_ALL);
//ini_set('display_error', 1);
$model = new ProjectDocument();
if ($model->load(Yii::$app->request->post()) ) {
$model->file = UploadedFile::getInstance($model, 'file');
// if ($model->load(Yii::$app->request->post())){
// $filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$title = _file[1];
$description = $file[2];
$phase = $file[3];
$modelnew->title = $title;
$modelnew->description = $description;
$modelnew->phase = $phase;
$modelnew->save();
}
unlink('uploads/'.$filename);
return $this->render('create',array('model'=>$model, 'message'=>$message));
}
}else{
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
return $this->render('create',array('model'=>$model, 'message'=>$message
));
}
But I getting an error like this,
"Access to undeclared static property: Yii::$app"
Anyone can help me to rectify the error, Thank you in advance..

update a record without removing the uploaded file in yii

I need to UPDATE record with out changing or deleting filename(i mean file) , OR reinsert file again so how i can do this?
here is my actionCreate, How i can write update?
public function actionCreate() {
$model = new Page;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save()) {
if ($model->filename !== null) {
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
So Please can anyone find a solution
If you don't need to change or delete filename in edit/update then ignore filename (and upload part) assuming the file is alrready uploaded and you don't wish to change/delete it.
public function actionUpdate($id) {
$model = $this->loadModel($id);
$file = $model->filename;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = $file;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Try this, it's working for me -
create a upload folder outside protected directory and also give read/write permission.
actionCreate function -
public function actionCreate() {
$model = new Page();
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if(!empty( $fileName)){
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias('application') . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
if(!$model->hasErrors() && $model->validate() && $model->save(false)) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'success'));
}
}
}
actionUpdate function -
public function actionUpdate() {
$model = Page::model()->findbyPK($id);
$model->scenario = 'update';
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
if(empty($_POST['Page']['filename'])) { $file_name = $model->filename; } //store existing file name into a variable if your uploading a file on update
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if($model->validate()) {
if(!empty($fileName)) {
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias( 'application' ) . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
else {
$model->filename = $file_name; //allow existing file name
}
if( !$model->hasErrors() && $model->save(false) ) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'update'));
}
}
}
In model rules array define this -
array('filename', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')

Inserting uploaded filenames into database table

I am trying to insert uploaded filenames to a table with the date they were uploaded, but I am running into some errors with trying to get the values of the filename with $_FILES
Here is my code:
public function uploadAction()
{
if (!$user = $this->identity()) {
return $this->redirect()->toUrl('/login/log');
}
$user = $this->identity();
$layout = $this->layout();
$layout->setVariable('user1', $user->username);
$form = new FileUploadForm();
$request = $this->getRequest();
if ($request->isPost()) {
$file = new File();
$form->setInputFilter($file->getInputFilter());
$captions = $request->getPost()->toArray();
$get_file = $this->params()->fromFiles('file');
$data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min' => '10kB', 'max' => FileHandler::FILESIZE . 'MB'));
$extension = new Extension(array('jpg', 'jpeg', 'png'), true);
$adapter = new Http();
$adapter->setValidators(array($size, $extension), $get_file['name']);
if (!$adapter->isValid()) {
return $this->redirect()->toUrl('/admin/upload-failure');
} else {
$dir_check = !is_dir(FileHandler::UPLOAD_PATH . $user->username)
?
mkdir(FileHandler::UPLOAD_PATH . $user->username) ? FileHandler::UPLOAD_PATH . $user->username : null
: FileHandler::UPLOAD_PATH . $user->username;
$adapter->setDestination($dir_check);
if ($adapter->receive($get_file['name'])) {
$this->getFileUploadFactory()->insertUploadDate($_FILES);
$file->exchangeArray($form->getData());
return $this->redirect()->toUrl('/admin/upload-success');
} else {
return $this->redirect()->toUrl('/admin/upload-failure');
}
}
}
}
public function insertUploadDate(array $file)
{
try {
$insert = new Insert('uploads');
foreach ($file as $key => $value) {
$insert->columns(array('filename', 'upload_date'))
->values(array('filename' => $value, 'upload_date' => date('Y-m-d')));
$adapter = $this->table_gateway->getAdapter();
$adapter->query(
$this->sql->getSqlStringForSqlObject($insert),
$adapter::QUERY_MODE_EXECUTE
);
}
return true;
} catch (\PDOException $e) {
// save the exception message to the error file
$writer = new Stream(self::ERROR_PATH);
$logger = new Logger();
$logger->addWriter($writer);
$logger->info($e->getMessage() . "\r\r");
return false;
}
}
and then in the controller I am calling it like this:
$this->getFileUploadFactory()->insertUploadDate($_FILES);
Like I said, it's not inserting the correct names of the files I uploaded (using html5 multiple upload option)
Thanks!

CakePHP Cache::clear does not work

I have a Cache Configuration in my bootstrap.php file as
Cache::config('long', array(
'engine' => 'File',
'duration' => '+1 week',
'probability'=> 100,
'mask' => 0666,
'path' => CACHE . 'long' . DS,
));
and i am trying to clear cache when a setting is edited. Below is my admin_edit function
public function admin_edit($id = null) {
if (!$this->Setting->exists($id)) {
throw new NotFoundException(__('Invalid setting'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Setting->save($this->request->data)) {
$this->Session->setFlash(__('The setting has been saved'));
$this->redirect(array('action'=> 'index'));
Cache::clear(false,'long');
Cache::gc();
}else {
$this->Session->setFlash(__('The setting could not be saved. Please, try again.'));
}
}else {
$options = array('conditions' => array('Setting.' . $this->Setting->primaryKey=> $id));
$this->request->data = $this->Setting->find('first', $options);
}
}
However, Cache::clear(false,'long') does not work and it does not clear the Cache. Not sure what is going wrong. Stuck for a few days now!
Please use below function in any controller and run that function where you want it will be clear all cache.
/**
* function to clear all cache data
* by default accessible only for admin
*
* #access Public
* #return void
*/
public function clear_cache() {
Cache::clear();
clearCache();
$files = array();
$files = array_merge($files, glob(CACHE . '*')); // remove cached css
$files = array_merge($files, glob(CACHE . 'css' . DS . '*')); // remove cached css
$files = array_merge($files, glob(CACHE . 'js' . DS . '*')); // remove cached js
$files = array_merge($files, glob(CACHE . 'models' . DS . '*')); // remove cached models
$files = array_merge($files, glob(CACHE . 'persistent' . DS . '*')); // remove cached persistent
foreach ($files as $f) {
if (is_file($f)) {
unlink($f);
}
}
if(function_exists('apc_clear_cache')):
apc_clear_cache();
apc_clear_cache('user');
endif;
$this->set(compact('files'));
$this->layout = 'ajax';
}
Once let me know if not working for you :)
Thanks

Is using Controller::render() in a Model::afterSave() possible with CakePHP?

I've got some sample code that I'd like to refactor as I need it to work after a record is saved. It currently works after the record is first rendered (using the afterFilter). What it does is render the view that I want with the layout and saves it to a file.
function afterFilter() {
parent::afterFilter();
if($this->params['pass'][0] == 'contact') {
$surrenderOuput = $this->surrender($this->params['pass'][0]);
$path = WWW_ROOT . 'cache' . DS . $this->params['pass'][0] . DS . 'index.html';
$file = new File($path, true);
$file->write($surrenderOuput);
$file->close();
}
}
function surrender($action = null, $layout = null, $file = null) {
$this->beforeRender();
$viewClass = $this->view;
if ($this->view != 'View') {
if (strpos($viewClass, '.') !== false) {
list($plugin, $viewClass) = explode('.', $viewClass);
}
$viewClass = $viewClass . 'View';
App::import('View', $this->view);
}
$this->Component->beforeRender($this);
$this->params['models'] = $this->modelNames;
if (Configure::read() > 2) {
$this->set('cakeDebug', $this);
}
$View =& new $viewClass($this);
if (!empty($this->modelNames)) {
$models = array();
foreach ($this->modelNames as $currentModel) {
if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
$models[] = Inflector::underscore($currentModel);
}
$isValidModel = (
isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
!empty($this->$currentModel->validationErrors)
);
if ($isValidModel) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$this->$currentModel->validationErrors;
}
}
$models = array_diff(ClassRegistry::keys(), $models);
foreach ($models as $currentModel) {
if (ClassRegistry::isKeySet($currentModel)) {
$currentObject =& ClassRegistry::getObject($currentModel);
if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$currentObject->validationErrors;
}
}
}
}
$this->autoRender = false;
$output = $View->render($action, $layout, $file);
return $output;
}
So I'm basically rendering the view with it's layout, and returning it as output, and saving it to a file. Great. Is there any way to do something similar in a model?
You may consider setting a member variable in your afterSave() in the model and checking that value in your afterFilter() in your controller.
I found this thread while searching for how to render a view from a model. In my case I'm calling a custom method in the model, so this might not work for afterSave(), but if you're calling a custom method you can do it like this:
Controller:
$this->Model->myFunc($this);
Model
public function myFunc($object) {
$object->render();
}
Hopefully that helps someone else who comes across this thread.

Categories