Pass in id using the index action - CakePHP 2.1 - cakephp-2.1

I have a controller in my CakePHP app called 'Profiles', and this is what my action called index is:
function index($id = NULL) {
$this->set('profile', $this->Profile->findById($id));
}
So using this method to pass in the id, I can then return the correct profile depending on the id that is in the link.
This works fine when I do this on an action called view, however when I try to do it on the index action it treats my id as if it were an action, and returns an error saying that the action doesn't exist. Is there a way to pass in the id on the index action in CakePHP, or does it have to be on an action besides the index such as a view action?
Cheers,
Adam.

If you want to pass an id to your method you have to visit a url with an id in it.
/profiles/index/<id_here>
Cake will load /profiles as /profiles/index magically. You can not use /profiles/<id> out the box, that would require a new Route before it would work.

If you used the Bake function to create your controller, the Index method would be used to display several records from the Profile model.
Is the three lines of code you displayed in your question the actual code from your controller?

This can be done with a custom route. Pass a parameter to the action...
Router::connect('/mycontroller/:id', array('controller' => 'mycontroller', 'action' => 'index'), array('pass' => array('id') ) );
and in your controller...
public function index( $id )
http://book.cakephp.org/3.0/en/development/routing.html#passing-parameters-to-action

Related

Stumpped trying to pass two parameters from view form to controller

I have a Laravel 6 app and am trying to pass two parameters from my view's form to my controller via a resource route. I can pass one, no problem, but passing two gives the same error:
Too few arguments to function App\Http\Controllers\Admin\SubscriptionsController::update(), 1 passed and exactly 2 expected
I've tried many different arrangements suggested from other posts but none bring the desired result.
Here's my route:
Route::resource('subscriptions', 'Admin\SubscriptionsController')
Here's my form in my view:
{{ Form::open(['route' => ['admin.subscriptions.update', $plan->id, $coupon_code], 'method' => 'PUT', 'id' => 'role-' . $plan->id, $coupon_code]) }}
Coupon Code: <input type="text" name="coupon_code">
{{ Form::close() }}
Here's my controller. It doesn't reach the dd() test.
public function update($id, $coupon_code)
{
dd($coupon_code);
...
In the error Whoops! page, I can see the POST DATA that $coupon_code is being sent over.
However, if I remove the $coupon_code parameter from the controller (leaving public function update($id) ) it functions fine passing $id from form to controller, but I don't get the $coupon_code data I need to process. Adding the second parameter bombs it.
Any suggestions are very welcome.
As you are using the resource controller, it won't allow you to pass additional fields directly to its update() route. Instead, you have to override the update route.
Here is how you can do it, Immediately below your resource.
You can add a new route as below:
// web.php
Route::resource('subscriptions', 'Admin\SubscriptionsController')
// Make sure you add name when you are overriding the route
Route::put('subscriptions/{subscription}/{coupon_code?}', 'Admin\SubscriptionsController#update'])->name('admin.subscriptions.update');
I believe you won't be sending the coupon code every time so you can add {coupon_code?} which becomes optional.
In you controller's update() method, make the coupon_code optional
public function update($id, $coupon_code = null)
{
...
}
You can not add a new param for Route::resource. If you really want to take 2 params, you should create a new route.
for an example:
Route::resource('subscriptions', 'Admin\SubscriptionsController')->except('update');
Route::put('/subscriptions/{id}/{coupon_code}', 'Admin\SubscriptionsController#update')->name('subscriptions.update');
But I think it's better not using method params. Why not just using input form?
so we can process the coupon code like this:
request()->coupon_code;

Yii's CController::forward() can specify parameters to pass to the action?

I want to use CController::forward() instead of redirect or instantiating the controller and directly calling the action, because this way Yii::app()->controller->action->id correctly shows the action that ultimately ran.
Although I don't see in the documentation how to specify parameters to pass to the forwarded action, because the $route parameter is a string, not an array.
public function actionIndex() {
$this->forward('/otherCtrl/view'); // how to pass a parameter here?
otherController.php:
public function actionView( $id ) {
//get the id here
Parameters injected into action method comes from $_GET. So if you need to pass $id into forwarded action, you need to set value in $_GET array:
$_GET['id'] = 'some id';
But using forward() is basically always a sign of bad design of application - I suggest to extract shared logic into separate method/component, and avoid using forward() or calling controller actions directly.
You can try:
$this->forward('/otherCtrl/view/id/'.$id);
Query string depends on your URL settings.

Access RouteMatch-Object in ViewHelper

In my Project, i created a ViewHelper, to display a form on every Page. If the user submit the form the Post information always posted to the same controller. After the Controller handles the post, the user should redirected to the page, where he submitted the form.
To redirect the dynamically i want to submit the controller and action via hidden elements. But i have no clue, how i can set them in the ViewHelper. I tried it with the InjectApplicationEventInterface, but my member variable was empty, so i guess its only work for controllers and not for helper.
So how can i access the RouteMatch Object?
The Zend\View\HelperPluginManager is the service locator that keeps your view helpers, and it contains no instance of the application event initializer, but it has a reference to the main service locator, since it is a plugin manager. Consider implementing following in your helper:
public function __construct(\Zend\Mvc\MvcEvent $mvcEvent)
{
// injecting the mvc event, since $mvcEvent->getRouteMatch() may be null
$this->mvcEvent = $mvcEvent;
}
Then, in your module's getViewHelperConfig (implementation of ViewHelperProviderInterface) you define following:
public function getViewHelperConfig()
{
return array(
'factories' => array(
'myHelper' => function (\Zend\ServiceManager\AbstractPluginManager $pm) {
$application = $pm->getServiceLocator()->get('Application');
return new MyViewHelper($application->getMvcEvent());
},
),
);
}

"Beautifying" a URL in Yii

I want to convert a URL which is of the format
path/to/my/app/Controller_action/id/2
to
path/to/my/app/Controller_action/id/User_corresponding_to_id_2
I have already seen this tutorial from Yii, but it isnt helping me with anything. Can anyone help me with this?
EDIT: I would also like to know if this thing is even possible in the POST scenario, ie I will only have path/to/my/app/Controller_action in the URL.
Add a getUrl method in your User model
public function getUrl()
{
return Yii::app()->createUrl('controller/action', array(
'id'=>$this->id,
'username'=>$this->username,
));
}
Add the following rule urlManager component in config/main.php
'controller/action/<username:.*?>/<id: \d+>'=>'controller/action'
And use the models url virtual attribute everywhere
dInGd0nG is on the correct track, but if I understand correctly you wish to do actions based on the actual username instead of the ID as well right?
It's not that hard in Yii. I'm assuming here for simplicity the controller is user and the action is view.
Your User controller:
public function actionView($id)
{
if (is_numeric($id))
$oUser = User::model()->findByPk($id);
else
// Luckily Yii does parameter binding, wouldn't be such a good idea otherwise :)
$oUser = User::model()->findByAttributes(array('username' => $id));
...
}
Your urlManager config:
'user/view/<id: \w+>' => 'user/view',
Or more generally:
'user/<action: \w+>/<id: \w+> => 'user/<action>',
To generate a user url in a view:
$this->createUrl('user/view', array('id' => $oUser->username));

Codeigniter paypal_lib->ammount from form?

I need to get the quantity of items from a form and pass that to CI's paypal_lib auto_form:
This is my controller:
function auto_form()
{
$this->paypal_lib->add_field('business', 'admin_1261513315_biz#pixelcraftwebdesign.com');
$this->paypal_lib->add_field('return', site_url('home/success'));
$this->paypal_lib->add_field('cancel_return', site_url('home/cancel'));
$this->paypal_lib->add_field('notify_url', site_url('home/ipn')); // <-- IPN url
$this->paypal_lib->add_field('custom', '1234567890'); // <-- Verify return
$this->paypal_lib->add_field('item_name', 'Paypal Test Transaction');
$this->paypal_lib->add_field('item_number', '001');
$this->paypal_lib->add_field('quantity', $quant);
$this->paypal_lib->add_field('amount', '1');
$this->paypal_lib->paypal_auto_form();
}
I have a library of my own that validates the input and redirects to auto_form on validation. I just need to pass the var $quant to the controller.
How can I achieve this?!
If you're redirecting directly to the auto_form controller method you can setup an argument there to pass your data in:
auto_form($quant)
Then, depending assuming you have no routes, rewriting, or querystrings 'on' (basically a stock CI setup) to interfere, and you are using the URL helper to redirect, you would do your redirect something like this:
redirect('/index.php/your_controller/auto_form/'. $quantity_from_form);
More on passing URI segments to your functions here.
Or if you're already using CI sessions in your application you can add the quantity value to a session variable for later retrieval inside of the auto_form controller method:
// Set After Your Form Passed Validation
$this->session->set_userdata('quant', $quantity_from_form);
// Retrieve Later in Controller Method After Redirect
$this->paypal_lib->add_field('quantity', $this->session->userdata('item'));
More on CI sessions here.

Resources