Zend Form: Custom validator isvalid() - zend-framework

I have to create my custom FORM:isvalid() function in my form like below, because I have to check if one of these 2 fields are at least filled out:
class Products_AddForm extends Zend_Form {
public function isValid($data)
{
// Check special post data
$pzn_val = $data['PZN'];
$mar_val = $data['PZO'];
if(empty($pzn_val) && empty($mar_val)) {
$this->getSubForm('sub1')->getElement('PZN')->setErrors(array('PZN or PZO needed'));
$this->getSubForm('sub2')->getElement('PZO')->setErrors(array('PZN or PZO needed'));
}
// Standard validation
return parent::isValid($data);
}
The errors for PZN and PZO will only fire if another error (other field) will be found.
How can I get the form error?
Field PZN and PZO are defined as not required.
TIA
Matt

Try:
public function isValid($data) {
$isValid = parent::isValid($data);
// Check special post data
$pzn_val = $data['PZN'];
$mar_val = $data['PZO'];
if(empty($pzn_val) && empty($mar_val)) {
$this->getSubForm('sub1')->getElement('PZN')->setErrors(array('PZN or PZO needed'));
$this->getSubForm('sub2')->getElement('PZO')->setErrors(array('PZN or PZO needed'));
$isValid = false;
}
return $isValid;
}

Related

how to config container with request variable

In the first place I had to configure parameters using the class "ParametersCompilerPass" to get data from database.Here si my class :
class ParametersCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$boutique = $em->getRepository('AcmeBundle:Boutique')->findOneByNom($container->getParameter('boutique.config'));
if(null !== $boutique){
$container->setParameter('url_site', $boutique->getUrl());
$container->setParameter('idboutique', $boutique->getId());
}else{
$container->setParameter('url_site', null);
$container->setParameter('idboutique', 0);
}
}
}
and when i set a parameter from request, it dont work, i tried in adding this code :
$request = $container->get('request_stack')->getCurrentRequest();
if($request->getMethod() == 'POST'){
if (null !== $choixbout = $request->get('choixbout')){
// $this->container->setParameter('idboutique',$choixbout);
}
}
the service request_stack return null.
I do not know how to configure a parameter from a POST variable.
Hope you can help me.
thanks
Is it solid requirement to have the parameter set?
It could be handy to create a service which has a request dependency that can act as a boutique parameter holder.
For example
# app/config/services.yml
app.boutique:
class: AppBundle\Boutique\Boutique
arguments: ['#request_stack']
app.boutique_info_dependant1:
class: AppBundle\Boutique\BoutiqueDependant1
arguments: ['#app.boutique']
app.boutique_info_dependant2:
class: AppBundle\Boutique\BoutiqueDependant2
arguments: ['#app.boutique']
This would be a parameter handler.
# AppBundle/Boutique/Boutique.php
class Boutique
{
/** #var RequestStack */
private $requestStack;
/**
* BoutiqueListener constructor.
* #param ContainerInterface $container
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function getBoutique()
{
$request = $this->requestStack->getCurrentRequest();
/// here you can add an extra check if the request is master etc.
if ($request->getMethod() == Request::METHOD_POST) {
if (null !== $choixbout = $request->get('choixbout')) {
return $choixbout;
}
}
return null;
}
}
Then using the handler
class BoutiqueDependant1
{
public function __construct(Boutique $boutique)
{
$this->myBoutique = $boutique->getBoutique();
}
}
This does not look like the best solution but could work...
Other option would be to rethink the application architecture to handle boutique information somehow differently.

Zend ACL Dynamic Assertion

I want to restrict my users to edit/delete only the comments which they added. I found an example on youtube by a guy named intergral30 and followed his instruction. And now my admin account has the possibility to edit/delete everything, but my user has no access to his own comment.
Here's the code:
Resource
class Application_Model_CommentResource implements Zend_Acl_Resource_Interface{
public $ownerId = null;
public $resourceId = 'comment';
public function getResourceId() {
return $this->resourceId;
}
}
Role
class Application_Model_UserRole implements Zend_Acl_Role_Interface{
public $role = 'guest';
public $id = null;
public function __construct(){
$auth = Zend_Auth::getInstance();
$identity = $auth->getStorage()->read();
$this->id = $identity->id;
$this->role = $identity->role;
}
public function getRoleId(){
return $this->role;
}
}
Assertion
class Application_Model_CommentAssertion implements Zend_Acl_Assert_Interface
{
public function assert(Zend_Acl $acl, Zend_Acl_Role_Interface $user=null,
Zend_Acl_Resource_Interface $comment=null, $privilege=null){
// if role is admin, he can always edit a comment
if ($user->getRoleId() == 'admin') {
return true;
}
if ($user->id != null && $comment->ownerId == $user->id){
return true;
} else {
return false;
}
}
}
In my ACL I have a function named setDynemicPermissions, which is called in an access check plugin's preDispatch method.
public function setDynamicPermissions() {
$this->addResource('comment');
$this->addResource('post');
$this->allow('user', 'comment', 'modify', new Application_Model_CommentAssertion());
$this->allow('admin', 'post', 'modify', new Application_Model_PostAssertion());
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$this->_acl->setDynamicPermissions();
}
And I'm calling the ACL-s isAllowed method from my comment model where I return a list of comment objects.
public function getComments($id){
//loading comments from the DB
$userRole = new Application_Model_UserRole();
$commentResource = new Application_Model_CommentResource();
$comments = array();
foreach ($res as $comment) {
$commentResource->ownerId = $comment[userId];
$commentObj = new Application_Model_Comment();
$commentObj->setId($comment[id]);
//setting the data
$commentObj->setLink('');
if (Zend_Registry::get('acl')->isAllowed($userRole->getRoleId(), $commentResource->getResourceId(), 'modify')) {
$commentObj->setLink('Edit'.'Delete');
}
$comments[$comment[id]] = $commentObj;
}
}
Can anyone tell me what have I done wrong?
Or what should I use if I want to give my admins the right to start a post and other users the right to comment on them. Each user should have the chance to edit or delete his own comment and an admin should have all rights.
You seem to be using the dynamic assertions in a wrong manner, as you are still passing the roleId to isAllowed().
What these dynamic assertions really do, is take a complete object and work with it. Zend will determine which rule has to be used by calling getResourceId() and getRoleId() on your objects.
So all you have to do is pass your objects instead of the strings to isAllowed():
public function getComments($id){
//loading comments from the DB
$userRole = new Application_Model_UserRole();
$commentResource = new Application_Model_CommentResource();
$comments = array();
foreach ($res as $comment) {
$commentResource->ownerId = $comment[userId];
$commentObj = new Application_Model_Comment();
$commentObj->setId($comment[id]);
//setting the data
$commentObj->setLink('');
// This line includes the changes
if (Zend_Registry::get('acl')->isAllowed($userRole, $commentResource, 'modify')) {
$commentObj->setLink('Edit'.'Delete');
}
$comments[$comment[id]] = $commentObj;
}
}
But in can be done better
You would not have to implement a total new Application_Model_CommentResource, but instead you can use your actual Application_Model_Comment like this:
// we are using your normal Comment class here
class Application_Model_Comment implements Zend_Acl_Resource_Interface {
public $resourceId = 'comment';
public function getResourceId() {
return $this->resourceId;
}
// all other methods you have implemented
// I think there is something like this among them
public function getOwnerId() {
return $this->ownerId;
}
}
Assertion would then use this object and retrieve the owner to compare it with the actually logged in person:
class Application_Model_CommentAssertion implements Zend_Acl_Assert_Interface {
public function assert(Zend_Acl $acl, Zend_Acl_Role_Interface $user=null,
Zend_Acl_Resource_Interface $comment=null, $privilege=null){
// if role is admin, he can always edit a comment
if ($user->getRoleId() == 'admin') {
return true;
}
// using the method now instead of ->ownerId, but this totally depends
// on how one can get the owner in Application_Model_Comment
if ($user->id != null && $comment->getOwnerId() == $user->id){
return true;
} else {
return false;
}
}
And the usage is like this:
public function getComments($id) {
//loading comments from the DB
$userRole = new Application_Model_UserRole();
$comments = array();
foreach ($res as $comment) {
$commentObj = new Application_Model_Comment();
$commentObj->setId($comment[id]);
//setting the data
$commentObj->setLink('');
// no $commentResource anymore, just pure $comment
if (Zend_Registry::get('acl')->isAllowed($userRole, $comment, 'modify')) {
$commentObj->setLink('Edit'.'Delete');
}
$comments[$comment[id]] = $commentObj;
}
}

ZF using placeholders inside plugins

I'm trying to implement a plugin that handles responses to the user on success or failure in a persistance transaction. When the response is false I use a _forward to the action that performed the form's submit and get my placeholder message shown but when the response is true I use a _redirect to the browse with the new record shown.
My problem is that when I use _redirect the browser doesn't show the placeholder message. I'll show the code here:
/**
* Plugin
*/
class Application_Plugin_PostMessage extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$message = $request->getParam('message');
$error = $request->getParam('error');
if (null !== $message || null !== $error) {
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$placeHolder = $view->placeholder('message');
$placeHolder->setPostfix('</div>');
if (null !== $error) {
$placeHolder->setPrefix('<div class="errorMessage">')
->append($error);
}
elseif (null !== $message) {
$placeHolder->setPrefix('<div class="infoMessage">')
->append($message);
}
}
}
}
/**
* Controller
*/
class My_FooController extends Zend_Controller_Action
{
public function init()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_PostMessage());
}
...
public function browseAction()
{
...
// No message is shown here on redirect
...
}
public function newAction()
{
...
// This code shows the placeholder on _forward call
...
}
public function insertAction()
{
if(true) {
return $this->_redirect('/my/foo/browse?message='
. urlencode("success message"));
}
else {
return $this->_forward('new', null, null, array(
'error' => 'error messsage'
));
}
}
}
I can't use _forward on success because I don't want the use of [F5] key repeats the insert action
Thanks in advance
This is what Flash Messenger is for:
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelper.flashmessenger.basicusage
It stores messages in your session removing the need for passing messages as you are.

Symfony2 checkbox form, alter date based on a checkbox

For test purposes I make a light library online tool with Symfony2.
I have a Borrow entity that links to other entities. I want to create a form to validate the return of the books a given user have borrowed.
I have gathered all the Borrow recordings that correspond to books the user has not returned.
Now I want to create a form with a checkbox list to validate the books the user has returned.
After that, I can make something like what follows (which is not the problem).
if ($this->getRequest()->getMethod() == 'POST')
{
$form->bindRequest($this->getRequest());
if ($form->isValid())
{
$obj_list = $form->getData();
foreach ($obj_list as $obj)
{
$obj->setBorrowEndDate(...); // Today's datetime
$em = $this->getDoctrine()->getEntityManager();
$em->persist($obj);
$em->flush();
}
return $this->redirect($this->generateUrl('index'));
}
else
{
$args['problem']=$form->errors();
}
}
// Continuation : creation of the form
instead of creating entity attribute, you can do it in this way:
$builder->add('check', 'checkbox', [
'mapped' => false
]);
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event)
{
$form = $event->getForm();
$object = $event->getData();
if($form->get('check')->getData() && !$object->getBorrowEndDate()) {
$object->setBorrowEndDate(new \DateTime());
}
$event->setData($object);
});
I don't really understand your problem but i'll try to help you:
1) Create a class attribute in your Entity (Borrow) called "check" for example, which is not depending on your databases:
private $check;
public function setCheck($check)
{
$this->check = $check;
}
public function getCheck()
{
return $this->check;
}
2) Add it in your class form as a checkbox input.
$builder->add('check', 'checkbox')
3) Then, you've got 2 solutions:
Update its setter like this:
public function setCheck($check)
{
$this->check = $check;
// Update borrow endtime
if ($this->check === true && !$this->getBorrowEndDate()) {
$this->setBorrowEndDate(new \DateTime());
}
}
Or use doctrine lifecycles:
/**
* Called before persisting your entity
*
* #ORM\prePersist
*/
public function prePersist()
{
// Update borrow endtime
if ($this->check === true && !$this->getBorrowEndDate()) {
$this->setBorrowEndDate(new \DateTime());
}
}
Hope this helps you !

accessing request parameters from inside validator

Is there a proper way to access other form fields from inside a validator?
Is there another solution than:
context.getViewRoot().findComponent("formid:exampleField:example")?
f.e I want to validate a city field inside a custom validator and checking if country is US.
Re-read your question and I am going to interpret it as this:
"You would like to write a custom validator that checks that if a city field exists, the country field is equal to 'US'"
So, I would look at going about this in the following fashion:
First create a validator interface:
#Documented
#ValidatorClass(value=CountryEqualsUSValidator.class)
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface CountryEqualsUS {
String message() default "The country should be US for the city provided";
}
Then create a validator class:
public class CountryEqualsUSValidator implements Validator<CountryEqualsUS> {
public void initialize(CountryEqualsUS arg0) {
}
public boolean isValid(Object value) {
if(value != null && value instanceof YourBeanClass) {
YourBeanClass yourBeanClass = (YourBeanClass) value;
if(/*some test logic here*/) {
return true;
else {
return false;
}
}
return false;
}
}
Then on the class that you want to validate:
#CountryEqualsUS
public class YourBeanClass {
...
}
Then, finally, on your controller/action class, when the form is submitted, the city is a value for which you want to check the country, add this method and call it:
public boolean doValidation(YourBeanClass yourBeanClass) {
ClassValidator requestValidator = new ClassValidator(yourBeanClass.getClass());
InvalidValue[] validationMessages = requestValidator.getInvalidValues(yourBeanClass);
if (validationMessages != null && validationMessages.length > 0) {
for (int i = 0; i < validationMessages.length; i++) {
//Add a validation message to be displayed to the user
}
return false;
}
return true;
}