How can I get the parameter in the URL and save it to a varialble so I can save it to my database?
example: www.mydomain.com/item/products/3 <-
This is for my upload image, so I can specify what product ID will I use for that image.
function add() {
if ($this->request->is('post')) {
$this->Upload->create();
if(empty($this->data['Upload']['image']['name'])) {
unset($this->request->data['Upload']['image']);
}
if(!empty($this->data['Upload']['image']['name'])) {
$filename = $this->request->data['Upload']['image']['name'];
$new_filename = STring::uuid().'-'.$filename;
$file_tmp_name = $this->request->data['Upload']['image']['tmp_name'];
$dir = WWW_ROOT.'img'.DS.'uploads';
move_uploaded_file($file_tmp_name,$dir.DS.$new_filename);
$this->request->data['Upload']['image'] = $new_filename;
if($this->Upload->save($this->request->data)) {
$this->Session->setFlash(__('Uploaded.'));
$this->redirect(array('action' => 'index'));
}
}
}
}
How will I add it here. Thank you in advance :)
Im using cakePHP
Just add the product id as a hidden input in the Form.
Then it will be included in the $this->data variable when you get the POST request.
For example in a controller method like the following
public function product($id) {
.....
}
You access it by the url (for example): www.mydomain.com/item/products/3 where Item is the controller, product is the method you are calling in that controller and 3 represent a parameter that is required to the function to work in this case $id. (assuming you don't have any routing configuration)
Is treated as a normal php variable, just do whatever you wanna do with it. Just make sure you pass the correct value
Related
I want to render the view to a variable without directly sending it to the browser. I used to do it with cakephp2.*. But, I cannot figure out how to do it in CakePHP3. Could you please tell me how to do it?
ViewBuilder was introduced in CakePHP 3.1 and handles the rendering of views. When ever I want to render to a variable I always go look at how send email works.
From a controller:
function index() {
// you can have view variables.
$data = 'A view variable';
// create a builder (hint: new ViewBuilder() constructor works too)
$builder = $this->viewBuilder();
// configure as needed
$builder->layout('default');
$builder->template('index');
$builder->helpers(['Html']);
// create a view instance
$view = $builder->build(compact('data'));
// render to a variable
$output = $view->render();
}
For Ajax request/response, I use this:
public function print(){
if ($this->request->is('ajax')) {
$data = $this->request->getData();
$builder = $this->viewBuilder()
->setTemplatePath('ControllerName')
->setTemplate('print');
->setLayout('ajax');
->enableAutoLayout(false);
$view = $builder->build(compact('data'));
$html = $view->render();
$res = ['html' => $html];
$this->set('response',$res);
$this->set("_serialize",'response');
}
}
And the print.ctp is under Template/ControllerName
In cakephp I have a search function which uses parameters and call backs. My issue is that I want to call this function with a parameter but the function cant accept parameters when called.
//I cant call this function with a paramater
$this->redirect(array('action' => 'email_list',$id,));
....
public function email_list($search = 0) {
$this->set( 'search',$search);
;
if (($this->request->is('post') || $this->request->is('put'))) {
if (isset($this->request->data['searchFilter'])) {
$filter_url['controller'] = $this->request->params['controller'];
$filter_url['action'] = $this->request->params['action'];
$filter_url['page'] = 1;
// for each filter we will add a GET parameter for the generated url
foreach($this->data['User'] as $name => $value){
if($value){
$filter_url[$name] = urlencode($value);
}
}
//Post params are now GET paramaters
return $this->redirect($filter_url);
}//isset
worked out a solution using a session variable that gets destroyed on entry. It is quick and easy. Having to redo a search function in cakephp ver 2 is not something i want to do. I am updating to cakephp ver 3
public function email_list($search = 0) {
if ($this->Session->check('sessrowid'))
{
$searchRowId=$this->Session->read('sessrowid');
$this->Session->delete('sessrowid');
}
I am using CakePHP 3. My action is:
function OrderFromReseller($api_key) {
$this->render('index');
$this->loadModel('Psetting');
$products = $this->Psetting->find('all');
$this->set(compact('products'));
}
Here I render another ctp file called index.ctp. Now 'products' variable is undefined in index. How to set this variable to index.ctp file from this action?
You need to call $this->render('index') last:-
function OrderFromReseller($api_key) {
$this->loadModel('Psetting');
$products = $this->Psetting->find('all');
$this->set(compact('products'));
$this->render('index');
}
render() tells Cake to generate the View so anything that follows will not get taken into account by the template as it has already been rendered.
Element file I am calling:
$brand = $this->requestAction('brands/buyer_getnames/');
Action file I am calling:
public function buyer_getnames(){
$newid=$this->Auth->User('brand_id');
$name=$this->Brand->find('first',array('conditions'=>array('Brand.id'=>$newid),'recursive'=>-1));
return $name['Brand']['name'];
}
Getting error below..!!
Private Method in BrandsController
Error: BrandsController::buyer_getnames() cannot be accessed directly.
Please help
Request action respects normal url routing rules
If you're using prefix routing then you can't access function prefix_foo() via a url of the form /controller/prefix_foo - it needs to be the corresponding prefix url: /prefix/controller/foo.
As such your request action call should be:
$brand = $this->requestAction('/prefix/brands/getnames/');
Note that if the only thing that method does is call a model method, you're better off simply doing:
$model = ClassRegistry::init('Brand');
$brand = $model->someMethod();
You can allow unauthorized access to action if your action is requested with requestAction method.
For example:
public function beforeFilter() {
parent::beforeFilter();
if ($this->request->is('requested') && $this->request->params['action'] == 'index') {
$this->Auth->allow(array('index'));
}
}
This may also work (haven't tested):
public function index() {
if ($this->request->is('requested')) {
$this->Auth->allow(array('index'));
}
}
let me know if i can help you more.
I am trying to invalidate a field by a condition in controller instead of Model.
$this->Model->invalidate('check_out_reason', __('Please specify check out reason.', true));
The above won't work to invalidate the field. Instead, I need the below:
$this->Model->invalidate('Model.check_out_reason', __('Please specify check out reason.', true));
However, if I wish get the error message show up in the "field" itself ($this->model->validationErrors), it needs to be "check_out_reason" instead of "Model.check_out_reason". That means, I can't get the error message to show up in the field itself if I wish to invalidate the input in controller.
May I know is this a bug in CakePHP?
i created a test controller called "Invoices", just for testing, and i developed the following function
public function index(){
if (!empty($this->request->data)) {
$this->Invoice->invalidate('nombre', __('Please specify check out reason.'));
if ($this->Invoice->validates()) {
// it validated logic
if($this->Invoice->save($this->request->data)){
# everthing ok
} else {
# not saved
}
} else {
// didn't validate logic
$errors = $this->Invoice->validationErrors;
}
}
}
i think it worked for me
Change the field "nombre" for your field called "check_out_reason" to adapt the function to your code
I found a workaround for manual invalidates from controller. Reading a lot on this issue I found out that the save() function doesn't take in consideration the invalidations set through invalidate() function called in controller, but (this is very important) if it is called directly from the model function beforeValidate() it's working perfectly.
So I recommend to go in AppModel.php file and create next public methods:
public $invalidatesFromController = array();
public function beforeValidate($options = array()) {
foreach($this->invalidatesFromController as $item){
$this->invalidate($item['fieldName'], $item['errorMessage'], true);
}
return parent::beforeValidate($options);
}
public function invalidateField($fieldName, $errorMessage){
$this->invalidatesFromController[] = array(
'fieldName' => $fieldName,
'errorMessage' => $errorMessage
);
}
After that, make sure that your model's beforeValidate() function calls the parent's one:
public function beforeValidate($options = array()) {
return parent::beforeValidate($options);
}
In your controller for invalidating a field use next line:
$this->MyModel->invalidateField('fieldName', "error message");
Hope it helps! For me it's working!