In my application I am using multiple forms, the forms submission points to another
action but redirects back to the previous action. In the form submission action I handle
the form input / validation. To return an error or success message I use the FlashMessenger.
My point of problem is that it's not clear how I set a namespace for the FlashMessenger. I have serval forms on the same page where I would like to use FlashMessenger messenges.
if ($this->flashMessenger()->hasMessages()) {
$messages = $this->flashMessenger()->getMessages();
foreach($messages as $message) {
echo $message;
}
}
I am guessing I should do something with '$this->flashMessenger('namespace').. In my controller action? But I didn't figure out how exactly make this work. If anyone has an example.. that would be great :)
You can add a message into a particular namespace by using these built-in methods in your action controller:
// in your controller
$this->flashMessenger()->addInfoMessage('info message');
$this->flashMessenger()->addSuccessMessage('success message');
$this->flashMessenger()->addErrorMessage('error message');
// in your view script
$this->flashMessenger()->getInfoMessages();
$this->flashMessenger()->getSuccessMessages();
$this->flashMessenger()->getErrorMessages();
Or if you want to specify your own namespace, you can use something like:
// in your action controller
$defaultNamespace = $this->getNamespace();
$this->setNamespace('yournamespace');
$this->addMessage($message);
$this->setNamespace($defaultNamespace);
// in your view script
$this->flashMessenger()->getMessagesFromNamespace('yournamespace');
For more information, you can see the documentation:
http://framework.zend.com/manual/2.3/en/modules/zend.mvc.plugins.html#flashmessenger-plugin
http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.flash-messenger.html#basic-usage
The namespace of the flash messenger controller plugin can be manual set using the setNamespace($namespace) method.
$this->flashMessenger()->setNamespace('foo')->addMessage($message);
However there are also convenience functions that will set a different namespace and message at the same time.
For example, if you want to add a success message then you can use:
$this->flashMessenger()->addSuccessMessage($message);
Internally the plugin will set the namespace as success and add the message to it (and then reset the namespace to allow for the next message to be set (defaults to default))
public function addSuccessMessage($message)
{
$namespace = $this->getNamespace();
$this->setNamespace(self::NAMESPACE_SUCCESS);
$this->addMessage($message);
$this->setNamespace($namespace);
return $this;
}
Related
Coming from Yii2 at the end of each request when something is logged, Yii2 adds additional data to your log, for example the $_POST data so you know what paramaters caused the issue.
Is there a way to add these information in Monolog too?
I don't want to use a Processor as it includes all those parameters to each and every record. I would just like to add an additional string in case something is logged at the end of the log after all messages are included/send (for example via BufferHandler when sending Mails via SwiftMailerHandler)
I found a way..
I can extend the default HtmlFormatter or LineFormatter and include my custom information that way
namespace modules\myspa\monolog;
class HtmlFormatter extends \Monolog\Formatter\HtmlFormatter
{
public function formatBatch(array $records): string
{
$formatBatch = parent::formatBatch($records);
$formatBatch .= '<br><br>Foobar.. add some custom info';
return $formatBatch;
}
}
Then I can add this one as a formatter
$swiftMailHandler = new SwiftMailerHandler($swiftMailer, $message, \Monolog\Logger::ERROR);
// add my formatter
$swiftMailHandler->setFormatter(new HtmlFormatter());
$psrLogger->pushHandler(new BufferHandler($swiftMailHandler));
I'm trying to set a message in Zend Framework 1's flash messenger. Then I'm outputting the result here as I was getting nothing in my view:
public function successAction()
{
$this->_helper->flashMessenger->addMessage('Account has been successfully created.');
$this->view->messages = $this->_helper->flashMessenger->getMessages();
var_dump($this->view->messages); exit;
}
..but it's just an empty array. Is there anything else I have to do withing the framework, or with the helper to set and retrieve these?
Here is how I was trying to access it from
The FlashMessenger helper allows you to pass messages that the user
may need to see on the next request. To accomplish this,
FlashMessenger uses Zend_Session_Namespace to store messages for
future or next request retrieval.
You can see it in the doc
So your message can be recovered in another action (other request).
If you want to retrieve the message in the same action, you can try to use getCurrentMessages():
$this->view->messages = this->_helper->flashMessenger->getCurrentMessages();
But if this message is only for one request, you can use Zend_Registry
I've inherited a website built using Codeigniter (v2.1.4). The client has asked for a change, and I'm not sure of the best way to achieve it.
I have the following method in the Main controller that powers a new vans page.
public function new_vans($slug = null){
$this->load->view('inc/header_view');
if($slug === NULL){
//If no slug is provided, show all new vans
$this->load->view('new_vans_view');
}else{
//If there is a slug, just show the selected van, or redirect if nothing returned
$data['new_van'] = $this->Database->getSingle('new_vans', array('slug' => $slug));
if(!empty($data['new_van'])){
$this->load->view('new_van_details_view',$data);
}else{
redirect('/new-vans');
}
}
$this->load->view('inc/footer_view');
}
The client has asked for a contact form to be added to a couple of pages including this one, and my question is, should I create a new method that just handles the contact form submissions? If so, how would I handle sending validation errors back to the page? The contact forms will all have the same fields, so I would guess creating a new method is the way to go?
Partial Views(forms)
Partial views are good for forms, they can be re-used
like your client has requested.
Returning views as data
There is a third optional parameter lets you change the behavior
of the function so that it returns data as a
string rather than sending it to your browser.
This can be useful if you want to process the data in some way.
If you set the parameter to true (boolean) it will return data.
The default behavior is false, which sends it to your browser.
Remember to assign it to a variable if you want the data returned:
$string = $this->load->view('myfile', '', true);
Master layouts
To create a Master layout so you can wrap your views
create a new file inside your views directory
views/master/layout.php
<body>
<?php $this->load->view($view); ?>
</body>
Controller
class someController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->template = 'master/layout';
}
public function index()
{
return $this->load->view($this->template, array(
'view' => 'somecontrollerview',
'contact_form' => $this->load->view('partials/forms/contact', array(), true)
));
}
}
somecontrollerview
Echo out the contact form(string)
<?php echo $contact_form; ?>
Contact Controller
Create a new Controller to handle your form validation
The client has asked for a contact form to be added to a couple of pages including this one, and my question is, should I create a new method that just handles the contact form submissions?
create a new controller and new methods
If so, how would I handle sending validation errors back to the page?
look through the codeigniter documentation for form validation. basically if they have an error you are going to show them a view with the form again. it does not matter which page they came "from".
The contact forms will all have the same fields, so I would guess creating a new method is the way to go?
you need to validate the form fields, hopefully capture the contact info to a database, send an email confirmation to the customer, and send an email to the sales person unless its being done directly from the database, and then show a view with a thank you.
each one of those steps is a separate method.
optionally you can show the email address on the thank you page saying 'we have sent you a copy to the email address: something#gmail.com -- that way if the customer messed up the email address they can go back and correct it.
I am working in codeigniter and Iam looking to make my own custom validation class using "Validation_form" library and my custom rule where I will place my own validation rules and use that from everywhere in my project, but this seems impossible, I tried in couples ways to handle this but nothing.
Codeigniter kindle force me to make my callback methods in my controller but I need them in my library or "method" or wherever else!!!
My question is, can I build an specific library where I'll place my validation rules and other functions I need to handle that?
you could create a new library in application/libriries and name the file MY_Form_validation
What you are doing here is extending the form_validation class so that you will not need to mess with the core files.
The MY_ is what is set on your config, be sure to check it if you changed yours.
sample MY_Form_validation.php
class MY_Form_validation Extends CI_Form_validation
{
//this is mandatory for this class
//do not forget this or it will not work
public function __construct($rules = array(){
parent::__construct($rules);
$this->CI->lang->load('MY_form_validation');
}
public function method1($str){
return $str == '' ? FALSE : TRUE;
}
pulic function method2($str)
{
//if you want a validation from database
//you can load it here
// or check the `form_validation` file on `system/libraries/form_validation`
}
public function check_something_with_post($tr)
{
return $this->CI->input->post('some_post') == FALSE ? FALSE : TRUE;
}
}
Basically, when you call a rule sample method1|method2 the value of your post field will be the parameter of the method. if you want to check other post you can do it by using $this->CI->input->post('name of the post');
when you want to pass a parameter just look at the form validation is_unique or unique code on system/libraries/form_validation you will have an idea.
To create a error message that goes with it go to application/language/english/MY_Form_validation_lang
Sample MY_form_validation_lang.php
$lang['method1'] = "error error error.";
$lang['method2'] = "this is an error message.";
if english does not exist on your application/language just create it.
check more atCreating libraries
NOTE:
On some linux or debian server you may want to change the file name from MY_Form_validation to
MY_form_validation note the small f on the word form.
I have a simple setup in Yii with a Model, View and a Controller to manage a DB table. (created with Gii)
When the user presses the delete button I want to validate this request with some rules of my own and if there is an error display this to the user.
Should I put validation method in the Model, call this validation from the controller delete method. But then I am not sure how I get a popup to appear on the webpage.
I can't speak specifically for Yii, but in general with PHP 5.3 a good practice would be to throw errors from models (mind you, human readable ones) and then catch them when you call the models in your controllers. The controllers can then pass along a list of errors to the views, which would be responsible for displaying the error(s) to the users.
<?php
class Model {
public function doImportantStuff() {
//Do stuff
if(true) {
throw new Exception('Important stuff could not be completed due to this important error.');
}
}
}
class Controller {
public function index() {
$data = array();
$crucial = new Model();
try {
$crucial->doImportantStuff();
} catch(Exception $e) {
$data['errors'][] = $e;
}
}
}
//And in the view
<?php if($data['errors']): ?>
<?php foreach($data['errors'] as $error): ?>
<p><?= $error->getMessage(); ?></p>
<?php endforeach; ?>
<?php endif; ?>
You would want to put your validation rules in your model, in the rules method, which Gii should have created for you. You can use a pre-defined validation rule or create your own, see here. You would probably want to define a "scenario" attribute for this delete function and then you can restrict your custom rule to that delete action.
The action would be defined in your controller, -- if you used Gii for CRUD creation you should have sample code to reference.
In your view, you could either use CActiveForm::error() to display an error on the page or call getErrors() to retrieve the errors to create a custom error state (with js or css, etc.).
Another option would be to define an onsubmit function with js that does an ajax call to validate the delete function prior to submit. (That ajax call would be made to a controller function and you would still want to validate in the model as well before deleting.)