Cakephp ajax form won't load the right view - cakephp

I'm just trying to call a function from a form submision (which is also call from ajax).
I want to call the add method but it's the index which always called.
My ajax view with the ajax submission form :
<?php $count = count($files); ?>
<div id="message"></div>
<i><?= __('Nombre de fichiers liƩs : ') . $count ?></i>
<?= $this->Form->create('FilesManager', array('enctype' => 'multipart/form-data', 'url' => array('action' => 'add'))); ?>
<?= $this->Form->input('file', array('type' => 'file', 'label' => false, 'class' => 'form-control')); ?>
<?= $this->Js->submit('Envoyer', array('update' => '#message', 'div' => false, 'type' => 'json', 'async' => false)); ?>
<?= $this->Js->writeBuffer(); ?>
i've also tried :
<?= $this->Form->create(null, array('enctype' => 'multipart/form-data', 'url' => array('controller' => 'FilesManagers', 'action' => 'add'))); ?>
<?= $this->Form->create('FilesManager/add', array('enctype' => 'multipart/form-data')); ?>
EDIT
$this->Form->create('FilesManager', array('action' => 'add'))
Don't work for me but the form generated look like :
<form action="/agralis/files_managers/add" enctype="multipart/form-data" id="FilesManagerIndexForm" method="post" accept-charset="utf-8">...<input id="submit-838644811" type="submit" value="Envoyer"><script type="text/javascript">
//<![CDATA[
$("#submit-838644811").bind("click", function (event) {$.ajax({async:false, data:$("#submit-838644811").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#message").html(data);}, type:"post", url:"\/agralis\/FilesManagers"});
return false;});
//]]>
</script></form>
I can see that form action look good (when i copy/paste the action in the browser url he found the method) but the url called from the ajax submit button is wrong ! How can I change that ?

The helpers are working independently
The Js helper is not aware of the Form helper, they don't interact with each other, and so the form URL is unknown to the Js helper.
The solution for that problem is rather simple, just look at the docs:
http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::submit
The submit() method accepts a url option where you can specify a URL in case the default one that is based on the current request doesn't fit you.
$this->Js->submit('Envoyer', array(
'url' => array('action' => 'add')
// ...
));
File uploads are not supported
The next problem that you'll encounter is that the file upload doesn't work. That's not part of the question, but I'll broach the subject.
The Js helper doesn't support generating the required JavaScript to handle file uploads, it would need to make use of the XMLHttpRequest Level 2 (xhr2) functionalities that older browsers are lacking.
You'll have to write custom JavaScript to handle that. Explanations and tutorials regarding that can be found all over the web.

Related

Why does CakePHP transform POST requests into PUT?

I'm running CakePHP 4.4.7 using PHP 8.0.23.
I have a controller
class StrawberriesController extends AppController
{
public function eat($id = null)
{
\Cake\Log\Log::debug(json_encode($this->request->getMethod()));
$this->request->allowMethod(['get', 'post']);
...
}
}
I have a template with a form
<?= $this->Form->create($entity, [
'url' => [
'controller' => 'Strawberries',
'action' => 'eat',
$entity->id,
],
]) ?>
<?= $this->Form->text('is_asap') ?>
<?= $this->Form->submit('now') ?>
<?= $this->Form->end() ?>
When I submit the form, the debug line shows
2022-11-03 16:58:06 debug: "PUT"{
"scope": []
}
I expected to receive an HTTP POST request. Especially because using the devtools:
in the elements tab, the form element has the attribute method="post"
in the network tab, the HTTP method inside the sent request is a POST
So why is the HTTP method transformed by CakePHP from POST to PUT?
How can I receive a POST request on my controller?
When you pass an entity with an ID (an existing element) in the first parameter of your $this->Form->create() CakePHP consider that is an update of your entity. And the convention for an update is to use "PUT" or "PATCH".
You can force the POST method like this :
$this->Form->create($entity, [
'url' => ['controller' => 'Strawberries', 'action' => 'eat', $entity->id],
'type' => 'POST'
]);
Doc : https://book.cakephp.org/4/en/views/helpers/form.html#options-for-form-creation

In Yii2, I need to download the file that I uploaded in /web/uploads/ folder. How do i do it?

Here is the the part of the view, I made a download button.
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Download', ['download', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
Here is the download function on my controller, I cant get it to work.
public function actionDownload($id)
{
$model = new Items();
$path = Yii::getAlias('#webroot');
$file = $path . '/' .$model->item_pathname;
if (file_exists($file)) {
Yii::$app->response->sendFile($file);
}
}
The path of the file is saved in the database's item_pathname (e.g. "/uploads/samplefile.doc". I don't know how to successfully access it to append it to the path variable. It would be of great help to solve this for me. Thanks!
If a download takes too much time, I see 2 possibilities
You can increase the max execution time of your script. That's not the best solution as the script will still time out for too big files but that's the simplest solution (there may be performance considerations unrelated to your question). To do so :
ini_set('max_execution_time', 5*60); // 5 minutes
You can use the X-SendFile header of Apache (if this module in enabled in Apache only) to let Apache handle the sending of the file. More about this on Yii2 documentation http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#sending-files. Beware of bugs in IE<=8.
if (file_exists($file)) {
Yii::$app->response->xSendFile($file);
}

How to use class in anchor tag and img tag

<img src="images/abc.jpg" class="img-style row2">.
I have to use above code in cakephp3. I have tried by html helper but there is some syntax error with my code.
Here is my code,
<?php echo $this->Html->link('".$this->Html->image('abc.jpg', ['class' => 'img-style row2'])."', $this->Html->image('xyz.jpg', ['class' => 'swipebox'])); ?>
Please help anybody regarding this.
Use image method into link method then use 'escape' => false, see example
echo $this->Html->link(
$this->Html->image('img.jpg',['class'=>'img-class','alt' => 'img',]),
['controller'=>'', 'action'=>''],
['escape' => false,'class'=>'link-class']
);

Multiple form with same model name on single page cakephp

I have two form on a single page: login form and register form. When I submit the register form, it validates both: form fields that are in login and registeration. How can I handle it if both form have the same model (user model)
Register form
<?php echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'add'))); ?>
<?php echo $this->Form->input('username', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('email', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('password', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('confirm_password', array('type' => 'password', 'label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->submit(__('Submit', true), array ('class' => 'reg_button', 'div' => false));
echo $this->Form->end();?>
and Login form is below
<?php echo $this->Form->create('User', array('controller' => 'users', 'action' => 'login'))?>
<?php echo $this->Form->input('User.username',array('label'=>false,'div'=>false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('User.password',array('label'=>false,'div'=>false, 'class' => 'reg_input'));?>
<?php echo $this->Form->submit(__('Log in', true), array ('class' => 'reg_button', 'div' => false)); ?>
<?php echo $this->Form->end();?>
When I submit registration form it validates both forms, I want to validate only the registration form.
How can I handle that?
I've come up with a "solution" (I find the approach dirty, but it works) for a different question (very similar to this). That other question worked with elements and views, though. I'll post the entire solution here to see if it helps someone (though I rather someone else comes with a different approach).
So, first: change the creation names for the two forms.
//for the registration
<?php echo $this->Form->create('Registration',
array('url' => array('controller' => 'users', 'action' => 'add'))); ?>
//for the login
<?php echo $this->Form->create('Login',
array('controller' => 'users', 'action' => 'login'))?>
The forms should work, look and post to the same actions, so no harm done.
Second step: I don't have your action code, so I'm going to explain what needs to be done in general
public function login() {
if ($this->request->is('post')) {
//we need to change the request->data indexes to make everything work
if (isset($this->request->data['Login'] /*that's the name we gave to the form*/)) {
$this->request->data['User'] = $this->request->data['Login'];
unset($this->request->data['Login']); //clean everything up so all work as it is working now
$this->set('formName', 'Login'); //we need to pass a reference to the view for validation display
} //if there's no 'Login' index, we can assume the request came the normal way
//your code that should work normally
}
}
Same thing for the registration (only need to change 'Login' to 'Registration').
Now, the actions should behave normally, since it has no idea we changed the form names on the view (we made sure of that changing the indexes in the action). But, if there are validation errors, the view will check for them in
$this->validationErrors['Model_with_errors']
And that 'Model_with_errors' (in this case 'User') won't be displayed in the respective forms because we've changed the names. So we need to also tweak the view. Oh! I'm assuming these both forms are in a view called index.ctp, for example, but if they are on separate files (if you're using an element or similar) I recommend add the lines of code for all the files
//preferably in the first line of the view/element (index.ctp in this example)
if (!empty($this->validationErrors['User']) && isset($formName)) {
$this->validationErrors[$formName] = $this->validationErrors['User'];
}
With that, we copy the model validation of the User to the fake-named form, and only that one. Note that if you have a third form in that view for the same model, and you use the typical $this->form->create('User'), then the validation errors will show for that one too unless you change the form name for that third one.
Doing that should work and only validate the form with the correct name.
I find this a messy approach because it involves controller-view changes. I think everything should be done by the controller, and the view shouldn't even blink about validation issues... The problem with that is that the render function of Controller.php needs to be replaced... It can be done in the AppController, but for every updgrade of Cakephp, you'll have to be careful of copying the new render function of Controller.php to the one replacing it in AppController. The advantage of that approach, though, is that the "feature" would be available for every form without having to worry about changing the views.
Well, it's just not that maintainable anyway, so better to leave it alone if it's just for this one case... If anyone is interested on how to handle this just in the controller side, though, comment and I'll post it.
You can duplicate your model and change his name and define $useTable as the same table name.
Example :
class Registration extends AppModel {
public $useTable = 'users';
You define the action in form->create like Nunser for your login form
<?php
echo $this->Form->create('User',array(
'url' => array(
'controller' => 'Users',
'action' => 'login',
'user' => true
),
'inputDefaults' => array(
'div' => false,
'label' => false
),
'novalidate'=>true,
));
?>
and your registration form
<?php
echo $this->Form->create('Registration',array(
'url' => array(
'controller' => 'Users',
'action' => 'validation_registration',
'user' => false
),
'inputDefaults' => array(
'div' => false,
'label' => false
),
'novalidate'=>true,
));
?>
In your controller define a method for registration validation and the most important define the render
public function validation_registration(){
$this->loadModel('Registration');
if($this->request->is('post')){
if($this->Registration->save($this->request->data)){
--- code ---
}else{
--- code ---
}
}
$this->render('user_login');
}
Sorry for my english ! Have a nice day ! :D
The create method on your login form is missing the 'url' key for creating the action attribute. I tried to re-create this once I fixed this and could not. Maybe that will fix it?

CakePHP Canonical Tag with html helper

How can I create this using the html helper? (with inline=false so i can specify it on a per-view basis)
<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish" />
Can't seem to find anything on this, apart from a patch that doesn't work.
Found this in CakePHP bugtracking site : http://cakephp.lighthouseapp.com/projects/42648/tickets/1063-support-for-custom-meta-tag-elements-in-htmlhelper
Apparently you can use
echo $this->Html->meta('canonical', 'http:://example.com', array('rel'=>'canonical', 'type'=>null, 'title'=>null));
//outputs <link href="http:://example.com" rel="canonical" />
It seems my friend just told me that I told him how to do this a few months back, problem solved...
<?php echo $this->Html->meta('canonical',
'http://www.example.com/product.php?item=swedish-fish',
array('rel'=>'canonical', 'type'=>null, 'title'=>null, 'inline' => false)
);?>
If you're looking for something that automatically outputs the current url into a canonical tag, you can use the $this->Html->url(null, true); or $this->here; within the Cakephp html helper.
<?php echo $this->Html->meta('canonical', $this->Html->url(null, true), array('rel'=>'canonical', 'type'=>null, 'title'=>null)); ?>
Or
<?php echo $this->Html->meta('canonical', $this->here, array('rel'=>'canonical', 'type'=>null, 'title'=>null)); ?>
WARNING:
I have heard of some cases where $this->here has issues on local dev environments.
In CakePHP 2:
echo $this->Html->meta('canonical', 'http://example.com', array('rel' => 'canonical', 'type' => null, 'title' => null, 'inline' => false));
In CakePHP 3:
echo $this->Html->meta('canonical', 'http://example.com', array('rel' => 'canonical', 'type' => null, 'title' => null, 'block' => true));
Note that the main difference between versions is that CakePHP 2 uses 'inline' => false whereas CakePHP 3 uses 'block' => true to place these within the document <head> tags.
In CakePHP 4:
In your view (es: Articles/view.php) add this:
<?php $this->Html->meta(
'canonical',
Router::url(['controller' => 'Articles', 'action' => 'view', $article->slug], true),
[
'block' => true
]
);
?>
Then you print it in your layout/default.ctp with this instruction
<?= $this->fetch('meta') ?>

Resources