I am working on a page that can update the sales agent on a specific order.
I made the list of options and a dropdown list is created.
Heres in the controller:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Heres the view:
echo $this->Form->create("Order");
echo $this->Form->input("OrderID");
echo $this->Form->input("UserID");
echo $this->Form->submit("Submit");
echo $this->Form->end();
When I submit the data, it appears that the data is saved, (the flash message is set).
However, when I then preset the fields with data that is already in the database, all the sudden it doesn't even post. (I put a debug after the reques->is("post) condition which doesnt show up after I submit).
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
if (!$this->request->data) {
$this->request->data = $order;
}
The input fields are correctly pre filled, but now the form doesn't even post.
Does anybody know whats wrong?
Thanks!
Update your controller code to:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is('post') || $this->request->is('put')) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Now put a debug after the reques->is('post') condition which will show what you need to show.
Related
I'm using default delete of Yii. And I just want soft delete a row, it's mean I keep that row and update column deleted from 0 to 1.
That my code in Controller:
public function actionDelete($id)
{
$model = $this->loadModel($id);
if (Posts::model()->countByAttributes(['category_id' => $model->id]) == 0) {
$model->deleted = 1;
$model->update();
}
if (!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
}
Now I just want if Post have any category, it will show popup cannot delete this Post.
Any solutions about this?
Ugh... usualy you would add errors in the validator. Honestly that is the best advice... well the Yii way. You could just check if $_POST is set, mass assign $_POST to $model->attributes and then let model worry about validation. What I would do next is write a custom but simple validation function in the model that would check if there are categories for said model and if yes return true, otherwise false. Then you would just do:
if($model->validate())
{
$model->delete = 1;
if($model->update)
{
// do whatever you wanna do redirect/render...
}
else {
Yii::app()->user->setFlash('error', "Unable to delete post");
// render or redirect... flash is more for redirect but it'll do the trick
}
}
This would solve the backend of it. In the view file you need to display this flash. In the view that you render if it's not deleted add this piece of code:
<?php if(Yii::app()->user->hasFlash('error')):?>
<div class="info">
<?php echo Yii::app()->user->getFlash('error'); ?>
</div>
<?php endif; ?>
I would do it this way... you can do whatever you want to do
I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).
I'm trying to modify the below code snippet / function hook to disable registration if the user is logged in.
<?php
add_filter("gform_disable_registration", "disable_registration", 10, 4);
function disable_registration($is_disabled, $form, $entry, $fulfilled){
//check form id and if not the form being checked status passed in to function
if ($form["id"] != 160)
return $is_disabled;
//check submitted values to decide if registration should be stopped
if ($entry["4"] == "No" && $entry["5"] == "No") {
//disable registration
return true;
}
else{
return false;
}
}
?>
I've tried the following to no avail:
add_filter("gform_disable_registration", "disable_registration", 10, 4);
function disable_registration($is_disabled, $form, $fulfilled){
//check form id and if not the form being checked status passed in to function
if ($form["id"] != 2)
return $is_disabled;
//check user login to decide if registration should be stopped
if( ! is_user_logged_in() ) {
return true;
}
else {
return false;
}
}
Hoping I can get this to work! Thank you.
Here is an article/snippet I wrote to do this... I didn't confirm if this is still the best way to accomplish this, but it certainly is a way that works. :)
http://gravitywiz.com/skip-user-registration-for-logged-in-users/
I believe there's a setting in the Form Settings to allow you require users to be logged in. Is there a reason you can't just use that?
I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>
flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}
I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.