I have done a code, in which i create events. When i create event there was a field named "detailed_address" which i have removed now, from database, from model,from the edit page, from every where.
Creating an event works fine. but when i edit that event and save it, there is error as:
The detailed address field is required.
I have checked my code for at-least 5 times there is no word detailed address now used.
controller methods:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
return redirect('event');
}
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
return view('event.create');
}
Can any one tell what will be my problem?
As #manix suggested, try running php artisan clear-compiled, then i'd suggest running php artisan cache:clear as well just to make doubly sure it's not a cache issue.
Something that could also be worth looking into is your requests folder (app\http\requests), if you weren't validating the input on the controller it was likely being done via requests which might still be checking for input that isn't coming through.
Is the field also still registered as mass assignable on the model?
Can't see why it'd throw a validation error but it's worth making doubly sure it's gone from there too
Related
I'm working on my cakephp project
and I am currently upgrading from 3.3.16 to 3.4.0
The project uses the cakephp-upload plugin to save an image.
The Upload plugin needs an existing entity to attach a file to it. A modification of the request is done to grab the avatar, before unsetting it to save the user.
I know this is not a good practice to modify a request, but the code was made this way.
With immutable objects in version 3.4.0, it is just not possible anymore. But i dont know how to do it properly.
Here is the error message given by my unit-test,
ran by vendor/bin/phpunit --filter testAdd tests/TestCase/Controller/Api/V1/UsersControllerTest.php:
There was 1 failure:
1) App\Test\TestCase\Controller\Api\V1\UsersControllerTest::testAdd
Failed asserting that file "/home/comptoir/Comptoir-srv/webroot/img/files/Users/photo/5/avatar/correctAvatarLogo.jpg" exists.
/home/comptoir/Comptoir-srv/tests/TestCase/Controller/Api/V1/UsersControllerTest.php:208
Here is the actual code:
public function add()
{
if (!empty($this->request->data)) {
$user = $this->Users->newEntity($this->request->data);
} else {
$user = $this->Users->newEntity();
}
$message = "";
// Get the avatar before unset it to save the user.
// The Upload plugin need an existing entity to attach a file to it.
if ($this->request->is('post')) {
if (isset($this->request->data['photo']) && !$user->errors()) {
$avatar = $this->request->data['photo'];
$this->request->data['photo'] = "";
}
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$user = $this->Users->get($user->id, ['contain' => []]);
isset($avatar) ? $this->request->data['photo'] = $avatar : null;
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$message = "Success";
$this->Flash->success(__d("Forms", "Your are registred on the Comptoir du Libre, welcome !"));
if (!$this->request->is('json')) {
$this->Auth->setUser($this->Auth->identify());
$this->redirect([
"prefix" => false,
"controller" => "Pages",
"language" => $this->request->param("language")
]);
}
} else {
$message = "Error";
}
} else {
$message = "Error";
$this->Flash->error(__d("Forms", "Your registration failed, please follow rules in red."));
}
$message == "Error" ? $this->set('errors', $user->errors()) : null;
}
$this->ValidationRules->config('tableRegistry', "Users");
$rules = $this->ValidationRules->get();
$userTypes = $this->Users->UserTypes->find('list', ['limit' => 200]);
$this->set(compact('user', 'userTypes', 'rules', 'message'));
$this->set('_serialize', ['user', 'userTypes', 'rules', 'message', 'errors']);
}
Does anyone know how to do that respecting the immutable rule ?
Your premise is wrong.
The Upload plugin needs an existing entity to attach a file to it
That's actually not correct, uploading files alongside creating new records works fine. There's no need for this stuff in your controller, it should be possible to handle this with a single basic save, ie you should investigate the problem that you're having with that, and fix it.
However looking at your test, it should fail anyways, because the file data that you're passing is invalid, it's neither an actual uploaded file for which is_uploaded_file() would return true, nor is it acceptable for user data to be able to define the temporary file path, and the error code, ie you're not properly validating the data if that test passes as is. Accepting such data is a security vulnerability, it could allow all sorts of attacks, from path traversal to arbitrary file injections!
Ideally your whole upload validation and writing functionality would support \Psr\Http\Message\UploadedFileInterface objects, that would allow for very simply testing by being able to pass instances of that class into the test data, that might be something worth suggesting for the plugin. Without such functionality, your second best bet would probably be something like modifying the table's validation rules before issuing the test request, so that is_uploaded_file() is being skipped, or you're switching to integration tests over HTTP, instead of the simulation in CakePHP.
I use html2pdf, which is based on TCPDF, in CakePhp to render Views in PDF.
However, sometimes the generation hangs, I mean the browser freezes and never receives data.
There is a way to debug such a behavior? In apache logs I do not see any kind of error...
$this->set(compact('quotation','company','user'));
$view = new View(null, false);
$view->set(compact('quotation','company','user'));
$view->viewPath = 'Quotations';
$view->layout = 'preventivo';
if ($quotation['Quotation']['quotation_type'] == SERVICE)
{
$content = $view->render('print_s_template');
$this->set(compact('content'));
$this->response->type('pdf');
$this->render('print');
the print.ctp has
App::import('Vendor', 'HTML2PDF', array('file' => 'html2pdf'.DS.'html2pdf.class.php'));
$html2pdf = new HTML2PDF('P','A4','it');
$html2pdf->WriteHTML($content);
$html2pdf->Output('exemple.pdf');
and the html is in print_s_template.ctp.
I found a solution myself. The problem is that I forgot to pass some variables to the View $view. And I suppose cake throw an error which, next, html2pdf cannot "render".
So: double check that all the variables in the view do exist!
I am trying to retrieve the id of the current user logged in so i can save it to another table. I've been around stack overflow and found a few ways of doing this but nothing seems to work.
This throws the error: Call to a member function user() on a non-object
$this->Auth->user('id');
This returns a null value:
$this->Session->read('User.id');
I played around with this for a bit https://github.com/mcurry/cakephp_static_user but for some reason it complained that I was calling unregistered functions when I know I had implemented them.
I've tried a few variations of the auth and session lines but they all return null or throw an error. Can anyone shed some light on what I might be missing or doing wrong?
Try this:
$loggedInUser = AuthComponent::user();
This gives the whole user array, if you're just after the id then you need this:
$userId = $loggedInUser['User']['id'];
It's what I'm using where I need it, and it works well for me.
It seems like you are not using CakePHP's built-in Auth component.
Your code says:
$components = array('DebugKit.Toolbar', 'Session', 'DataTable', 'RequestHandler', 'Usermgmt.UserAuth')
To include CakePHP's Auth component:
$components = array('...', 'Auth')
I am trying to debug my sql but I am having a hard time. I know I can use this:
<?php echo $this->element('sql_dump'); ?>
to dump the sql but this doesnt (or at least I dont know how to use it) work if I am doing an ajax call. Because the page is not reloaded, the dump does not get refreshed. How can I run my command and debug the sql? Here is the code I have in my controller:
public function saveNewPolicy(){
$this->autoRender = false;
$policyData = $this->request->data["policyData"];
$numRows=0;
$data = array(
'employee_id' => trim($policyData[0]["employeeId"]),
'insurancetype_id'=> $policyData[0]["insuranceTypeId"],
'company' => $policyData[0]["companyName"],
'policynumber' => $policyData[0]["policyNumber"],
'companyphone' => $policyData[0]["companyPhone"],
'startdate'=> $policyData[0]["startDate"],
'enddate'=> $policyData[0]["endDate"],
'note' => $policyData[0]["notes"]
);
try{
$this->Policy->save($data);
$numRows =$this->Policy->getAffectedRows();
if($numRows>0){
$dataId = $this->Policy->getInsertID();
$response =json_encode(array(
'success' => array(
'msg' =>"Successfully Added New Policy.",
'newId' => $dataId
),
));
return $response;
}else{
throw new Exception("Unspecified Error. Data Not Save! ");
}
}catch (Exception $e){
return $this->EncodeError($e);
}
}
The problem is that if the company field in my array is empty, empty, the insert will fail without any error. I know it has failed, though, because of the numrows variable I use. I know the field accepts nulls in the database. It seems like the only way for me to debug this is to look at what SQL is being sent to MySql. Anyone know how to debug it? I am using CakePhp 2.4
I use this approach. I added this method in my AppModel class:
public function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
and then in any controller you call this like:
debug($this->{your model here}->getLastQuery());
Rather than trying to hack around in CakePHP, perhaps it would be easier to just log the queries with MySQL and do a tail -f on the log file? Here's how you can turn that on:
In MySQL, run SHOW VARIABLES; and look for general_log and general_log_file entries
If general_log is OFF, run SET GLOBAL general_log = 'ON'; to turn it on
In a terminal, run a tail -f logfile.log (log file location is in the general_log_file entry) to get a streaming view of the log as it's written to
This is very helpful for these circumstances to see what's going on behind the scenes, or if you have debug off for some reason.
My problem is fairly basic: whenever an action in CakePHP is blackholed, I want to display a custom error page; the default behaviour of Cake to display a "File not found" message confuses the hell out of users (not to mention developers). So I came up with this, by searching the docs and StackOverflow:
class TestsController extends AppController
{
public $components = array ('Security');
public function beforeFilter ()
{
parent::beforeFilter ();
$this->Security->blackHoleCallback = 'blackhole';
$this->Security->csrfExpires = '+5 seconds'; // for testing
}
public function index ()
{
}
public function doit ()
{
$this->log ('Performing request; entry = ' . $this->data['foo'], 'tests');
$this->set ('foo', $this->data['foo']);
}
public function blackhole ($type)
{
$this->log ('Request has been blackholed: ' . $type, 'tests');
$this->render ('/Errors/blackhole');
$this->response->send ();
exit ();
}
}
In index.ctp there is a simple form with a single textbox, that commits to doit (excluded for brevity). This works, but I have one major issue: the exit() in the blackhole() function. The problem is, if I do not exit here doit() is still called, even if the request is blackholed, as evidenced by the log:
2013-01-30 15:37:21 Tests: Request has been blackholed: csrf
2013-01-30 15:37:21 Tests: Performing request; entry = kfkfkfkf
This is clearly not what you expect. The Cake documentation hints at using (custom) exceptions to stop processing in blackhole(), but that:
completely beats the purpose of using a custom handler;
adds another layer of complexity to something that should be simple.
My question is: is there a proper way to do an "exit" from blackhole() so that Cake does all the rendering/cleanup/etc. that it usually does; I already had to add $this->response->send() to force output to the browser. Or, althernatively, a way to tell Cake to skip calling doit() after blackhole().
My suggestion would be to redirect in your blackhole.
This is done e.g. here in the cookbook http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#usage
$this->redirect(array('controller' => 'test', 'action' => 'index'));
A redirect will issue an exit (http://book.cakephp.org/2.0/en/controllers.html#flow-control).
You can also send something nice to the user if you want, before the redirect:
$this->Session->setFlash('What are you doing!?');
In your blackhole callback you could just throw an exception with required message. That would render the proper error page and get logged too (assuming you have turned on logging for errors in core.php).