How to create a controller from a button id in cakephp 2.x - cakephp-2.0

I am trying to create a controller from a button id in CakePHP.
Here is what I am trying to do:
<button id="initial_pay" class="btn btn-action" onclick="payWithPaystack()">Initial payment - N5,000</button>
public function initial_pay() {
$amount= 55;
$credit = $this->calculateCredit($amount, true);
$uid = $this->Auth->user('id');
$this->CreditBalances->addCredit($uid, floatval($credit));
}
How can I achieve this so that when users click on the button, the action code will be executed?

You can do it like this:
echo $this->Html->link(
'Initial payment - N5,000',
array(
'id' => 'initial_pay',
'class' => 'btn btn-action',
'controller' => 'myController',
'action' => 'initial_pay',
'full_base' => true
)
);
More info: https://book.cakephp.org/2.0/en/core-libraries/helpers/html.html
But if you want the user to click the button and stay in the same page without reloading, you'll need to call mycontroller/initial_pay with ajax.

Related

Create two actions on the same view file in cakephp?

I have a profile page where the url looks like this:
/ClinicalAnnotation/Participants/profile/11
I want to create this /ClinicalAnnotation/Participants/profile/11/submitreview/1
How can I do this with routes?
Also:
On this profile page I have an <a href=""> tag.
<a href="/ClinicalAnnotation/Participants/profile/'.$participantId.'/submitreview/'$medicalRecordReviewId'">Medical Record Review 2 Completed</span>
So I want to create an action in my ParticipantsController.php:
public function submitreview($participantId, $medicalRecordReviewId)
{
echo "Hello";
}
There's also a file called PermissionManagerComponent.php. I have to add the permissions here, something like:
'Controller/ClinicalAnnotation/Participants/submitreview' => 'Controller/ClinicalAnnotation/Participants/profile',
Right now when a User clicks on the a tag, I want to see the word Hello. Then I'll know what I'm trying to do is working.
Attached is a screenshot of the page and the <a href=""> tag (bottom right portion of the screenshot).
You can use custom route elements to form pretty much any URL you want, something along the lines of this:
Router::connect(
'/ClinicalAnnotation/Participants/profile/:participantId/submitreview/:medicalRecordReviewId',
array(
'controller' => 'Participants',
'action' => 'submitreview',
),
array(
// pass route element values to the controller action
'pass' => array(
'participantId',
'medicalRecordReviewId',
),
// restrict route elements to integer values
'participantId' => '[0-9]+',
'medicalRecordReviewId' => '[0-9]+',
)
);
To generate a link in your templates you can then use the helpers, for example:
echo $this->Html->link('Medical Record Review 2 Completed', array(
'prefix' => null,
'plugin' => false,
'controller' => 'Participants',
'action' => 'submitreview',
'participantId' => $participantId,
'medicalRecordReviewId' => $medicalRecordReviewId,
));
See also
Cookbook > Development > Routing > Passing Parameters to Action
Cookbook > Development > Routing > Reverse Routing
Cookbook > Views > Helpers > HtmlHelper > link()

How to perform any action before submit form in cake php

I have a form in cake php Here i have some hidden field that i want to sent when user click on submit button.
At start hidden field value is blank you can see in given form below
I set that hidden field value in playTimer() function in js file
But my prob is when i am going to submit that form it have blank value for actionId hidden field in post data .Wen i again clcik submit then i have value .
I want to set it when user first clcik the submit button so taht i am using before call back function.
echo $this->Form->create('Meditation', array('id' => 'timerform'));
echo $this->Form->hidden('actionId', array('value'=>'', 'id'=>'actionId'));
echo $this->Js->submit('Play', array(
'before' => 'playTimer();',
'update' => '#map_container',
'complete' => 'setsessionid();',
'success' => 'soundPlay();resume();',
'class' => 'btn btn-med-success playTimer',
'div' => false,
'async' => false,
'url' => array('action' => 'timerupdateDuo')
));
==========Custom.js============
function playTimer(){
$("#actionId").val('playTimer');
}
Thanks
<? echo $this->Form->submit(__('Save'), array(
'class' => 'ClassOfTheFormSubmitBTN'
)); ?>
<script type="text/javascript">
$(function(){
$('.ClassOfTheFormSubmitBTN').on('click',function(){
// implement your logic here
$('#MODELNAMEactionId').val('something');
//you can use ajax here with serialize to send the form
//to stop the form from posting return false;
});
});
</script>

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 & Twitter Bootstrap: CSS icons in a button

I'd like to insert a icon of Twitter Bootstrap into this specific button.
The previous mentioned method to add 'escape' => false (here: CakePHP & Twitter Bootstrap CSS button icons) does not work for me.
I tested it succesfully with a simple html-bootstrap-code - but with cakePHP-specific code it does not work.
echo $this->Form->postLink(__('set User'),
array('controller' => 'institutions', 'action' => 'setAssignee', $user['User'] ['institution_id'], $user['User']['id']),
array('class' => 'btn btn-warning icon-plus'),
__('Are you sure?', $user['User']['last_name'], $institution['Institution']['name']));
Won't work, the icon-plus class will be overridden by the background applied to btn.
To get this to work, use an <i> like this:
echo $this->Form->postLink('<i class="icon-plus"></i> ' . __('set User'),
array('controller' => 'institutions', 'action' => 'setAssignee', $user['User'] ['institution_id'], $user['User']['id']),
array('class' => 'btn btn-warning', 'escape'=>false),
__('Are you sure?', $user['User']['last_name'], $institution['Institution']['name']));

How to display name in the url instead id in Cakephp?

I have created an application in cakephp environment,
I am displaying the user profile using user_id in user profile page
I am sending the value to controller using anchor tag like below:
(I can't send the name because it is not unique).
View Profile
Function in User Controller :
function viewprofile($userid){
// my logic
}
the profile url is like this:
http://www.xyz.com/users/12
I want to display the name of user instead user_id
How can we display name(with slug) in url in cakephp
Please help me
echo $this->Html->link('View Profile', array(
'controller' => 'users',
'action'=> 'view',
$result['user']['slug']
));
you have to do 3 things.
Create unique User Slugs (you might have that already ;-) )
Create your links with the code Dave mentioned before
echo $this->Html->link('View Profile', array('controller' => 'users','action'=> 'view',$result['user']['slug']));
tell your routing what to do (/app/condig/routes.php) with it
Router::connect('/user/*', array('controller' => 'users', 'action' => 'view'));
Now you will get pretty urls and the slug will be a parameter that can be used to find the user in your User table
Try this code
echo $this->Html->link('View Profile',array('plugin' => false,
'controller' => 'users',
'action' => 'view',
"slug"=>$data['slug']));
And in your Routes file
Router::connectNamed(array('slug'));
Router::connect('/user/:slug', array(
'plugin' => false,
'controller' => 'users',
'action' => 'view',
),array(
"pass"=>array("slug")
)
);

Resources