PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label controller. Show all posts
Showing posts with label controller. Show all posts

Sunday, December 4, 2022

[FIXED] How to make file .json with codeigniter?

 December 04, 2022     codeigniter, controller, json, jsonencoder, php     No comments   

Issue

This is my json encode in my controller:

public function loaddata(){
    $sql = $this->db->query('select * from e_alat_angkutan')->result();

    return json_encode($sql);

}

how to make file .json ? please help


Solution

In the controller __construct() method load the file helper:

public function __construct()
{
    parent::__construct();
    $this->load->helper('file');
}

And then echo it with second param to TRUE:

public function loaddata(){
    $sql = $this->db->query('select * from e_alat_angkutan')->result();

    echo json_encode($sql,TRUE);
}

As points this answer Write to JSON file using CodeIgniter:

//If the json is correct, you can then write the file and load the view

// $fp = fopen('./data.json', 'w');
// fwrite($fp, json_encode($sql));

// if ( ! write_file('./data.json', $arr))
// {
//     echo 'Unable to write the file';
// }
// else
// {
//     echo 'file written';
// }   

Hope it helps!



Answered By - JP. Aulet
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 18, 2022

[FIXED] How can I lead users to new route instead the current route in my controller ? Symfony

 October 18, 2022     controller, symfony     No comments   

Issue

I'd like to lead users to a new route when he has submitted the search form. The new route will be named "events". In order to get all data that I need, I let him to stay on search. At the moment, it's the only way I have found to pass the two selections the user has made from search and events saved in database.

Thank you very much for help.

I am willing to share more about my code or show to you what I've tried.

<?php

namespace App\Controller\Front;

use App\Entity\Events;
use App\Entity\BigCity;
use App\Entity\Country;
use App\Entity\Language;
use App\Form\SearchType;
use App\Repository\EventsRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{
    #[Route('/search', name: 'search')]
    public function search(
        Request $request, 
        SessionInterface $sessionInterface,
        EventsRepository $eventsRepository,
    ){   
        $data = $request->request->all();
        $sessionSearchFormData  = $sessionInterface->get('searchFormData');

        $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $data = $form->getData();
            $sessionInterface->set('searchFormData', $data);
            
            $events = $eventsRepository->findAll();
            
            return $this->render("front/events.html.twig", [
                'bigcity'=> $form->get('bigcity')->getData()->getId(), 
                'category'=> $form->get('category')->getData()->getId(), 
                'events' => $events
            ]);

        }
        return $this->renderForm('front/search.html.twig', [ 
            'form' => $form,
        ]);
    }

    #[Route('/events', name: 'events')]
    public function events(
        Request $request, 
        EventsRepository $eventsRepository, 
        CategoriesRepository $categoriesRepository, 
        BigCityRepository $bigCityRepository
    ){
        $events = $eventsRepository->findAll();

        $category = $categoriesRepository->find($request->query->get('category'));
        $bigcity = $bigCityRepository->find($request->query->get('bigCity'));

        return $this->render("front/events.html.twig", [
            'events' => $events,
            'category' => $category,
            'bigcity' => $bigcity
        ]);
    }
}

Solution

The last time we have forget getId() here

'category'=> $form->get('category')->getData()
'bigcity'=> $form->get('bigcity')->getData()

and that's why you was redirect to localhost:8888/gozpeak/public/events? without any parameter

Now it should be like this

$queryStringParameters = http_build_query([
    'category'=> $form->get('category')->getData()->getId(),
    'bigcity'=> $form->get('bigcity')->getData()->getId()
 ]);

So based on your code this should works fine , tested on local. Just copy and paste the two functions in place of others if it works, you can edit them as you like later

#[Route('/search', name: 'search')]
public function search(Request $request, SessionInterface $sessionInterface)
{
    $sessionSearchFormData = $sessionInterface->get('searchFormData');

    $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $data = $form->getData();
        $sessionInterface->set('searchFormData', $data);

        $queryStringParameters = http_build_query([
            'category'=> $form->get('category')->getData()->getId(),
            'bigcity'=> $form->get('bigcity')->getData()->getId()
        ]);

        $url = $this->generateUrl("events").'?'.$queryStringParameters;

        return $this->redirect($url);

    }
    return $this->render('front/search.html.twig', [
        'form' => $form->createView()
    ]);
}

#[Route('/events', name: 'events')]
public function events(Request $request, EventsRepository $eventsRepository, CategoriesRepository $categoriesRepository, BigCityRepository $bigCityRepository)
{
    $events = $eventsRepository->findAll();
    $categories = $categoriesRepository->findAll();

    $category = null;
    $bigcity = null;

    if ($request->query->has('category')) {
        $categoryId = $request->query->get('category');
        $category = $categoriesRepository->find($categoryId);
    }
    if ($request->query->has('bigCity')) {
        $bigCityId = $request->query->get('bigCity');
        $bigcity = $bigCityRepository->find($bigCityId);
    }


    return $this->render("front/events.html.twig", [
        'events' => $events,
        'categories' => $categories,
        'category' => $category,
        'bigcity' => $bigcity
    ]);
}


Answered By - hous
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 3, 2022

[FIXED] How to use multiple payment gateways function in single controller in laravel 8?

 July 03, 2022     controller, laravel, laravel-8, payment-gateway, paypal     No comments   

Issue

I am using PayPal, Razor pay, Stripe payment gateways in my project. When select user one of them payment gateway it redirects to assigned controller function from there it redirects its particular controller. I want to write all the functions for payment gateways in single controller to cut off redirections for customer.

enter image description here

when user select payment gateway and submit the form it redirects to mentioned below controller function

 if ($payment_mode->payment_gateway_name == "Paypal") {
                return redirect()->route('paywithpaypal', $planId);
            } else if ($payment_mode->payment_gateway_name == "Razorpay") {
                return redirect()->route('paywithrazorpay', $planId);
            } else if ($payment_mode->payment_gateway_name == "Stripe") {
                return redirect()->route('paywithstripe', $planId);
            } else if ($payment_mode->payment_gateway_name == "Bank Transfer") {
    }

and in that controller all functions is defined.


Solution

Create Classes as below:

  1. PaymentController
  2. Seperate classes implementing RazorpayService, StripeService, BankTransferService apis
  3. Factory Method to create class object of RazorpayService, StripeService, BankTransferService based on request parameters

PaymentController uses factory method to create object of appropriate service and calls appropriate method on this object using input parameters



Answered By - pks11
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, May 18, 2022

[FIXED] How to render different versions of the same file?

 May 18, 2022     controller, if-statement, partial, ruby, ruby-on-rails     No comments   

Issue

For example I have this file:

_goal.html.erb

<table>
  <tr>
    <%= goal.name %>
    <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
  </tr>
</table>

It is being rendered from the home page:

 <h1><b>Goals</b></h1>
   <%= render @unaccomplished_goals %>
   <%= render @accomplished_goals %>
<% end %> 

How can we wrap an accomplished goal with <span class="label label-info-success"> but if it is an unaccomplished goal keep it <span class="label label-info">?

In the controller:

@accomplished_goals = current_user.goals.accomplished
@unaccomplished_goals = current_user.goals.unaccomplished

Here was my latest attempt, which just made them all -info:

<% if @unaccomplished_goals == true %>
  <span class="label label-info"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% else @accomplished_goals == true %>
  <span class="label label-warning"><%= goal.deadline.strftime("%d %b %Y") %></span>
<% end %>

Maybe you'll have more luck :)

Thank you so much.


Solution

Create a helper method that returns the correct classes for the goal's status. In application_helper.rb:

def deadline_label_class(goal)
  if goal.accomplished?
    'label label-info'
  else
    'label label-warning'
  end
end

This assumes that Goal has an instance method called accomplished? which returns true/false. You may have to write that method if it doesn't exist or use some other criteria.

Then use the helper in the _goal.html.erb template:

<table>
  <tr>
    <%= goal.name %>
    <span class="<%= deadline_label_class(goal) %>">
      <%= goal.deadline.strftime("%d %b %Y") %>
    </span>
  </tr>
</table>


Answered By - infused
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use ASP.Net MVC Child Actions with VS 2017 C# and MVC 5

 May 18, 2022     action, controller, model-view-controller, partial, views     No comments   

Issue

I have a scenario but do not know if it is possible to do this with child actions.

I do not have any code to show. Basically, there would be a simple list on the left side of a view containing summary data. On each line of the list there would also be a 'view details' link or button. So, I want the user to click that link/button, and then on the right side I want more details about the particular selected item to be displayed. The user could then click on the view details for another item and view those details etc.

How is this best achieved in ASP.Net MVC?

Thanks in advance.


Solution

This is an example for the OP, this may or may not be the best way, but it will work:

So your left panel has buttons or links, if the text of your button/link is enough to pull back the relevant data from the server, just pass that to the server via Ajax, else if you wanted to use ids or some unique identifier, you could append that to the id property of your buttons/links and then pass that to the server, I will let you decide which you want to use:

//Example HTML
<div id="panelLeft">
   <button id="btnOne" class="btnInfo">Info on Cats</button>
   <br/>
   <button id="btnTwo" class="btnInfo">Info on Dogs</button>
</div>

//Assuming you are using JQuery
//Either in your page add a script tag with this code, or add a script file
//to your project and import it into your page (View)
$(function(){
      //Add click events to all your buttons by using the common className btnInfo
      $('.btnInfo').on('click', function(){
            const serverSideData = $(this).text(); //If you are using the text
            //of the button to find the info server side
            $.ajax({
                  url: "yourUrlToServerSideMethod",
                  type: "POST",
                  data: { yourServerSideParameter: serverSideData },
                  success: function(data){
                      //Successfully posted to server and got response
                      //If data is in JSON format, you can parse it with JSON.parse()

                      //Clear your div on the right which displays the item data
                      $('#divRightPanelInfo).html('');
                      $('#divRightPanelInfo).append(data); //If this is just a string
                      //Or create some pretty element(s) and append that to div

                  },
                  error: function(jqXHR, exception){
                      //Handle error, show error label or something
                  }
              });
       });
 });


Answered By - Ryan Wilson
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, May 12, 2022

[FIXED] How to bind a custom route to a method of a controller via yaml without triggering an automatic query from api-platform and symfony?

 May 12, 2022     api-platform.com, controller, php, symfony     No comments   

Issue

  • I have a simple symfony project base on api-platform.
  • I have an entity named "MyEntity".
  • I have a ressource yaml config file to tell api-platform how my entity to be query via api call .
  • In the yaml, I added a route named exportcsv exposed as export, it will be called by my front with this url : http://127.0.0.1:8000/api/myentitys/export.
  • This route is mapped to call the export method from MyEntity controller.
  • In MyEntity controller I have a method named export and I will do nothing except dumping a sentence then die ( dd('why?!'); ).

Expected behavior:

  • call the export url
  • Nothing should be done on the server/database, and the front will just receive a dump of the string why?!

Actual behavior:

  • call the export url
  • execute a query on the table'db named myentity
  • then receive a dump of the string why?!

I discovered the query when I added data to my table. Performance went longer and longer as I added more data on the table. I would never reach the Why?! at some point. I checked my database, and saw that a select all on the myentity table were active. I searched a bit on the documentation, the only thing I could find is :

pagination_partial: true

When adding this in the yaml, to the export route, it will still execute a query, but as it now paginated, it will take way less time.


My question is:

How to totatlly remove this query at all ?


In Controller/MyEntityController.php :

        namespace App\Controller;
        
        use App\Entity\MyEntity;
        use Doctrine\ORM\EntityManagerInterface;
        use Exception;
        // use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
        use Symfony\Component\Translation\Exception\NotFoundResourceException;
        use Symfony\Bundle\FrameworkBundle\Console\Application;
        use Symfony\Component\Console\Input\ArrayInput;
        use Symfony\Component\Console\Output\NullOutput;
        use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
        use Symfony\Component\HttpFoundation\File\UploadedFile;
        use Symfony\Component\HttpFoundation\Request;
        use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
        use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
        use Symfony\Component\HttpKernel\KernelInterface;

        class MyEntityController// extends AbstractController
        {
    
        private ParameterBagInterface $params;
        private EntityManagerInterface $entityManager;
    
        public function __construct(ParameterBagInterface $params, EntityManagerInterface $entityManager)
        {
            $this->params = $params;
            $this->entityManager = $entityManager;
        }
    
        public function export(KernelInterface $kernel): array
        {
            dd("why?!");
    }
// ...
}

In ressource/entity.yaml :

resources:
  App\Entity\MyEntity:
    shortName: ~
    description: ~
    attributes:
      order:
        referenceCafHuissier: asc
        montantEcheance: asc

      # security: 'is_granted("ROLE_USER")'
      normalization_context:
        groups: ['myentity:read']
      denormalization_context:
        groups: ['myentity:write']
    properties:
    ...
    collectionOperations:
    ...
      exportcsv:
        security: 'is_granted("ROLE_MYENTITY_ADMIN")'
        # pagination_partial: true
        method: 'GET'
        path: '/myentity/export'
        controller: 'App\Controller\MyEntityController::export'
        openapi_context:
          summary: Export CSV
          parameters: []
          responses:
            '200':
              description: Génération réussi de l'export CSV
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      type:
                        type: string
                        description: mime-type du fichier.
                      content:
                        type: string
                        description: Base64 du contenu du fichier.

Solution

The query you're talking about is most likely made by the ReadListener.

To disable it, set the read property to false, as explained here :

collectionOperations:
    exportcsv:
        method: get
        path: /pensions/export
        # ...
        read: false    


Answered By - rugolinifr
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, April 22, 2022

[FIXED] How don't break MVC and DRY, sharing a method (Helper/Controller)

 April 22, 2022     cakephp, cakephp-2.3, controller, helper, php     No comments   

Issue

First question on StackOverflow (I don't know if I'm doing this right, so sorry if I mess it up)

Background: My controller has a method that list all actions in my app and plugins called getActions().

And I need to use getActions() in a Helper that overrides HtmlHelper->link() method, because the purpose of this method is return null if the link is forbidden by Acl, thus not rendering any link that would lead to a forbidden action.

Question How to share this method? I'm doing this wrong?

Lib is the right way to go?

This doesn't seem right: In CakePHP, how do I call an AppController method from a helper?


Solution

The right place for the method is Lib, because its a general purpose method that is going to be used in differents places with differents objectives.

CakePHP's core has many examples of this approach like: CakeTime, CakeNumber and others.

Others examples could be seen in some of CakeDC plugins too.

IMHO @yossi was right about "assuming the data as static", but his approach of storing the data in Session just would make my code more confusing.

In my particular case I'm taking the Lib way. Thanks for the help.



Answered By - gpedote
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] How to do math operations in the Controller and then display them in blade

 April 19, 2022     controller, laravel, laravel-blade, math     No comments   

Issue

I am at a low level of Laravel and PHP advancement. All my knowledge is based on YouTube tutorials, Laravel documentation and online forums.

To deepen my knowledge, I decided to create an application project that would calculate the price based on constant values ​​and variables (entered by the user). The constants are in one table, they are put in there by me and cannot be changed. Variable values ​​are entered by the user.

At the moment, I managed to make a connection to the database (full CRUD), however, I cannot cope with the formula for calculating many records from two tables. I don't know how to perform math calculations in Controller and then display them in Blade.

I do not expect ready code, but only advice on what method to use or whether I made a mistake while creating the tables. I am asking for help and thank you to those who made it to the end of this post.

The first table with constant values ​​looks like this: constant_costs

id cost_name amount_of_cost
1 Tax_01 1.36
2 Tax_02 0.15
3 Tax_03 0.08
4 Transport 0.37
5 Margin_01 0.26
6 Margin_02 0.10

The second table, the value of which is added by the user by the form (I entered some sample numbers below): stuff

id value_01 value_02 value_03
1 100 4 20

The formula for the price is a bit complicated: (((value_01 / 159 + Margin_01) * value_02) + Tax_01 + Tax_02 + Tax_03 + Transport + Margin_02) * value_03

When I put the accessor in the Model, I get an error: BadMethodCallException Method Illuminate \ Database \ Eloquent \ Collection :: getFormulaCalculation does not exist.

In my Model
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class stuff extends Model
{
    use HasFactory;

    protected $primaryKey = 'id';

    public $timestamps = FALSE;

    protected $fillable = ['value_01', 'value_02', 'value_03'];

    /**
     * Price formula
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    public function getFormulaCalculationAttribute(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => (($this->value_01 / 159 + 0.26) * $this->value_02) + 1.369 + 0.15261 + 0.08 + 0.37 + 0.1 * $this->value_03);
    }
}

In my Controller
use Illuminate\Http\Request;
use App\Models\stuff;

public function result()
    {
        public function result()
    {
        $stuff = stuff::all();
        $getFormulaCalculationAttribute = $stuff->getFormulaCalculation();

        return view('stuff.result')->with('getFormulaCalculationAttribute', $getFormulaCalculationAttribute);
    }
    }

Solution

I didn't get the idea from creating a table for constant values, there is a simple solution to create this calculation in your Eloquent model.

you can create an Accessor for your formula something like this

public function getFormulaCalculationAttribute()
{
    return ((($this->value_01 / 159 + Margin_01) * $this->value_02) + Tax_01 + Tax_02 + Tax_03 + Transport + Margin_02) * $this->value_03;
}

just replace the constant with your values

after that, you can call this attribute like this

echo $value->formula_calculation;

please pay attention to your laravel version starting from laravel 9 defining an accessor is different https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

or for laravel 9

https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor

I hope it's helpful



Answered By - Ahmed Hassan
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 18, 2022

[FIXED] Laravel Controller update model from different users

 March 18, 2022     controller, laravel, laravel-5, php     No comments   

Issue

In my Laravel application, I have a Model called Project which has, among others, a property called approved_at. There is also a ProjectController, which contains the usual methods *(index, show, create, update, edit...)

Now, the user that created the Project can edit it (modifying its other attributes), but only some "staff" members have the right to approve one.

From what I understand, there can be two ways to handle the approval operation:

  1. Both users, from their respective views (let's call them edit and approve) fire the ProjectController@update method, which will internally distinguish who-can-do-what by means of authorization or policies;
  2. I create a new ProjectApprovalController, with its own update method, and check the authorization at the endpoint (eg, /projects/{id}/approve).

What is the best approach to tackle this behaviour?


Solution

It depends on what do you want to do with this in the future. If there would be some kind of extra steps to do behind the approve method for example: connection to external micro service to check if project exists in external database with subsidies then you should definitely split it.

If you don’t mind I would suggest you to not focus so much on the implementation. Your application should be removable as fast as you build it. There is a great presentation about this from Greg Young called ‘The Art of Destroying Software’. Be more focus to build your solution with SOLID principles and test the behaviour of this method to make it easier to replace in the future.

to answer your question, second option is more restful approach, but I don’t know if that is not shooting to fly with a cannon



Answered By - Kacper Majczak
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Get current action in CakePHP 3

 March 18, 2022     cakephp, cakephp-3.0, controller, php     No comments   

Issue

In CakePHP 2 I could get the current action by using $this->action, but in CakePHP 3.x I can't use this anymore, as it returns the following error:

Error: actionHelper could not be found.

How do I get the current action in CakePHP 3?


Solution

$this->request->actionOR $this->request->params['action'] both works.



Answered By - Danilo Azevedo
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] How to login a user from the Controller in cakephp4? Using the authentication plugin

 March 11, 2022     authentication, cakephp, controller     No comments   

Issue

I build a application, that has a normal login with the Authentication plugin, and other form of login that happens in the controller. In cakephp3 we can do that with $this->Auth()->login , $this->Auth()->setUser, etc. But in cakephp4 the Authentication plugin doesn't have a $this->Authentication->login/setUser. The questions is how do i do that?.

I obtaing the user in the controller and i don't have any way to login that user.

I'm wondering if any of you have encounter this problem

This is my authentication service:

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
        $service = new AuthenticationService();

        // Define where users should be redirected to when they are not authenticated
        $service->setConfig([
            'unauthenticatedRedirect' => Router::url([
                'prefix' => false,
                'plugin' => null,
                'controller' => 'Users',
                'action' => 'login',
            ]),
            'queryParam' => 'redirect',
        ]);

        $fields = [
            IdentifierInterface::CREDENTIAL_USERNAME => 'email',
            IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
        ];
        // Load the authenticators. Session should be first.
        $service->loadAuthenticator('Authentication.Session');
        if ($request->getParam('action') == 'googleLogin') {
            $service->loadAuthenticator('Authentication.Form', [
                'fields' => $fields,
                'loginUrl' => Router::url([
                    'prefix' => false,
                    'plugin' => null,
                    'controller' => 'Users',
                    'action' => 'googleLogin',
                ]),
            ]);
        } else {
            $service->loadAuthenticator('Authentication.Form', [
                'fields' => $fields,
                'loginUrl' => Router::url([
                    'prefix' => false,
                    'plugin' => null,
                    'controller' => 'Users',
                    'action' => 'login',
                ]),
            ]);
        }
        // Load identifiers
        $service->loadIdentifier('Authentication.Password', compact('fields'));

        return $service;
    }

and this is the controller

$this->Authorization->skipAuthorization();

        $data = $this->request->getData();
        $email = $data['email'];

        $repository = new UserRepository($this->Users);
        $user = $repository->findUserByEmail($email);

        $response = $this->response;

        if (!empty($user)) {
            $response->withStatus(201);
            return $response;
        } else {
            $user = $this->Users->newEmptyEntity();
            $dataUser['username'] = $email;
            $dataUser['email'] = $email;
            $dataUser['password'] = 'esquemaPerfecto';
            $dataUser['role'] = 'cliente';
            $user = $this->Users->patchEntity($user, $dataUser);
            if ($this->Users->save($user)) {
                $this->Authentication->setUser($user);
                $sendEmail = new EmailHelper($dataUser['email'], 'Vehiculos de Primera mano Registro', 'Usted se ha registrado con exito en la pagina de Vehiculos de Primera Mano y su contraseña es ' . $dataUser['passwords']);
                $sendEmail->send();

                $response->withStatus(200);
                return $response;
            }
        }

        $response->withStatus(400);
        return $response;
    }

All ideas are welcome


Solution

According to Migration from the AuthComponent docs section

Any place you were calling AuthComponent::setUser(), you should now use setIdentity():

// Assume you need to read a user by access token
$user = $this->Users->find('byToken', ['token' => $token])->first();

// Persist the user into configured authenticators.
$this->Authentication->setIdentity($user);


Answered By - Yaroslav
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 9, 2022

[FIXED] cakephp 3 Allow user to edit only their profile

 March 09, 2022     cakephp, cakephp-3.0, controller, php, roles     No comments   

Issue

I am making a app with cakephp 3, my user have two roles, admin and student. The admin can access everything and the student just his profile. I done this part already, but i do not know how to restrict the students just to see his profiles and not all the profiles. for example, if i logged with user 3 this is the url http://localhost:8765/users/view/4 to see the profile of user 4, but if a change the 4 with a 3, i can see the profile of user 3. how i can fix this?

AppController.php

class AppController extends Controller
{


    public function initialize()
    {
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'loginRedirect' => [
                'controller' => 'Users',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);
    }

    public function beforeFilter(Event $event)
    {
        $this->Auth->allow(['login']);
    }

    public function isAuthorized($user)
    {
    // Admin can access every action
        if (isset($user['rol']) && $user['rol'] === 'admin') {
            return true;
       }
    // Default deny
       return false;
    }
}

UserController.php

class UsersController extends AppController
{

/**
 * Index method
 *
 * @return void
 */
public function index()
{
    $this->paginate = [
        'contain' => ['Grados']
    ];
    $this->set('users', $this->paginate($this->Users));
    $this->set('_serialize', ['users']);
}

/**
 * View method
 *
 * @param string|null $id User id.
 * @return void
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function view($id = null)
{
    $user = $this->Users->get($id, [
        'contain' => ['Grados', 'Clases', 'ConveniosUsuarios', 'Desvinculaciones', 'HistorialAlumnos', 'Pagos', 'Pedidos']
    ]);
    $this->set('user', $user);
    $this->set('_serialize', ['user']);
}

/**
 * Add method
 *
 * @return void Redirects on successful add, renders view otherwise.
 */
public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->data);

        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
    }
    $grados = $this->Users->Grados->find('list', ['limit' => 200]);
    $this->set(compact('user', 'grados'));
    $this->set('_serialize', ['user']);
}

/**
 * Edit method
 *
 * @param string|null $id User id.
 * @return void Redirects on successful edit, renders view otherwise.
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function edit($id = null)
{
    $user = $this->Users->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        $filename = WWW_ROOT.'files'.DS.'images'.DS.$this->request->data['id'].$this->request->data['foto']['name'];
        move_uploaded_file($this->request->data['foto']['tmp_name'],$filename);
        $user->set('foto',$filename);
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
    }
    $grados = $this->Users->Grados->find('list', ['limit' => 200]);
    $this->set(compact('user', 'grados'));
    $this->set('_serialize', ['user']);
}

/**
 * Delete method
 *
 * @param string|null $id User id.
 * @return void Redirects to index.
 * @throws \Cake\Network\Exception\NotFoundException When record not found.
 */
public function delete($id = null)
{
    $this->request->allowMethod(['post', 'delete']);
    $user = $this->Users->get($id);
    if ($this->Users->delete($user)) {
        $this->Flash->success(__('The user has been deleted.'));
    } else {
        $this->Flash->error(__('The user could not be deleted. Please, try again.'));
    }
    return $this->redirect(['action' => 'index']);
}

public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    // Allow users to register and logout.
    // You should not add the "login" action to allow list. Doing so would
    // cause problems with normal functioning of AuthComponent.
    $this->Auth->allow(['logout']);
}

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {
            $this->Auth->setUser($user);
            if ($this->Auth->user('rol') == 'Alumno') {
                $this->redirect('users'.DS.'view'.DS.$this->Auth->user('id'));
            }else{
                return $this->redirect($this->Auth->redirectUrl());
            }
        }else{
            $this->Flash->error(__('Usario o contraseña invalidos!'));    
        }
    }
}

public function logout()
{
    return $this->redirect($this->Auth->logout());
}

public function isAuthorized($user)
{
    $userid=$this->Auth->user('id');
    $action = $this->request->params['action'];
    if ($user['rol']=='Admin') {
        return true;
    }else if ($user['rol']!='Admin') {
        if (in_array($action, ['edit', 'view'])) {
            return true;
        }
        return false;
    }
    return parent::isAuthorized($user);
}
}

debug($this->request)

object(Cake\Network\Request) {
params => [
    'plugin' => null,
    'controller' => 'Users',
    'action' => 'view',
    '_ext' => null,
    'pass' => [
        (int) 0 => '4'
    ]
]
data => []
query => []
cookies => [
    'CAKEPHP' => 't8o6augt5qd0a8p3squq4kmni2'
]
url => 'users/view/4'
base => ''
webroot => '/'
here => '/users/view/4'
trustProxy => false
[protected] _environment => [
    'DOCUMENT_ROOT' => 'C:\xampp\htdocs\intranet\webroot',
    'REMOTE_ADDR' => '::1',
    'REMOTE_PORT' => '50389',
    'SERVER_SOFTWARE' => 'PHP 5.6.8 Development Server',
    'SERVER_PROTOCOL' => 'HTTP/1.1',
    'SERVER_NAME' => 'localhost',
    'SERVER_PORT' => '8765',
    'REQUEST_URI' => '/users/view/4',
    'REQUEST_METHOD' => 'GET',
    'SCRIPT_NAME' => '/index.php',
    'SCRIPT_FILENAME' => 'C:\xampp\htdocs\intranet\webroot\index.php',
    'PATH_INFO' => '/users/view/4',
    'PHP_SELF' => '/index.php',
    'HTTP_HOST' => 'localhost:8765',
    'HTTP_CONNECTION' => 'keep-alive',
    'HTTP_CACHE_CONTROL' => 'max-age=0',
    'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36',
    'HTTP_ACCEPT_ENCODING' => 'gzip, deflate, sdch',
    'HTTP_ACCEPT_LANGUAGE' => 'es-ES,es;q=0.8,en;q=0.6',
    'HTTP_COOKIE' => 'CAKEPHP=t8o6augt5qd0a8p3squq4kmni2',
    'REQUEST_TIME_FLOAT' => (float) 1437761676.7461,
    'REQUEST_TIME' => (int) 1437761676,
    'HTTP_X_HTTP_METHOD_OVERRIDE' => null,
    'ORIGINAL_REQUEST_METHOD' => 'GET',
    'HTTPS' => false
]
[protected] _detectors => [
    'get' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'GET'
    ],
    'post' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'POST'
    ],
    'put' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'PUT'
    ],
    'patch' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'PATCH'
    ],
    'delete' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'DELETE'
    ],
    'head' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'HEAD'
    ],
    'options' => [
        'env' => 'REQUEST_METHOD',
        'value' => 'OPTIONS'
    ],
    'ssl' => [
        'env' => 'HTTPS',
        'options' => [
            (int) 0 => (int) 1,
            (int) 1 => 'on'
        ]
    ],
    'ajax' => [
        'env' => 'HTTP_X_REQUESTED_WITH',
        'value' => 'XMLHttpRequest'
    ],
    'flash' => [
        'env' => 'HTTP_USER_AGENT',
        'pattern' => '/^(Shockwave|Adobe) Flash/'
    ],
    'requested' => [
        'param' => 'requested',
        'value' => (int) 1
    ],
    'json' => [
        'accept' => [
            (int) 0 => 'application/json'
        ],
        'param' => '_ext',
        'value' => 'json'
    ],
    'xml' => [
        'accept' => [
            (int) 0 => 'application/xml',
            (int) 1 => 'text/xml'
        ],
        'param' => '_ext',
        'value' => 'xml'
    ],
    'mobile' => object(Closure) {

    },
    'tablet' => object(Closure) {

    }
]
[protected] _detectorCache => []
[protected] _input => ''
[protected] _session => object(Cake\Network\Session) {
    [protected] _engine => null
    [protected] _started => true
    [protected] _lifetime => '1440'
    [protected] _isCLI => false
}
}

Solution

I finnaly solve the problem, with this plugin: https://github.com/AlessandroMinoccheri/UserPermissions



Answered By - Luis Martinez
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 8, 2022

[FIXED] Yii url manager only ID in url

 March 08, 2022     controller, url, url-rewriting, yii     No comments   

Issue

i have in YII for example domain: www.example.com/product-url-1234

how to set rules in urlManager and how to use controller/action/id


Solution

If you want to use this url www.example.eu/product-url-1234

and suppose 'index' is the name of the action of the 'user' controller that will handle the request

Then create a rule like

'<id:.*?>'=>'user/index'

Now if you will use Yii::app()->createUrl('user/index',array('id'=>'product-url-1234'))

then it will give you the desired result.

And if you Visit this Url, User/Index will handle the request.



Answered By - Let me see
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, March 6, 2022

[FIXED] Yii2, optional parameter in the rounte

 March 06, 2022     controller, rules, yii, yii-url-manager, yii2     No comments   

Issue

During the development, I have faced to the one issue with urlManager.

I have SiteController with "category" action.

public function actionCategory($id = null, $city = null, $location = null)
{
   echo $id;
   echo $city;
   echo $location;
}

All possible combination that can be used with this action:

id, city, location = null
id, city = null, location
id, city = null, location = null
id = null, city = null, location = null
id = null, city = null, location

I do not know how to write the rules in the UrlManager, after that I will get the following values in the variables after press the links:

<h4><?= Html::a('ID City', ['/site/category', 'id' => 'barbershop', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:

id = 'barbershop'
city = 'Praha'
location = ''

<h4><?= Html::a('ID Location', ['/site/category', 'id' => 'barbershop', 'location' => '23,65'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:

id = 'barbershop'
city = ''
location = '23,65'

<h4><?= Html::a('ID', ['/site/category', 'id' => 'barbershop'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:

id = 'barbershop'
city = ''
location = ''

<h4><?= Html::a('City', ['/site/category', 'city' => 'Praha'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:

id = ''
city = 'Praha'
location = ''

<h4><?= Html::a('Location', ['/site/category', 'location' => '14,23'], ['class' => 'btn btn-primary']) ?></h4>
The return value from "category" action:

id = ''
city = ''
location = '14,23'

Would you like you help me with this issue?


Solution

As per your requirements you need to set rules only for Controller and action name. All other fields are passed through $_GET. and you can fetch them using Yii::$app->getRequest()->getQueryParam('param') method.

For you url you can use normal rules for pretty url like

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ],
    ],


Answered By - Ninja Turtle
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 4, 2022

[FIXED] searchbox in codeigniter giving blank data

 March 04, 2022     codeigniter, controller, model, mysql, php     No comments   

Issue

i have a simple searchbox in codeigniter, the controller is like below:

function searchtrack() {
    $this->load->model('excel_import_model');
    if(isset($_POST['submittrack'])) {
        $awb=$this->input->post('awb');
        $data['slt']= $this->excel_import_model->searchtrack($awb);
        $this->load->view("searchtrack",$data);
    }
}
}

the model is like below:

public function searchtrack($awbno) {
    $this->db->select('*');
    $this->db->where("awb", $awbno);
    $this->db->from('consignments');
    $query = $this->db->get();
    $result = $query->result();
    return $result;
}

and finally the display view:

<?php
  foreach($slt as $val){ echo $val->id; }
?>

however this not giving me any values, the post input is getting passed to the controller and the database column and all is fine, can anyone please tell me what is wrong in here thanks in advance


Solution

In your model, replace "where" with "like". "Where" look for specific data where "like" look for similar data.

public function searchtrack($awbno) {
    $this->db->select('*');
    $this->db->like("awb", $awbno, 'both');
    $this->db->from('consignments');
    $query = $this->db->get();
    $result = $query->result();
    return $result;
}

To control where the wildcard (%) placing in "like" method, a third parameter is used.

$this->db->like('awb', $awbno, 'before');    // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
$this->db->like('awb', $awbno, 'after');     // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
$this->db->like('awb', $awbno, 'none');      // Produces: WHERE `title` LIKE 'match' ESCAPE '!'
$this->db->like('awb', $awbno, 'both');      // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'


Answered By - mail2bapi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 1, 2022

[FIXED] concatenate 2 arrays obtained from loop in php

 March 01, 2022     arrays, codeigniter, controller, object, php     No comments   

Issue

can you correction my code

$tongkol = $dataSurat->pilih_kepala;
$integerIDs = array_map('intval', explode(',', $tongkol));
for ($i = 0; $i < sizeof($integerIDs); $i++) {
    $this->pegawai->groupStart();
    $this->pegawai->where("find_in_set($integerIDs[$i], id_pegawai)");

    $this->pegawai->groupEnd();
    $query = $this->pegawai->get()->getResult();

    var_dump($query);

i want result like this, 2 object inside 1 array

array(2) { 
    [0]=> object(stdClass)#105 (18) { ["id_pegawai"]=> string(1) "6" ["nip"]=> string(3) "123" ["nama"]=> string(13) "RENNY, SH., M" ["jenis_pegawai"]=> string(3) "PNS" ["id_golongan"]=> string(1) "4" ["id_pangkat"]=> string(1) "5" ["id_jabatan"]=> string(1) "3" ["jenis_kelamin"]=> string(6) "wanita" ["alamat"]=> string(7) "Jakarta" ["agama"]=> string(5) "Islam" ["tempat_lahir"]=> string(7) "Jakarta" ["tanggal_lahir"]=> string(10) "1984-02-20" ["no_hp"]=> string(12) "081200000000" ["email"]=> string(15) "email@email.com" ["pasfoto"]=> string(0) "" ["created_at"]=> string(10) "2021-11-22" ["updated_at"]=> string(10) "2021-11-28" ["slug"]=> string(0) "" } 
    [1]=> object(stdClass)#106 (18) { ["id_pegawai"]=> string(1) "7" ["nip"]=> string(3) "456" ["nama"]=> string(16) "MUHAMMAD SYAFI'I" ["jenis_pegawai"]=> string(7) "HONORER" ["id_golongan"]=> string(1) "4" ["id_pangkat"]=> string(1) "5" ["id_jabatan"]=> string(1) "3" ["jenis_kelamin"]=> string(4) "pria" ["alamat"]=> string(7) "Bandung" ["agama"]=> string(5) "Islam" ["tempat_lahir"]=> string(8) "Malaysia" ["tanggal_lahir"]=> string(10) "1960-10-31" ["no_hp"]=> string(5) "14045" ["email"]=> string(15) "email@gmail.com" ["pasfoto"]=> string(0) "" ["created_at"]=> string(10) "2021-11-22" ["updated_at"]=> string(10) "2021-11-28" ["slug"]=> string(0) "" } } 

but i got like this

array(1) { 
    [0]=> object(stdClass)#108 (18) { ["id_pegawai"]=> string(1) "6" ["nip"]=> string(3) "123" ["nama"]=> string(13) "RENNY, SH., M" ["jenis_pegawai"]=> string(3) "PNS" ["id_golongan"]=> string(1) "4" ["id_pangkat"]=> string(1) "5" ["id_jabatan"]=> string(1) "3" ["jenis_kelamin"]=> string(6) "wanita" ["alamat"]=> string(7) "Jakarta" ["agama"]=> string(5) "Islam" ["tempat_lahir"]=> string(7) "Jakarta" ["tanggal_lahir"]=> string(10) "1984-02-20" ["no_hp"]=> string(12) "081200000000" ["email"]=> string(15) "email@email.com" ["pasfoto"]=> string(0) "" ["created_at"]=> string(10) "2021-11-22" ["updated_at"]=> string(10) "2021-11-28" ["slug"]=> string(0) "" } } 
array(1) { 
    [0]=> object(stdClass)#110 (18) { ["id_pegawai"]=> string(1) "7" ["nip"]=> string(3) "456" ["nama"]=> string(16) "MUHAMMAD SYAFI'I" ["jenis_pegawai"]=> string(7) "HONORER" ["id_golongan"]=> string(1) "4" ["id_pangkat"]=> string(1) "5" ["id_jabatan"]=> string(1) "3" ["jenis_kelamin"]=> string(4) "pria" ["alamat"]=> string(7) "Bandung" ["agama"]=> string(5) "Islam" ["tempat_lahir"]=> string(8) "Malaysia" ["tanggal_lahir"]=> string(10) "1960-10-31" ["no_hp"]=> string(5) "14045" ["email"]=> string(15) "email@gmail.com" ["pasfoto"]=> string(0) "" ["created_at"]=> string(10) "2021-11-22" ["updated_at"]=> string(10) "2021-11-28" ["slug"]=> string(0) "" } }

Solution

Try using array_merge

$result = array();
$tongkol = $dataSurat->pilih_kepala;
$integerIDs = array_map('intval', explode(',', $tongkol));
for ($i = 0; $i < sizeof($integerIDs); $i++) {
    $this->pegawai->groupStart();
    $this->pegawai->where("find_in_set($integerIDs[$i], id_pegawai)");

    $this->pegawai->groupEnd();
    $result = array_merge($result, $this->pegawai->get()->getResult());

    var_dump($result);


Answered By - Kinglish
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 16, 2022

[FIXED] Symfony php Custom exception controller not working

 February 16, 2022     controller, php, routes, symfony, symfony4     No comments   

Issue

I'm trying to create a custom exception controller in php Symfony 4. Essentially what I want to do is to have a default route that gets called when no other routes match.

I'm trying to follow the suggestions here: https://symfony.com/doc/current/controller/error_pages.html#custom-exception-controller

I've created the twig.yaml file inside configs>>pacakges:

twig:
    exception_controller: App\Controller\ExceptionController::showException

I've also created the ExceptionController class:

<?php
namespace  App\Controller;


use Symfony\Component\HttpFoundation\Response;

class ExceptionController
{

    public function showException()
    {
        $response = new Response();
        $response->setContent("Some random text");
        $response->headers->set('Content-Type', 'text/plain');
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->setStatusCode(200);
        return $response;
    }
}

When I visit a url that does not exist I'm expecting to see the text "Some random text" but instead I get the default symfony not found page:

enter image description here

Any ideas what I might be doing wrong?


Solution

You mentioned that you created a twig.yaml under configs/packages.

Two things:

  1. This should be config, not configs
  2. twig.yaml should already exist, there is no need to create this file.

My suspicion is that if you created this file, you've created a file in the wrong place and Symfony is not picking up your configuration change. Instead, add your configuration change to the existing twig.yaml file under config/packages.

Once you add your custom exception_controller path to this existing (assumed default) twig.yaml it should look something like this:

twig:
    default_path: '%kernel.project_dir%/templates'
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    exception_controller: App\Controller\ExceptionController::showException

I tested this with a fresh install and it works as expected.

Hope this helps :)


Your method should be called showException and not endpoint as you defined in your twig.exception_controller configuration.



Answered By - Darragh Enright
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 13, 2022

[FIXED] laravel route::post wrong method gets called

 February 13, 2022     controller, laravel, route-parameters, routes     No comments   

Issue

Starting off with a bit of background information, i have 3 models - Course, Pathway, Module.

Course HAS-MANY Pathway
Pathway HAS-MANY Module
Course HAS-MANY-THROUGH Module (through Pathway)

I have set up routes for creating Course, Pathway and Module. However, when I try to save the newly created model instance, it calls the wrong route method - does not even hit the store method of the relevant Controller

I understand that the order of the routes is important. I tried changing them around but it still does not work as intended.

Here's what I have so far :

// modules
Route::get('/courses/{course}/edit/pathways/{pathway}/modules/create', [App\Http\Controllers\ModulesController::class, 'create'])->name('createModule');
Route::post('/courses/{course}/edit/pathways/{pathway}/modules', [App\Http\Controllers\ModulesController::class, 'store'])->name('storeModule');

// Pathways
Route::get('/courses/{course}/edit/pathways/create', [App\Http\Controllers\PathwaysController::class, 'create'])->name('createPathway');
Route::get('/courses/{course}/pathways/{pathway}/edit', [App\Http\Controllers\PathwaysController::class, 'edit'])->name('editPathway');
Route::delete('/courses/{course}/pathways/{pathway}', [App\Http\Controllers\PathwayController::class, 'destroy'])->name('destroyPathway');
Route::post('/courses/{course}/edit/pathways', [App\Http\Controllers\PathwaysController::class, 'store'])->name('storePathway');


// VQs/Qualifications
Route::resource('courses', App\Http\Controllers\CourseController::class, [
    'names' => [
        'index'     => 'allCourses',
        'create'    => 'createCourse',
        'store'     => 'storeCourse',
        'show'      => 'showCourse',
        'edit'      => 'editCourse',
        'update'    => 'updateCourse',
        'destroy'   => 'destroyCourse',
    ]
]);

The problem is that when I try to store a Pathway or Module, it hits the Route::post('/courses/{course}') route.

I tried changing around the order of the routes, but none of that worked. I've also made sure that the create forms action is of the right Url Route. its all still the same.

I also can't tell which controller method is being called. Tried doing a dd() on CourseController@create, PathwaysController@create, ModulesController@create but none of them get hit.

Any help as to why this is happening will be greetly appreciated


Edit

here are some of my routes: enter image description here


Solution

Fixed it. Turns out there wasn't a problem with my routes at all.

The problem was that I had vertical navs and tab-panes on that page, and most of them had a form in them. I had not closed the form in one of the tab-panes and so this form was getting submitted to the action of the form above in that page.

i.e. Make sure to close forms using:

{{ Form::close() }}


Answered By - Suhaib Ahmad
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 2, 2022

[FIXED] CakePHP Call to a member function disable() on a non-object

 February 02, 2022     cakephp, cakephp-2.x, controller, model, php     No comments   

Issue

never use cakephp before and we have a project to edit for our client made in cakephp 2.5.

We tried to create a new functionality "Emplois" to add jobs inside the website. We mainly recreate what existed from an other models / controller already working inside the website but currently we get this error and we can't figure the problem.

Error: Call to a member function disable() on a non-object
File: /home/voyou/subdomains/labsurface/app/Controller/EmploisController.php
Line: 95

Here's the model : /app/Model/Emploi.php

<?php
App::uses('AppModel', 'Model');
/**
 * Emploi Model
 *
 */
class Emploi extends AppModel {

public $faIcone = "thumb-tack";
public $order = 'Emploi.ordre';


public $actsAs = array(
        'I18n' => array(
            'fields' => array('nom')
        ),
    );
/**
 * Display field
 *
 * @var string
 */
    public $displayField = 'nom_fre';
/**
 * Search field
 *
 * @var string
 */
    public $searchField = 'nom_fre';
}

And here's the controller : /app/Controller/EmploisController.php

<?php
App::uses('AppController', 'Controller');
/**
 * Emplois Controller
 *
 * @property Emploi $Emploi
 */
class EmploisController extends AppController {

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('get');
        
    }

/**
 * get method
 *
 * @return void
 */
    public function get($id = null) {
        if($id) {
            return $this->Emploi->findById($id);
        }
        else {
            return $this->Emploi->find('all');
        }
    }
    
    /**
 * get beforeRender method
 *
 * @return void
 */
    public function beforeRender()  {
        $this->set('faIcone', $this->Emploi->faIcone);
    }

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->Emploi->recursive = 0;
        $this->set('Emplois', $this->paginate());
        parent::beforeRender();
    }

/**
 * voir method
 *
 * @param string $id
 * @return void
 */
    public function voir($id = null) {
        $this->Emploi->id = $id;
        if (!$this->Emploi->exists()) {
            throw new NotFoundException(__('Emploi invalide'));
        }
        $emploi = $this->Emploi->read(null, $id);
        $this->set('Emploi', $emploi);
        $this->set("title_for_layout", $emploi['Emploi']['seo_title']); 
        $this->set("description_for_layout", $emploi['Emploi']['seo_description']);
    }
    
    
/**
 * page_plugin method
 *
 * @return void
 */
    public function page_plugin($page_id = null) {
        $this->Emploi->recursive = 0;
        $this->set('Emplois', $this->Emploi->find('all', array('conditions'=> array('Emploi.page_id' => $page_id))));
    }
    
    
    
/**********************************
 * 
 *    Actions administratives
 * 
 **********************************/
    
/**
 * admin method
 *
 * @return void
 */
     public function admin($search = null) {
         
        //(debug($this));
        $this->layout = 'admin';
        $this->Emploi->Behaviors->disable('I18n');
        $this->Emploi->recursive = 0;
        
        $options['limit'] = 10000;
        if ($search) {
        $options['conditions'] = array('Emploi.'.$this->Emploi->searchField.' LIKE' => '%'.$search.'%');
        }
        $this->paginate = $options;

        $this->set('Emplois', $this->paginate());
        $this->set('searchField', $this->Emploi->searchField);
        
        if($this->RequestHandler->isAjax()) {
            $this->layout = 'ajax';
            $this->render('/Elements/tables/Emplois');
        }       
     }
/**
 * irre method
 *
 * @return void
 */ 
    public function irre($page_id = null){
        $this->set('page_id', $page_id);
        $this->set('Emplois', $this->Emploi->findAllByPageId($page_id));
            }

/**
 * ajouter method
 *
 * @return void
 */
    public function ajouter() {
        $this->layout = 'admin';
        $this->Emploi->Behaviors->disable('I18n');
        if ($this->request->is('post')) {
            $this->Emploi->create();
            if ($this->Emploi->save($this->request->data)) {
                $this->Session->setFlash(__('Le/la emploi a bien été ajouté'));
                $this->redirect(array('action' => 'admin'));
            } else {
                $this->Session->setFlash(__('Le/la emploi n\'a pas pu être ajouté. S\'il vous plaît, essayer de nouveau.'));
            }
        }
    $this->render('modifier');
    }

/**
 * modifier method
 *
 * @param string $id
 * @return void
 */
    public function modifier($id = null) {
        $this->layout = 'admin';
        $this->Emploi->Behaviors->disable('I18n');
        
        $this->Emploi->id = $id;
        if (!$this->Emploi->exists()) {
            throw new NotFoundException(__('emploi invalide'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Emploi->save($this->request->data)) {
                $this->Session->setFlash(__('Le/la emploi a bien été sauvegardé'));
                $this->redirect(array('action' => 'admin'));
            } else {
                $this->Session->setFlash(__('Le/la emploi n\'a pas pu être sauvegardé. S\'il vous plaît, essayer de nouveau.'));
            }
        } else {
            $this->request->data = $this->Emploi->read(null, $id);
        }
    }

/**
 * supprimer method
 *
 * @param string $id
 * @return void
 */
    public function supprimer($id = null) {
        if (!$id) {
            throw new MethodNotAllowedException();
        }
        $this->Emploi->id = $id;
        if (!$this->Emploi->exists()) {
            throw new NotFoundException(__('Emploi invalide'));
        }
        if ($this->Emploi->delete()) {
            $this->Session->setFlash(__('Emploi supprimé'));
            $this->redirect(array('action' => 'admin'));
        }
        $this->Session->setFlash(__('Emploi n\'a pu être supprimé'));
        $this->redirect(array('action' => 'admin'));
    }
    
/**
 * ordre method
 */ 
    
    public function ordre() {
        $this->autoRender = false;
        $this->Emploi->Behaviors->disable('I18n');
        $this->Emploi->Behaviors->disable('Image');
        $error = 0;
        Configure::write('debug', 0);
        foreach($_POST['Emplois'] as $pos=>$id) {
            if($id) {
                $data['Emploi']['id'] = $id;
                $data['Emploi']['ordre'] = $pos;
                if (!$this->Emploi->save($data, array('fieldList'=>array('ordre')))) {
                    $error++;
                }
            }
        }
    }
}

The error point to the line $this->Emploi->Behaviors->disable('I18n'); inside the public function admin but from our understanding, $this->Emploi is null and we have no idea how to link the model to the controller.

Here the /app/Model/AppModel.php

<?php
/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {
    
    function getNextId(){

        $next_increment = 0;

        $table = Inflector::tableize($this->name);

        $query = "SHOW TABLE STATUS LIKE '$table'";

        $db =& ConnectionManager::getDataSource($this->useDbConfig);

        $result = $db->rawQuery($query);



       while ($row = $result->fetch(PDO::FETCH_ASSOC)) {

            $next_increment = $row['Auto_increment'];

        }

        return $next_increment;

    }  
    
}

Solution

As mentioned in the comments, the problem with your code is that it uses non US English names, which violates CakePHP's naming conventions, and breaks the magic around that which is using inflection for tasks like finding and loading the default model for a controller based on singularizing the controller name.

Inflection mostly works on word endings as known from US English based words, it's not like the inflector knows about all possible words, it's just some basic grammar rules and a few exceptions, so things might work for words from other languages simply because their ending happens to match a rule. -ois as in your Emplois name matches the rule for uninflected words, it will catch words like bourgeois or Illinois. Regarding your example from the comments, Projets and Projects, there's no difference for the inflector, it will not match anything irregular, but just the the -s ending rule, and therefore being interpreted as plural, so it happens to just work by chance, so to speak.

Ideally you use proper English names everywhere. If you cannot work that out right now, then the next best thing would be to either use custom inflections, or depending on the situation where inflection is failing, interfer manually, like using loadModel() manually. An example for custom inflection for Emploi/Emplois would be:

// in `app/Config/bootstap.php`

Inflector::rules('singular', array(
    'irregular' => array(
        'emplois' => 'emploi',
    ),
));

See also

  • Cookbook > Development > Configuration > Inflection Configuration
  • Cookbook > Getting Started > CakePHP Conventions


Answered By - ndm
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 29, 2022

[FIXED] Codeigniter config file change from model or controller

 January 29, 2022     codeigniter, config, controller, model     No comments   

Issue

How can we edit config file details from model or controller...? I want to change currency based on location of the user...


Solution

From Codeigniter User Guide - Setting a Config Item

with this:

$this->config->set_item('item_name', 'item_value');

you can change your config item on the fly.



Answered By - Kokers
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing