I have a form of uploading a file and everything works. I just need to set the folder into which files will be thrown.
My files: http://wklej.org/id/1756722/
Just add filter RenameUpload to Your FilesFilter:
Form/FilesFilter:
<?php
namespace DynamicAppModuleFiles\Form;
use Zend\InputFilter\InputFilter;
class FilesFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name'=> 'upload',
'required'=> true,
'validators' => array(
array('name'=>'NotEmpty')
),
'filters' => array(
array(
'name' => 'File/RenameUpload',
'options' => array(
'target' => 'path/to store/files'
)
)
)
));
}
}
More options you can find here: http://framework.zend.com/manual/current/en/modules/zend.filter.file.html#renameupload
EDIT:
Also make sure that you're calling $form->getInputFilter()->getValues(); after $form->isValid()
Related
this is the content of the autoload/global.php file :
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=web_builder;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
this is the content of the autoload/local.php file:
return array(
'db' => array(
'username' => 'DB_User_Name',
'password' => 'DB_Password',
,
); )
this is part of the content of module/Module.php :
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\Adapter\Adapter;
.........
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Controller\UserController' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new Model\StickyNotesTable($dbAdapter);
return $table;
},
),
);
}
Here I really don't understand what this function do, I just copy pasted from an example. If you could explain me what does getServiceConfig function do, I will really appreaciate it.
Finally the controller content:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
class UserController extends AbstractActionController{
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
}
public function loginAction(){
// here i just want to a simple select and yes I know queries will be executed
//in Model, but I want to here a simple query.
//For example in Codeigniter I can't do in model, controller, or view as well.
return new ViewModel();
}
The result of all this code is obviously an error:
Catchable fatal error: Argument 1 passed to Application\Controller\UserController::__construct() must be an instance of Zend\Db\Adapter\Adapter, none given, called in C:\xampp\htdocs\zf2\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170 and defined in C:\xampp\htdocs\zf2\module\Application\src\Application\Controller\UserController.php on line 21
Can someone post an answer to make this database or query stuff work ? thx
I have a following Link in zf2
<?php echo $this->translate('Enquiries') ?>
and this router in zf2
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
which convert above link into
Enquiries
which is fine.
I am using angularjs, which uses anchor fragments a lot.
How can I add achor "#/active" on above zf2 link url, so target url look something like this.
Active Enquiries
do you have a reason why you are not just adding the anchor manually after the url definition url(...).'#/active' ?
if you have, try this:
'route' => '/[:controller[/:action[#/:anchor]]]',
UPDATE:
I checked the source for router and uri and url , it seems that url view helper accepts a 'fragment' key for the third option so try this :
url('[route]',array([params]),array('fragment'=>'/active'));
Zend/View/Helper/Url
Zend/Mvc/Router/Http/TreeRouteStack
Zend/Uri/Uri
Create following view Helper by extending Url
namespace Application\View\Helper;
use Zend\View\Helper\Url;
class MyUrl extends Url {
public function __invoke($name = null, $params = array(), $options = array(), $reuseMatchedParams = false) {
if (isset($params['anchor']) && !empty($params['anchor'])) {
$anchor = $params['anchor'];
unset($params['anchor']);
} else {
$anchor = '';
}
$link = parent::__invoke($name, $params, $options, $reuseMatchedParams);
return $link . $anchor;
}
}
In Module file add following in factory to add newly created helper
public function getViewHelperConfig() {
return array(
'factories' => array(
'myUrl' => function($sm) {
$locator = $sm->getServiceLocator();
$helper = new \Application\View\Helper\MyUrl;
$router = \Zend\Console\Console::isConsole() ? 'HttpRouter' : 'Router';
$helper->setRouter($locator->get($router));
$match = $locator->get('application')
->getMvcEvent()
->getRouteMatch();
if ($match instanceof RouteMatch) {
$helper->setRouteMatch($match);
}
return $helper;
},
),
);
}
Add anchor in URL as parameter
<?php echo $this->translate('Enquiries') ?>
I've installed Miles Johnson's Uploader plugin and set it up with one of my models and got it working perfectly. Very nice.
Then I went and set it up on another model with almost identical code [the only difference is the upload path] and it won't work on the second model. When I submit the form the plugin doesn't seem to notice; I get an SQL error from an attempt to insert the POST file array straight into the DB.
Here is the code. [Other than this the plugin is imported in the bootstrap]
public $actsAs = array(
'Uploader.Attachment' => array(
'photo' => array(
'name' => 'formatFileName',
'uploadDir' => '/uploads/uses/img/',
'dbColumn' => 'photo',
'maxNameLength' => 30,
'overwrite' => true,
'stopSave' => true,
'allowEmpty' => false,
'transforms' => array(
array('method' => 'resize', 'width' => 240, 'dbColumn' => 'photo_thumb'))
)
),
'Uploader.FileValidation' => array(
'fileName' => array(
'extension' => array('gif', 'jpg', 'png', 'jpeg'),
'required' => true
)
)
);
This is on the model that is not uploading and the only difference is the uploadDir.
Does the plugin only work on one model? Any clues? thnx :}
Edit for extra clarity
Here is my view code:
echo $this->Form->create('Use', array('type' => 'file'));
echo $this->Form->input('Use.photo', array('type' => 'file'));
echo $this->Form->input('Use.desc', array('rows' => '3', 'label' => 'Description'));
echo $this->Form->end('Add to Gallery');
And here is my controller code:
public function add() {
if ($this->request->is('post')) {
$this->Use->set('user_id', $this->Auth->user('id'));
if ($this->Use->save($this->request->data)) {
$this->Session->setFlash('Your Use has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your Use.');
}
}
}
The plugin doesn't work in only one model. You can add more uploader into your site.
The model seems to be good, I suggest you to see into your form to see if you have create the form in the right way into your view (is imporant to put into your form: 'type' => 'file'
example:
echo $this->Form->create('Product', array ('class' => 'form', 'type' => 'file'));
echo $this->Form->input('ModelImage.filename', array('type' => 'file'));
echo $this->Form->submit('Add Image', array('id'=>'add_image'));
echo $this->Form->end();
Or the problem is the name Use try to change the name with another
After checking thru the code with Alessandro [thank you :)] I found the problem.
If you look in the View and Controller code you can see that the model is named 'Use'. This was the problem, as Use is a loaded word in PHP and I shouldn't have used it for a model name.
I renamed the model to Outcome and now the Uploader works perfectly.
Trying to get the CakePHP Upload Plug-in to work. The file uploads fine, the thumbnails are created...etc, but having a few issues:
-the 'name' field in the 'uploads' table is empty
-the 'upload' field in the 'uploads' table is empty ('attachment' field in the doc example)
-if I use {model} in the 'path' set in the Upload model, it uses 'upload' as the model folder - it should go in a folder of the associated model, not the upload model every time
//Upload MODEL
public $actsAs = array(
'Upload.Upload' => array(
'photo' => array(
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'thumb' => '80x80',
),
'thumbnailMethod' => 'php',
'path' => '{ROOT}webroot{DS}uploads{DS}{model}{DS}{field}{DS}',
'maxSize' => '5242880', //5MB
'mimetypes' => array('image/jpeg', 'image/png', 'image/gif', 'image/bmp'),
'extensions' => array('jpg', 'gif', 'png'),
),
)
);
//ArticleData MODEL
public $hasMany = array(
'Upload' => array(
'className' => 'Upload',
'foreignKey' => 'foreign_key',
'conditions' => array(
'Upload.model' => 'ArticleData',
),
),
);
//CONTROLLER
public function admin_upload() {
if(!empty($this->request->data)) {
$this->loadModel('Upload');
debug($this->request->data);
if($this->Upload->save($this->request->data)) {
$this->Session->setFlash('SAVED!!!!!!!!');
} else {
$this->Session->setFlash('NOT SAVED!!!!!!!!');
}
}
}
// VIEW
echo $this->Form->create('ArticleData', array('type'=>'file'));
echo $this->Form->input('Upload.model', array('type'=>'hidden', 'value'=>'ArticleData'));
echo $this->Form->input('Upload.foreign_key', array('type'=>'hidden', 'value'=>'4f93676e-347c-4e0c-8e6c-0a3cadcd7f7c'));
echo $this->Form->input('Upload.photo', array('type'=>'file'));
echo $this->Form->end('Submit');
Dave:
-the 'name' field in the 'uploads' table is empty
This is normal, I think is is more of a "display" name field as opposed to "filename" field. The name should be stored in the "photo" field in your example.
-if I use {model} in the 'path' set in the Upload model, it uses 'upload' as the model folder - it should go in a folder of the associated model, not the upload model every time
You'll want to alias the model, like so:
//ArticleData MODEL
public $hasMany = array(
'AliasModelHere' => array(
'className' => 'Upload',
'foreignKey' => 'foreign_key',
'conditions' => array(
'Upload.model' => 'ArticleData',
),
),
);
// Then
$this->ArticleData->AliasModelHere->save($data)
I am currently trying to use Miles J plugin located here http://milesj.me/code/cakephp/uploader Although I have made great progress learning CakePhp, I am currently having a problem using the plugin and I would appreciate any help provided.
I have followed all the necessary steps to use the plugin. It has been downloaded put on Plugin folder, I bootstrapped with CakePlugin::loadAll().
So far so good.
Next I have proceed to set up the table as indicated by the plugin developer.
Ok, now back to my own code. I have the following set up:
images_controller.php , image.php and their views.
My goal now is to use the plugin inside those files as such:
App::import('Vendor', 'Uploader.Uploader');
Class ImagesController extends AppController {
var $components = array('Auth');
var $helpers = array('Design');
var $uses = array('Image', 'Uploader.Upload');
function manage(){
//here I show a simple upload form that uses the action saveimage
}
function saveimage(){
$this->Uploader = new Uploader();
if(!empty($this->data)){
$this->Upload->save($this->data);
}
}
}
Now, my model is set as follows
Class Image extends AppModel {
public $useTable = 'uploads';
public $actsAs = array(
'Uploader.FileValidation' => array(
'file' => array(
'extension' => array(
'value' => array('gif', 'jpg', 'jpeg'),
'error' => 'Only gif, jpg and jpeg images are allowed!'
),
'minWidth' => 500,
'minHeight' => 500,
'required' => true
),
'import' => array(
'required' => false
)
),
'Uploader.Attachment' => array(
'file' => array(
'name' => 'uploaderFilename',
'uploadDir' => '/files/uploads/',
'dbColumn' => 'path',
'maxNameLength' => 30,
'overwrite' => true,
'stopSave' => false,
'transforms' => array(
// Save additional images in the databases after transforming
array(
'method' => 'resize',
'width' => 100,
'height' => 100,
'dbColumn' => 'path_alt'
)
),
'metaColumns' => array(
'size' => 'filesize', // The size value will be saved to the filesize column
'type' => 'type' // And the same for the mimetype
)
),
'import' => array(
'uploadDir' => '/files/uploads/',
'name' => 'uploaderFilename',
'dbColumn' => 'path',
'overwrite' => true,
'stopSave' => false,
'transforms' => array(
array(
'method' => 'scale',
'percent' => .5,
'dbColumn' => 'path' // Overwrite the original image
)
)
)
)
);
}
}
On my model for testing purposes I have not changed anything but just copied and pasted the very same array as shown in the the Test/Model folder inside the plugin, which is meant to show the functionality of the plugin.
The following confusion, errors or lack of understanding is taking place:
My file is not being uploaded to the webroot/files/uploads folder
My data is being inserted in the database, but not in a complete manner by leaving empty as shown:
id | caption | path | path_alt | created |
4 | | | |2012:02:..|
Above, I expect the path to be saved, but it doesn't.
I have to admit my confusion comes mainly from my inexperience using plugins, so I am aware I might be doing something wrong regarding my models or my configuration.
Any prompt help would be appreciated greatly as I have tried to work this out on my own without any success.
A few things:
1 - In your controller you do not need to import the Uploader class. You also don't need to use the Uploader.Upload model (it's merely an example test case). All you need to do in the controller is call $this->Image->save() which will upload the file and save the path as a row into the database (if you defined the Attachment in Image).
2 - In your view, create the file input. Pay attention to the input name.
echo $this->Form->input('FILE_INPUT_NAME', array('type' => 'file'));
3 - In your Image model, setup the AttachmentBehavior and its options for that specific input field:
'Uploader.Attachment' => array(
'FILE_INPUT_NAME' => array(
'uploadDir' => '/files/uploads/',
'dbColumn' => 'path'
),
'ANOTHER_INPUT' => array()
);
Be sure that the column "path" exists in your images table. And thats it.
For more information on what each option does, check out the following: http://milesj.me/code/cakephp/uploader#uploading-files-through-the-model