I configure json api in my suitecrm and now i want to add validation mandatory fields for some parameter please suggest me how to add validation and custom message.
I tried to add validation but can't get success is any idea how to configure validation message display
Use before_save logic hooks in that module in which you want to add validation then create you own method to check validation e.g. for checking pan number you can use pan regix then apiException
Hello try this one to your custom api controller
here`s my sample custom/application/Api/V8/Controller/CustomController.php
namespace Api\V8\Controller;
use Slim\Http\Request;
use Slim\Http\Response;
class CustomController extends BaseController
{
public function saveLeads(Request
$request, Response $response, array $args)
{
try {
$jsonResponse = $request->getParams();
$leadBean = \BeanFactory::newBean('Leads');
if(empty(jsonResponse['name'])
{
$resultMessage['Error'] = 'Please filled up the Name';
}else{
$leadBean->name = jsonResponse['name'];
$leadBean->save();
$resultMessage['Succes'] = Leads Has been created';
}
return $this->generateResponse($response, $resultMessage, 201);
} catch (\Exception $exception){
return $this->generateErrorResponse($response, $exception, 400);
}
}
Related
I've created a contact form in Cakephp 4 refering to the doc (https://book.cakephp.org/4/en/core-libraries/form.html).
I have a problem to remove input values after the email has been sent.
Here's my ContactController.php :
<?php
namespace App\Controller;
use App\Controller\AppController;
use App\Form\ContactForm;
class ContactController extends AppController
{
public function index()
{
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->getData())) {
$this->Flash->success('We will get back to you soon.');
$contact->setData([]); // I want to remove data in contact form after the email has been sent, but it doesn't work
} else {
$this->Flash->error('There was a problem submitting your form.');
}
}
$this->set('contact', $contact);
}
}
Why is $contact->setData([]); in the code abode not removing data in my contact form ?
The form helper will prefer request data, eg the POST data from your form submit, otherwise the input would always get lost when a validation error occurs.
If you want to show the form page again after successful submit, then you should redirect to the current page, that's called the PRG (Post-Redirect-Get) pattern.
So instead of $contact->setData([]);, do:
return $this->redirect(['action' => 'index']);
That's also what your baked controllers will do for add and edit actions.
See also
Cookbook > Controllers > Redirecting to Other Pages
I am building an angular application and want to implement password reset. However, default laravel config doesn't appear to allow one to do this using purely XMLHttpRequest ($http.post) requests and responds with a 302 redirect.
I managed to get postLogin and postRegister to work without issuing redirects by implementing said methods in authController class and returning a json response, doing this overrides the default laravel implementation of said methods. No such luck with postEmail and it appears the method is not hit at all, I just get a 302 response back immediately.
Ideally, other than to check their E-mail, I don't want the user to leave the single page angular application at all.
So 1. User posts E-mail to postEmail -> Email with reset link or better 'reset code' is sent to E-mail address -> User then inputs the reset token code into the already open web app or if it can't be done, browse to reset password page opened in new tab.
I tried implementing postEmail method as such:
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return response()->json(['msg' => 'A reset link has been sent to your E-mail'], 200);
case Password::INVALID_USER:
return response()->json(['msg' => 'This E-mail cannot be found in our system'], 200);
}
}
Also, where is template for the E-mail with the reset link that laravel sends out ?
You can create a PasswordController within the App\Http\Controllers\Auth namespace to extend the password reset methods.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function postEmail(Request $request)
{
}
}
To overwrite the email templates you can create a reminder.blade.php in the app/views/emails/auth directory, or change the location of the template file in the app/config/auth.php config.
while the accepted answer is completely valid, another solution without overriding the original notification class is as follows, ResetPassword provides a static method called createUrlUsing which accepts a Closure, So we can override the URL as something like the below:
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Notifications\ResetPassword;
...
$status = Password::sendResetLink(
['email' => $args['email']],
function ($user, $token) {
ResetPassword::createUrlUsing(function ($notifiable, $token) {
// This is where you override the URL, you can also take a look at
// the `url`, `action` and `route` functions in Laravel and skip
// `sprintf` if you prefer to stick to Laravel functions only.
return sprintf(
"%s/%s/?token=%s&email=%s",
config('your.optional.frontend_url'),
config('your.optional.password_reset'),
$token,
$notifiable->getEmailForPasswordReset(),
); // frontend_url/password_url/?token=TOKEN&email=EMAIL
});
return $user->notify(new ResetPassword($token));
}
);
// This is an optional way to handle the final response, you can convert it to
// JSON or ignore it.
return $status === Password::RESET_LINK_SENT
? ['status' => __($status)]
: throw new Error(__($status));
This piece of code should be placed at a new route to handle password reset requests instead of using the default Laravel one.
I am trying to invalidate a field by a condition in controller instead of Model.
$this->Model->invalidate('check_out_reason', __('Please specify check out reason.', true));
The above won't work to invalidate the field. Instead, I need the below:
$this->Model->invalidate('Model.check_out_reason', __('Please specify check out reason.', true));
However, if I wish get the error message show up in the "field" itself ($this->model->validationErrors), it needs to be "check_out_reason" instead of "Model.check_out_reason". That means, I can't get the error message to show up in the field itself if I wish to invalidate the input in controller.
May I know is this a bug in CakePHP?
i created a test controller called "Invoices", just for testing, and i developed the following function
public function index(){
if (!empty($this->request->data)) {
$this->Invoice->invalidate('nombre', __('Please specify check out reason.'));
if ($this->Invoice->validates()) {
// it validated logic
if($this->Invoice->save($this->request->data)){
# everthing ok
} else {
# not saved
}
} else {
// didn't validate logic
$errors = $this->Invoice->validationErrors;
}
}
}
i think it worked for me
Change the field "nombre" for your field called "check_out_reason" to adapt the function to your code
I found a workaround for manual invalidates from controller. Reading a lot on this issue I found out that the save() function doesn't take in consideration the invalidations set through invalidate() function called in controller, but (this is very important) if it is called directly from the model function beforeValidate() it's working perfectly.
So I recommend to go in AppModel.php file and create next public methods:
public $invalidatesFromController = array();
public function beforeValidate($options = array()) {
foreach($this->invalidatesFromController as $item){
$this->invalidate($item['fieldName'], $item['errorMessage'], true);
}
return parent::beforeValidate($options);
}
public function invalidateField($fieldName, $errorMessage){
$this->invalidatesFromController[] = array(
'fieldName' => $fieldName,
'errorMessage' => $errorMessage
);
}
After that, make sure that your model's beforeValidate() function calls the parent's one:
public function beforeValidate($options = array()) {
return parent::beforeValidate($options);
}
In your controller for invalidating a field use next line:
$this->MyModel->invalidateField('fieldName', "error message");
Hope it helps! For me it's working!
I need to be able to log/receive an email when a 404 error occurs. I can see in the docs how to set up a new template for these errors, but how do I catch them in the first place in my controller so that I can implement the logging/emailing logic?
Maybe adding an event listener listening for the kernel.exception event would do it?
Check out http://symfony.com/doc/current/book/internals.html#kernel-exception-event along with http://symfony.com/doc/current/reference/dic_tags.html#dic-tags-kernel-event-listener
A little example:
1) Create a custom Listener
//bundles/Acme/AcmeBundle/Listener/CustomListener.php
namespace Acme\AcmeBundle\Listener;
use Symfony\Component\EventDispatcher\Event;
public class CustomListener {
public function onKernelException(Event $event) {
//Get hold of the exception
$exception = $event->getException();
//Do the logging
// ...
}
}
2) Add the listener to your config
//config.yml
services:
kernel.listener.your_listener_name:
class: Acme\AcmeBundle\Listener\CustomListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
To get hold of the logging or mailing (Swiftmailer) services, you might consider injecting them into the listener (http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services)
I am new to CakePHP.
I would like to use the model validate mechanism, but I'm having trouble overriding the errors that are displayed. I am building an API where all the views need to be rendered in JSON and I have a JSON format that all errors need to output as. I've defined a custom AppError class and I have successfully be able to define custom errors in this format there.
Is there a way to use the AppError class to override the output of the error messages coming from validation?
Thanks.
I came up with a solution by adding these methods to my AppModel class:
function validates($options = array()) {
$result = parent::validates($options);
if (!$result) {
$this->_validateErrors();
}
return $result;
}
function _validateErrors() {
foreach ($this->validationErrors as $code) {
$this->cakeError('apiError', array('code' => $code)); // Custom JSON error.
return;
}
}
I then manually call $this->Model->validates() before a Model::save() call in my controller. This seems to be working well.
As far as I know, there's no direct way to get validation errors from within your AppError class. The way around it would be to create an AppModel class in app/app_model.php and use the onError() callback method to pass the error to your AppError class.
// app/app_model.php
class AppModel extends Model {
public function onError() {
// Pass the errors to your AppError class
AppError::someErrorMethod($this->getErrors());
}
}