Error this value is not valid

Symfony version(s) affected: 5.0.1 Description I am getting the weird error description with that hash, with is not very friend human error. I try to google and look at the source at vendor/symfony...

Symfony version(s) affected: 5.0.1

Description

I am getting the weird error description with that hash, with is not very friend human error. I try to google and look at the source at vendor/symfony/form/Extension/Validator/Constraints/Form.php, which I only found a Form contraint called NOT_SYNCHRONIZED_ERROR but no documentation or explanation in docs about which is doing or which cause the origen of this error.

I had a old legacy code inherit from other developer that was using:

$form->handleRequest($request);
$form->submit($request);

At the same time. So submit method probably is not syncronized and raise that error in isValid() form. Should be catched and displayed as global error form in a more friendly way.

footer.html.twig

<div class="col-xl-4 col-md-6 col-lg-4">
						{{ render(controller('App\Controller\FooterNewsletterController::renderNewsletterForm', {'base' : 1})) }}
					</div>

footer_newsletter/index.html.twig

<div class="footer_widget">
							<h3 class="footer_title">Subscribirse</h3>
							<form id="suscriber_footer_form" name="footer_newsletter_type" class="newsletter_form" 
								action="{{ url('newsletter_subscription') }}">
								<input name="email_susbscriber" id="email_susbscriber" type="text" placeholder="Introduce tu email">
								<button name="send_subscriber" id="send_subscriber" type="submit" value="Enviar">Enviar</button>
							</form>
							<p class="newsletter_text">No usaremos tu correo para enviar spam.</p>
						</div>

src/Form/FooterNewsletterType.php

<?php

namespace AppForm;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsEmail;
use SymfonyComponentValidatorConstraintsNotBlank;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;

class FooterNewsletterType extends AbstractType
{
    public const EMAIL_FIELD_NAME    = 'email_susbscriber';
    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder->add(self::EMAIL_FIELD_NAME, EmailType::class, [
                'required' => true,
                'empty_data'  => '',
                'constraints' => [
                    new NotBlank(),
                    new Email(['mode' => 'strict']),
                ],
            ]);
            $builder->add('send_subscriber', SubmitType::class);
            
            $builder->setMethod(Request::METHOD_POST);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true,
            'error_bubbling' => false,
        ]);
    }
    
    public function getBlockPrefix()
    {
        return 'footer_newsletter_type';
    }
}

src/Controller/FooterNewsletterController.php

<?php

namespace AppController;

use AppFormFooterNewsletterType;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationJsonResponse;

class FooterNewsletterController extends AbstractController
{
    /**
     * @Route("/footer/newsletter", name="footer_newsletter")
     */
    public function renderNewsletterForm(Request $request): Response
    {
        $data = [];
        
        return $this->render('footer_newsletter/index.html.twig', [
            $data
        ]);
    }
    
    /**
     * 
     *
     * @Route("/newsletter/suscripcion", name="newsletter_subscription", methods={"POST"})
     */
    public function newsletterSubscribed(Request $request): Response
    {
        $form = $this->createForm(FooterNewsletterType::class, null, ['csrf_protection' => false])->handleRequest($request);
        
        $form->handleRequest($request);
        $form->submit($request); // PROBLEM HERE (second time processed)
            
        if ($request->isMethod('POST') && $request->isXmlHttpRequest()) 
        {

            if ($form->isSubmitted() && $form->isValid())
            {
                [FooterNewsletterType::EMAIL_FIELD_NAME => $email] = $form->getData();
                
                if (empty($email))
                {
                    // Not a spam, save email, etc...
                    //$org = (new Organization())->setName($email);
                    
                    $this->addFlash('success', sprintf('Thank you "%s"! See you later on 🐝️!', 'bla')); /
                }
                else
                {
                    // Spam detected!
                    $warning = sprintf('🐛 SPAM detected: email: "%s", honeypot content: "%s"', $email, 'blo');
                    $this->addFlash('warning', $warning);
                }
                
                return new JsonResponse('Form valid ' . print_r($form->getData(), TRUE), 200);
            }
            else
            {
                $errors = [];
                foreach ($this->getErrors(true) as $error)
                 {

 var_dump((string)$error->getMessage());
var_dump((string)$error->getCause());
var_dump((string)$error->getOrigin());

var_dump((string)$error->getMessageTemplate());
var_dump((string)$error->getMessageParameters());


}

var_dump((string)($this->getErrors(true)));exit;

                $response = new JsonResponse('', 200);
                $response->setData('errors', print_r($errors, TRUE));
                return $response;
            }
            
        }
        
        
    }
}

Javascript

if($( "#suscriber_footer_form" ))
		{
        		$( "#suscriber_footer_form" ).submit(function( event ) 
                {	
                	  event.preventDefault();

                	  var form = $('#suscriber_footer_form')[0]; // You need to use standard javascript object here
                	  var formData = new FormData(form);
                	  
                	  $.ajax({
                        type: "POST",
                        url: $(this).attr("action"),
                        data: formData + '&send_subscriber=true',
                        processData: false,
    					contentType: false,
    					cache: false,
                        success: (data) => 
                        {
                        	console.log('Submission was successful.');
                			console.log(data);
                
                            $('#popup-box-content').html('<p style="text-align: center">Thank you for ' +
                            'subscribing to The Polyglot Developer newsletter!</p>');
                        },
                        error: function (data) {
                            console.log('An error occurred.');
                            console.log(data);
                        },
                    });
                	  
                	  
                	  
                });
         }

Output:

string(24) "This value is not valid."
string(109) "Object(SymfonyComponentFormForm):
    This value is not valid. (code 1dafa156-89e1-4736-b832-419c2e501fca)"

Possible Solution
Detect when submit is called after handleRequest or improve error messaging to be more friendly

Additionally. Using only:

$form->submit($request);

Produces the error also of no syncronized.

Using only:

$form->handleRequest($request);

Will detect the form as NO subbmited.

And using:

$form->handleRequest($request);
$form->submit($request);

Will produce no syncronized.

At some point the form send via ajax is not picking the values after form submition.

I have a problem in my visualforce page, while rerendering the page, by clicking any button/ any request is sent to controller.

Visualforce page is:

apex:page controller="selectController">

<apex:pageblock >
<apex:form >
<apex:pagemessages />
<apex:repeat value="{!setOfSection}" var="section">

<br/>
<apex:pageBlocksection title="{section}">

<apex:variable value="{!mapOfSectionandItsClass[section]}" var="listOfInnerclass"/>

check:
<apex:repeat value="{!listOfInnerclass}" var="Innerclass"><br/>
<apex:selectList value="{!Innerclass.value}" multiselect="true" size="1">
<apex:selectoptions value="{!Innerclass.listOfdropdown}"/>

</apex:selectList>



</apex:repeat>


</apex:pageBlocksection>



</apex:repeat>


<apex:commandButton value="Check" action="{!check}"/>

</apex:form>
</apex:pageblock>

</apex:page>

Controller is:

public class selectController {

    public Map<String,List<InnerClass>> mapOfSectionAndItsClass{get;set;}
    public set<String> setOfSection{get;set;}

    public selectController(){
        mapOfSectionAndItsClass = new Map<String,List<Innerclass>>();
        setOfSection = new set<STring>();

        for(Innerclass__c newContact:[SELECT Name,Low__c,Medium__c,High__c,Section__c from Innerclass__c where section__c!=NULL]){
            List<InnerClass> listOfInnerClass = new List<InnerClass>();
            if(mapOfSectionAndItsClass.containsKey(newcontact.section__c)){
                listOfInnerClass = mapOfSectionAndItsClass.get(newContact.section__c);
            }
            Innerclass newInnerclass = new Innerclass();
            newInnerclass.listOfDropdown= new List<SelectOption>();
            newInnerclass.listOfDropdown.add(new SelectOption(newContact.Low__c,newContact.Low__c));
            newInnerclass.listOfDropdown.add(new SelectOption(newContact .Medium__c,newContact.Medium__c));
            newInnerclass.listOfDropdown.add(new SelectOption(newContact.High__c,newContact.High__c)); 
            listOfInnerClass.add(newInnerclass)                       ;
            mapOfSectionandItsClass.put(newContact.section__c,listOfInnerclass);            
        }

        setOfSection  = mapOfSectionandItsClass.keyset();
    }

    public pageReference check(){
        return NULL;
    }

    public class InnerClass{
        public String value{get;set;}
        public List<selectOption> listOfDropdown{get;set;}
    }

    public class Innerclass2{
        public string section{get;set;}
        public List<Innerclass> listOfInnerclasses{get;set;}
    }


}

Its loading fine with all the Innerclass and its options.

When i click the button, its throwing error as

(Id of the selectList):Validation error: value is not valid

This error is throwing other than last section.

could you please pin point the error in this page/classes, and help me to solve this..

Thanks..

  • Solved Questions
  • This Question

CloudMikeCloudMike

Validation Error: Value is not valid — One Cause/Solution

I recently ran into a problem where a Visualforce page was throwing a cryptic error message related to a custom picklist (apex:selectList).  The complete error was something like:

j_id0:frmSelectProductsServicesw:filterSection:j_id10:j_id15:selectedPF:Validation Error: Value is not valid

After some digging and research here in the forums, testing and a call to Tech Support it seemed the cause and solution for similar problems didn’t quite apply.  I eventually found the solution (in my case) and wanted to share it in hopes that it would help others.

The cause was due to a conflict between the underlying stored data in SFDC and how certain controls behave when rendered to HTML.  In this case, there was a double space embedded in the underlying data between the Z and I in the value Product.Family field (eg. ‘S&U Z  Internal’). 

Background:

  1. For Visualforce controls (ie. apex.outputField, apex.outputText, apex:selectList) and modes (ie. edit and view), every control ultimately must renders as HTML.  Typical HTML rendering behavior suppresses any extra spaces within text.  That is why it is common practice to use the &nbsp to chain multiple spaces together. 
  2. In this case, the underlying stored data in the Product.Family field included a double space:
          ‘S&U Z  Internal’
    however when it was rendered to the screen, the HTML took control and used only a single space:
          ‘S&U Z Internal’
  3. Once the user clicked the submit button to begin the search, the picklist in this case tried to cross-reference the selected value with the actual data that was bound to the control and found no match, thus the cryptic error that was returned — “selectedPF:Validation Error: Value is not valid”.
          ‘S&U Z  Internal’ != ‘S&U Z Internal’

Funny thing is, when the underlying data is rendered in a input textbox (ie. apex.inputText), the double space is displayed.  Once I removed the double space from the underlying data, the error was fixed.

Hopefully this solution helps.

Thanks to Sreenivas Voore in Premiere Tech Support.

You need to sign in to do that.

Dismiss

Hello everybody! I am new both to JSF and JPA and hope you can help me with a problem I couldn’t solve even after several hours of debugging and google searches..

I have 2 entities which are in a ManyToMany relationship:

@Entity
public class TestRun implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToMany(mappedBy=»associatedWithTestRuns»)
private Collection<Tracker> associatedTrackers;
// getters and setters

@Override
public boolean equals(Object object) {

if (!(object instanceof Tracker)) {
return false;
}
Tracker other = (Tracker) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

}
@Entity
public class Tracker implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToMany
private Collection<TestRun> associatedWithTestRuns;

// getters and setters
//id based equals(), etc
}

They model the fact that a TestRun can be associated with several trackers (and viceversa).

I then have 2 Managed Beans (generated by NetBeans 7.0) called respectively TestRunController and TrackerController: each such bean has an aggregation to an Entity. I show here the relevant code for just one of them, as they are almost identical:

@ManagedBean(name = «trackerController»)
@SessionScoped
public class TrackerController implements Serializable {

private Tracker current;
@EJB
private my.TrackerFacade ejbFacade;

public Tracker getSelected() {
if (current == null) {
current = new Tracker();
}
return current;
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false); // Returns an array of SelectItem(Object value => Tracker, String description)
}
@FacesConverter(forClass = Tracker.class)
public static class TrackerControllerConverter implements Converter {

public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
TrackerController controller = (TrackerController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, «trackerController»);
return controller.ejbFacade.find(getKey(value));
}

java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}

String getStringKey(java.lang.Long value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}

public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Tracker) {
Tracker o = (Tracker) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException(«object » + object + » is of type » + object.getClass().getName() + «; expected type: » + TrackerController.class.getName());
}
}
}

I added into the DB a couple of Trackers and finally created a Facelet for the insertion of a TestRun. This facelet uses a selectManyCheckbox which should allow to choose which trackers are associated with a testrun:

<h:outputLabel value=»Tracker» for=»tracker» />
<h:selectManyCheckbox id=»tracker» value=»#{testRunController.selected.associatedTrackers}» title=»Tracker»>
<f:selectItems value=»#{trackerController.itemsAvailableSelectMany}»/>
</h:selectManyCheckbox>

The form gets properly created and displayed and I am even able to create a TestRun record when I don’t select any Tracker. But as soon as I select a Tracker, I get the error «Validation Error: Value is not valid» (I think this should correspond to javax.faces.component.UISelectMany.INVALID).

I read in internet (and in this forum as well) that this problem is sometimes connected with a missing overriding of equals(), but this should not be my case… Furthermore, I noticed (while debugging) that such method gets never invoked after the form is sent. The same happens with TrackerControllerConverter#getAsObject(), which according to several posts should be another cause for the problem…

I am relly confused and hope you can help me..

Bye and… THANKS!

Понравилась статья? Поделить с друзьями:
  • Error this username is already registered please choose another one
  • Error this statement may fall through werror implicit fallthrough
  • Error this server is already on your list ok
  • Error this script needs bsddb3 to be installed
  • Error this script must be started from web server s document root