validation,symfony2,constraints,formbuilder , Symfony2 form builder without class check if multiple fields are empty


Symfony2 form builder without class check if multiple fields are empty

Question:

Tag: validation,symfony2,constraints,formbuilder

I am using form builder without class and have two fields with each having constraints :

$form = $this->createFormBuilder()
        ->add('name', 'text', array(
            'required'=>false,
            'constraints'=> new Length(array('min'=>3)
        ))
        ->add('dob', 'date', array(
            'required'=>false,
            'constraints'=> new Date()
        ))
        ->getForm()
        ->handleRequest($request);

This works great but I want to check if both fields are emtpy, and display error. Just can't seem to get a handle on this. Could someone provide help???


Answer:

the easiest solution is to just set both as required ...

but.. on post you could check as simple as

if( empty($form->get('name')->getData()) && empty($form->get('dob')->getData())){
   $form->addError(new FormError("fill out both yo"));
   // ... return your view
}else {

  // ... do your persisting stuff
}
... 

the symfony way would possibly be adding a custom validator I suggest you to look at custom validator especially this part

pseudo :

namespace My\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CheckBothValidator extends ConstraintValidator
{
    public function validate($foo, Constraint $constraint)
    {
            if (!($foo->getName() && $foo->getDob()) {
                $this->context->addViolationAt('both', $constraint->message, array(), null);
            }
    }
}

Related:


Validation of a form before submission


php,validation,symfony2,form-submit
Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want the...

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass


php,symfony2,doctrine,entity,bundle
I created a Product.php file in my bundle Mingle\StandardBundle\Entity like this: <?php namespace Mingle\StandardBundle\Entity; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity * @ORM\Table(name="product") */ class Product { /* * @ORM\Column(type="integer") * @ORM\ID * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* * @ORM\Column(type="string",length=100) */ protected $name; /* * @ORM\Column(type="decimal",scale=2) */ protected $price; /*...

How to validate non-db attributes on an ActiveRecord model?


ruby-on-rails,validation,activerecord
I have the following class: class Instance < ActiveRecord::Base attr_accessor :resolution validates_format_of :resolution, with: /\A\d+x{1}\d+\d/ def resolution=(res) validate! (set the resolution etc) end def resolution (get the resolution and return) end end The resolution attribute is not stored in the database, but is a transient property of the instance. When...

how to multiply two column names using codeigniter validation rule


php,codeigniter,validation
I have three columns.The product of two columns get into third column name income_amount using codeigniter validation rule.the first column is crop_quantity and the second is per_rate controller $this->form_validation->set_rules('crop_quantity', 'Crop Quantity', 'required|numeric'); $this->form_validation->set_rules('per_rate', 'Per Rate', 'required|numeric|callback_get_product'); $this->form_validation->set_rules('income_amount', 'Income Amount', 'required|numeric');...

wkhtmltopdf on openSuSE: cannot connect to X server


php,symfony2,pdf-generation,twig,wkhtmltopdf
I need wkhtmltopdf on openSuSE. I have installed it via the repository. The version is 0.12.1. To render HTML with Symfony, I use the KnpSnappyBundle. By rendering a twig template, I got the following error message: The exit status code '1' says something went wrong: stderr: "wkhtmltopdf: cannot connect to...

Javascript/jQuery form validation


javascript,jquery,forms,validation
I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out...

Symfony one-to-one, unidirectional relation


symfony2,doctrine2
I have two entities. User and Contact. User and contact have the same property phone_number. I would like to get all contacts with user object if its exists. It is also possible that the same phone number exists in contact table but it doesn't exist in user table. Below is...

Codeigniter Form Validation Rule for match (password)


php,forms,codeigniter,validation
I am trying to write Form validation rules in my Controller to submit Change Password form in which I am checking the old password too. I am getting the old password(current) from db and placing it in a hidden input field. My Rules are simple and are given below $config=array(...

Unique Entity Error message


api,symfony2,exception-handling,doctrine
I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...

Symfony/Twig radio style formbuilder


php,symfony2,twig,formbuilder
I need to style each of radio button using Symfony form builder. This is my part of my createFormBuilder: ->add('categoryId', 'entity', array( 'class' => 'MyBundle:Category', 'property' => 'name', 'required' => false, 'expanded' => true )) And in my twig template: {% for child in form.categoryId %} <div class="radio i-checks col-md-3">...

Symfony2: ajax call redirection if session timedout


ajax,symfony2,session
I have a working dashboard with ajax request. I fire an ajax request on some events which will update a part of the dashboard. But if the session has expired, the part will be refreshed with the login page. How can i do a redirection after the ajax call if...

Symfony Crawler: how to check that a link to a particular page exists


php,symfony2,phpunit,functional-testing
I'm writing some functional tests and i want to verify that the Edit link exists on the page if the user is logged in. The link is a simple <a href="/profile/22/edit">Edit</a>. How can I filter it using the Crawler component of Symfony? One solution is this: $this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count()); But...

How to write and use Monolog handlers and channels


php,symfony2,monolog,symfony-2.6
I have read some docs here but still not clear to me how to write and use a custom Monolog handler and channel. Let me explain a bit what I want to achieve. I have a custom function and I want that log to be logged into a file called...

Validation on Radio Buttons


c#,wpf,validation,data-binding,radio-button
I'm not really sure how to word this, so here goes. I've got some radio buttons on a form in my WPF application which get validated. They're basically a required field for this form. When I start to fill in the form, both radio buttons are marked with a red...

how to use validationResover


validation,typo3-flow
Like shown here I want to use the validationResolver to dynamically validate user inputs in my App. Therefore I want to proove, if a condition is true in my controller. If the condition is true, I want to validate with an own validator. For that I tried that: public function...

Symfony files which are included in CSS are not found when using assetic


css,symfony2,twig,assetic
I'm using Symfony with Twig and I use assetic. The problem is that my CSS file includes other CSS files like that: @import url(ie8.css); @import url(blocks.css); @import url(plugins.css); @import url(app.css); And these files are not found when webpage is displayed. Same happens with fonts and images. How do I solve...

Using crontab to call wget every 5 minutes


php,symfony2,crontab,wget
I am working on a project where the wget and crontab are used to run a process in the background. I have a php file named "Hello.php" that I want to run this every 5 minutes. I have found that if I want to have a cron job run every...

Symfony 2 unable to pass entity repository to form


php,forms,symfony2,runtime-error
I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

Deserializing or parse XML response in Symfony2


php,xml,symfony2,deserialization,jmsserializerbundle
I am calling a API method through cURL and I got this response: <?xml version="1.0" encoding="UTF-8"?> <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload"> <id>75080000002s5siAAA</id> <operation>query</operation> <object>User</object> <createdById>00580000008ReolAAC</createdById> <createdDate>2015-06-23T13:03:01.000Z</createdDate> <systemModstamp>2015-06-23T13:03:01.000Z</systemModstamp> <state>Open</state>...

What is a reliable isnumeric() function for python 3?


python,regex,validation,python-3.x,isnumeric
I am attempting to do what should be very simple and check to see if a value in an Entry field is a valid and real number. The str.isnumeric() method does not account for "-" negative numbers, or "." decimal numbers. I tried writing a function for this: def IsNumeric(self,...

Using JavaScript or JQuery to clear a file upload field if the file selected is not a certain type [duplicate]


javascript,jquery,html,validation,file-upload
This question already has an answer here: Limit file format when using <input type=“file”>? 8 answers I have essentially re-skinned a file-upload form field. <input id="uploadFile" placeholder="Choose File" disabled="disabled" /> <div class="fileUpload btn btn-primary"> <span>Upload</span> <input id="uploadBtn" type="file" class="upload" /> </div> .fileUpload { position: relative; overflow: hidden; margin: 10px;...

With a OneToMany relation between entities, how create the right queryBuilder with Doctrine (on the Inversed Side entity)


php,symfony2,doctrine2,one-to-many,query-builder
I have these 3 entities in my symfony2.6 project: Compteurs.php class Compteurs { /** * @var \PointsComptage * * @ORM\ManyToOne(targetEntity="PointsComptage", inversedBy="compteurs") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="pointscomptage_id", referencedColumnName="id") * }) */ private $pointsComptage; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="ParametresMesure", mappedBy="compteurs") */ private $parametresMesure; ParametresMesure.php: class ParametresMesure { /** * @var Compteurs...

Symfony2 creating and persisting entity relationships


php,mysql,symfony2,doctrine2
I have two entities Skin and Email. I want Email to be a part of the Skin entity, however I can't use the console to update schema automatically right now, and that is probably why I can't get the relationship to work. So I want to store all the Emails...

Symfony/Twig how to render a Route set by anotation?


php,symfony2,routing,twig,url-routing
Let's say I have this code in a controller: <?php namespace Foo\BarBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc; /** * @Mvc\Route("/foo/bar") */ class TestController extends Controller /** * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"}) * @Mvc\Template * * @return view */ public function testAction($id) { return array('test' => $id); } } How...

Store entity from session doesn't work => $em->persist()


php,symfony2,doctrine2
at first: Sorry for my poor english :-) A beginner need help! I have 3 entities/tables: Tables: contact_person id, title, firstname, surname, adress_id address id, street, zip, city, country_id country (fix values) id, name, code 1, Austria, AT 2, Germany, DE ... Entities: /** * ContactPerson * * @ORM\Table(name="contact_person") *...

Update session in symfony2 for shoppingg cart


php,symfony2,symfony-2.1,php-5.3,symfony-2.3
I have the following code : public function addAction(Request $request){ //Get submited data // Get Value from session $sessionVal = $this->get('session')->get('aBasket'); // Append value to retrieved array. $aBasket = $request->request->all(); if(count($sessionVal) > 0) { foreach ($sessionVal as $key=>$value) { if($aBasket['product_id'] == $sessionVal[$key]['product_id']) { $sessionVal[$key]['product_quantity'] = $sessionVal[$key]['product_quantity'] + $aBasket['product_quantity'];...

Logs an entire array using Monolog [closed]


php,symfony2,monolog,symfony-2.6
Is there any way to log an entire array using Monolog? I have been reading several docs but didn't find a way to log the entire array in a readable format, any advice? Docs I've read: Monolog, how to log PHP array into console? http://symfony.com/doc/current/cookbook/logging/monolog.html https://www.webfactory.de/blog/logging-with-monolog-in-symfony2 ...

Seeding fails validation for nested tables (validates_presence_of)


ruby-on-rails,ruby,validation,ruby-on-rails-4,associations
An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

Symfony change validation message globally


php,symfony2,symfony-2.3
Is there a way to change the basic validation error message to one I need for all entities at once? Currently using Yaml config for every entity, but it's not a way. CF\MyBundle\Entity\User: properties: email: - Email: message: e-mail no válido - NotBlank: message: Campo obligatorio username: -NotBlank: message: Campo...

Symfony\Component\Config\Exception\FileLoaderLoadException] error


php,symfony2,twig,swiftmailer
Hi I stumble upon this error everytime I want to run my Symfony application from console. Therefore I am unable to use this symphony app at all. Please help me with your knowledge. [Symfony\Component\Config\Exception\FileLoaderLoadException] Unable to parse at line 9 (near "mailer_transport="gmail"") in /opt/lampp/htdocs/symblog.dev/app/config/parameters.yml (which is being imported from "/opt/lampp/htdocs/symblog.dev/app/config/config.yml")....

ClassNotFoundException Symfony UserBundle


symfony2,fosuserbundle
I'm developping a website on Symfony2, I want to intergrate FOSUserBundle. I am using Doctrine ORM User class. I've followed the installation steps but I got this error: ClassNotFoundException in AppKernel.php line 21: Attempted to load class "FOSUserBundle" from namespace "FOS\UserBundle". Did you forget a "use" statement for another namespace?...

How to validate in database for uniqueness?


ruby-on-rails,validation,ruby-on-rails-4
I am using Rails 4.2 with Ruby 2.1.5. Here is my API table: create_table "apis", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.string "status" t.string "coname" end How do I validate that a user cannot create an API with the same name and same status twice? For...

how to get validated the associated attributes? rails4


ruby-on-rails,validation
I am using rails4. I have a model, lets say human. Human has nested model Man. Man has attributes Name, Address, Number. I am trying to make an api in which i am not able to validate associated attributes. I was able to validate the man by using validates_associated, But...

Set Auth Token manually for different firewall


symfony2
My application has 2 security firewalls "admin" - used by internal staff "account" - used by customers. Previoly I had one action under the account firewall, the action in the controller looks something like this. $user = //get user somehow $token = new UsernamePasswordToken($user, null, 'account', $user->getRoles()); $this->get('security.token_storage')->setToken($token); With this...

jQuery validate equalTo


javascript,jquery,validation
I would like to use jQuery validate() plugin using the equalTo to validate a signature field, basically the signature field must match the first name and last name field, is this possible using the validate() plugin? http://jqueryvalidation.org/equalTo-method/ shows me how to check if it is equal to another input, but...

Unable to configure Symfony (3rd party) bundle


php,symfony2,rss
I am faily new to Symfony and I am trying to setup a third party bundle that reads RSS feeds and then insert them into database. The third party bundle I am trying to use is called rss-atom-bundle After reading the instructions I can get the RSS feeds however I...

How to conditionally invoke spring validators


java,spring,validation
I have a model like below. Existing code already has validations on individual properties. Now I have a requirement to ignore existing validations on billing_country and address if buyer.method is foo. I was thinking I could have a custom validator at buyer level, check for method and invoke validations only...

How adapt the path to the previous and next article


php,symfony2
I am looking for a solution to access in the current article to the previous(<<) or the next article(>>) at the end of the page of an article. I thought to get the current paramater of the url with this : {{ dump(app.request.attributes.get('_route_params')) }} and inject in the path with...

Symfony2/Twig - iterate over select options


php,symfony2,twig
Usual way of displaying select field is to call {{ form_row(form.doctor_service_id, {'attr':{'class':'form-control'}}) }} I would like to perform two things: Check if this field is actually a select field Iterate over every option (value, name). I know how twig iterator works, I just don't know how to access select options...

Setting cookie for AngularJS translate locale using PHP


php,angularjs,symfony2,angular-translate
My app uses Symfony and AngularJS. I have translations some with Symfony itself and some with AngularJS angular-translate. How do I set a cookie or session variable to change language for AngularJS from PHP?

Symfony2: changing the request class and updating the test environment


php,symfony2,request,phpunit
I have modified the base Request class of my application as explained in the accepted answer of this question. It works very well, except when launching my functional tests, I get the following error: Controller "My\Bundle\AppBundle\Controller\MyController::searchAction()" requires that you provide a value for the "$request" argument (because there is no...

Force Uppercase on Symfony2 form text field


php,forms,symfony2
I've inherited a Symfony2 project that has a form built as such: $builder ->add('Status', 'choice', array( 'choices' => array('' => '', 'PASS' => 'PASS', 'FAIL' => 'FAIL', 'INCOMPLETE' => 'INCOMPLETE', 'DROPPED' => 'DROPPED',), 'required' => FALSE, )) ->add('First_Name', 'text', array('label'=>'First Name', 'required' => FALSE)) ->add('Last_Name', 'text', array('label'=>'Last Name', 'required' =>...

MVC HTML Helpers: Get all validation attributes


c#,asp.net-mvc,validation,html-helper
When it comes to making custom helpers, how can we get the value for the validation attributes (client-side validation)? for example the built in helpers do something like this: <label class="control-label " for="Starts">Starts</label> <span class="field-validation-valid text-danger" data-valmsg-for="Starts" data-valmsg-replace="true"></span> <input class="form-control text-box single-line" data-val="true" data-val-date="The field Starts must be a date."...

Setup VPS with a Symfony2 project from git repository


symfony2,vps
I have a: - VPS with LAMP stack - local symfony2 project (git) - bitbucket repository What do I need to do to properly setup my project in the production evironment? Folder structure/permissions? Can I simply clone the repository in the public folder? (I don't think so) P.s. I've already...

Symfony Entity query builder that checks for free spots


php,mysql,symfony2,doctrine2,dql
First off all: I know the title isn't helping, but it's the best I can think of. So I've got two entities in Symfony one is called Team and the other one Slot the Slot entity has a name, a start and end date and all that stuff. Besides that...

Laravel 5 form request validation returning forbidden error


php,validation,laravel,laravel-4,laravel-5
I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php. My set up so far: routes.php: Route::post('clinic/{id}', array('as' => 'postUpdateAddress', 'uses' =>...

C# Validate DataSet filled with DGV data as XML


c#,xml,validation,datagridview,xsd
I want to make a "Save as" button which will validate data from dataGridView with .xsd XML schema before saving it as an XML file. The idea was to save DataTable filled with DGV data as an XML, validate it with .xsd and delete it if the file is valid...

Correct PHP contact form syntax? [duplicate]


php,forms,validation
This question already has an answer here: PHP: “Notice: Undefined variable” and “Notice: Undefined index” 11 answers I am trying to follow a PHP contact form tutorial from here! Seems pretty simple and I'm completely new to PHP. However, when running my project, I get so many "Notice" messages...

Remove automaticaly entity in BD when choice value not selected (or null selected)


php,forms,symfony2,doctrine
I would like to know if symfony/doctrine can manage automaticaly the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null) exemple: I have a PICTURE entity linked to a VOTE...