symfony validation form doesn't call - validation

I'm making a website with symfony2, and i have some troubles with form validaiton. It seems like method "isValid()" on my form is never called :
heres is my form creation :
public function createAction(Request $request)
{
$pro = new Professionnel();
$created=false;
$form = $this->createFormBuilder($pro)
->add("raison_sociale",null,array("label"=>"Raison sociale * : "))
->add("siret",null,array("label"=>"N° SIREN * : "))
->add("nom",null,array("label"=>"Nom *: "))
->add("prenom",null,array(
"label"=>"Prénom *: "
))
->add("adresse",null,array(
"required"=>false,
"label"=>"Adresse : "
))
->add("code_postal","text",array(
"required"=>false,
"label"=> "Code Postal : "
))
->add("ville",null,array(
"required"=>false,
"label"=> "Ville : "
))
->add("tel",null,array("label"=>"Téléphone * : ","required"=>true))
->add("mobile",null,array(
"required"=>false,
"label"=>"Mobile : "
))
->add("fax",null,array(
"required"=>false,
"label"=>"Fax : "
))
->add("email","email",array("label"=>"Email * : "))
->add("username",null,array("label"=>"Login * : "))
->add("password","password",array("label"=>"Mot de passe * : "))
->add("newsletter",null,array("required"=>false,"label"=>"Je souhaite m'inscrire à la newsletter"))
->add("accept","checkbox",array("label"=>" "))
->getForm()
;
if ($request->isMethod("POST"))
{
$form->bind($request);
if ($form->isValid())
{
$em=$this->getDoctrine()->getEntityManager();
$pro=$form->getData();
$encoder = $this->get('security.encoder_factory')->getEncoder($pro);
$pro->setPassword($encoder->encodePassword($pro->getPassword(),$pro->getSalt()));
$em->persist($pro);
$em->flush();
$created=true;
$this->get("session")->getFlashBag()->add("success", "Votre compte a bien été créé. Vous avez reçu un mail confirmant votre inscritpion.");
}
}
return $this->render('OverscanProfessionnelBundle:Front:create.html.twig',array('form'=>$form->createView(),'created'=>$created));
}
and here is my validatio.yml :
webapp\ProfessionnelBundle\Entity\Professionnel:
constraints:
Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: email
message: "L'email est déjà pris"
Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: username
message: "Ce login est déjà pris"
properties:
raison_sociale:
- Valid:
siret:
- Length:
min : 9
max : 9
minMessage: "Le SIREN doit contenir 9 caractères"
maxMessage: "Le SIREN doit contenir 9 caractères"
- Regex:
pattern: "/\d/"
match: true
message: "Le SIREN ne doit pas contenir de lettre"
tel:
- Length:
min : 10
max : 10
minMessage: "Le numéro de téléphone doit contenir 10 chiffres"
maxMessage: "Le numéro de téléphone doit contenir 10 chiffres"
so when i post my form no validation are called but constraints are !
Can someone help me please ?

Take a look at your "app/../config.yml"
You should see something like this :
framework:
...
validation: { enable_annotations: true }
Set it to :
framework:
...
validation: { enabled: true, enable_annotations: true }
And then, your validation.yml should be loaded !

Try adding the data class to your form like this:
$this->createFormBuilder($entity, array(
'data_class' => '\Vendor\YourBundle\Entity\MyEntity',
)
)
// -> add()

Related

As it is referenced in the xpath to a one more view tag

I'm using scrapy framework and I can not load the other data from my analyzed webpage, it has a tag to see more. Could you tell me what you could do about it, thank you.
import scrapy
from scrapy.spiders import CrawlSpider,Rule
from scrapy.linkextractors import LinkExtractor
from prueba1.items import Prueba1Item
from scrapy.exceptions import CloseSpider
class PruebaSpider(CrawlSpider):
name = 'prueba1'
item_count = 0
allowed_domain = ['http://www.abc.com.py/']
start_urls = ['http://www.abc.com.py/buscar/?buscar=Santiago+Pe%C3%B1a'
'http://www.abc.com.py/buscar/?buscar=Santi+Pe%C3%B1a',
'http://www.abc.com.py/buscar/?buscar=santiago+pe%C3%B1a',
'http://www.abc.com.py/buscar/?buscar=santi+pe%C3%B1a']
rules = {
Rule(LinkExtractor(allow =(),canonicalize = True, unique =
True,restrict_xpaths=('//html/body/div/a[#id="load-more"]'))),
Rule(LinkExtractor(allow =(),canonicalize = True, unique =
True,restrict_xpaths=('//div[#class="article"]')),
callback = 'parse_item', follow=True)
}
def parse_item(self, response):
ml_item=Prueba1Item()
ml_item['article'] = response.xpath('normalize-space(//h1)').extract()
ml_item['fecha'] = response.xpath('normalize-
space(//small)').extract()
ml_item['contenido'] = response.xpath('normalize-
space(//p[#class="summary"])').extract()
ml_item['contenido2'] = response.xpath('normalize-
space(//div[#class="text"])').extract()
ml_item['url'] = response.xpath('normalize-
space(//link/#href)').extract()
ml_item['comentarioFacebook'] = response.xpath('normalize-
space(//div[#class="_30o4"]/span/span[#class="_5mdd"])').extract()
self .item_count += 1
if self.item_count > 50:
raise CloseSpider('item_exceeded')
yield ml_item
According to the search results I have more than 4000 results but I can not bring more than 50 with this code.
The contents are loaded dynamically using json in this format:
{
"titulo": "Tuma se suma a Marito",
"copete": "El diputado \u00d3scar Tuma oficializ\u00f3 su respaldo a la candidatura de Mario Abdo Ben\u00edtez a la presidencia, ya que sus reportes indicaron que el candidato de Colorado A\u00f1etet\u00e9 tiene mayor intenci\u00f3n de votos. El 100% de su dirigencia se lo pidi\u00f3, dice. ",
"publicacion": "09-11-2017 08:00",
"imagen": "2017\/10\/02\/el-diputado-scar-tuma-inscribio-ayer-las-precandidaturas-de-su-movimiento-tu-asuncion-en-la-junta-de-gobierno--200750000000-1634915.jpg",
"url": "nacionales\/tuma-se-suma-a-marito-1648202.html",
"autor": "",
"hits": "3163",
"comentarios": "1",
"corte_url": "https:\/\/s3-sa-east-1.amazonaws.com\/assets.abc.com.py\/2017\/10\/02\/_146_162_1542245.jpg",
"corte_width": 146,
"corte_height": 162,
"autor_nombre": null,
"autor_url": "http:\/\/www.abc.com.py\/autor\/-.html",
"total": "4861"
}
Therefore you can get the data in json format directly from the url below without using Xpath or css selector(try open this url in your browser):
http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=0&limit=7&aditional=
I believe it's not difficult to modify the url to get the data you want and put them into your scripts, for example, get 10 items from the second item, just change begin to 2 and limit to 10:
http://www.abc.com.py/ajax.php?seccion=busqueda-avanzada&tipo=4&tipoplant=0&buscar=Santiago+Pe%C3%B1a&desde=&hasta=&seccion-noticia=&temas=&begin=2&limit=10&aditional=

Jython, websphere : Operation getStatsObject not in ModelMBeanInfo

Could you please help me to get the current value of ActiveCount (ThreadPoolModule) in websphere ?
Below you can find my code and the error generated :
perfName = AdminControl.completeObjectName ('name=WebContainer,type=ThreadPool,process=G5-WLS,*')
perfOName = AdminControl.makeObjectName (perfName)
sigs = ['javax.management.ObjectName', 'java.lang.Boolean']
jvmName = AdminControl.completeObjectName ('name=WebContainer,type=ThreadPool,process=G5-WLS,*')
params = [AdminControl.makeObjectName (jvmName), java.lang.Boolean ('false')]
jvmStats=AdminControl.invoke_jmx (perfOName, 'getStatsObject', params, sigs)
ActiveCount=jvmStats.getStatistic( 'ActiveCount').getCurrent()
Error in line 6 :
wsadmin> jvmStats=AdminControl.invoke_jmx (perfOName, 'getStatsObject', params, sigs)
WASX7015E: Exception reçue lors de l'exécution de la commande : " jvmStats=AdminControl.invoke_jmx (perfOName, 'getStatsObject', params, sigs)"; informations sur l'exception :
javax.management.MBeanException
javax.management.ServiceNotFoundException: Operation getStatsObject not in ModelMBeanInfo
Sorry I have found the answer :
perfName = AdminControl.completeObjectName ('type=Perf,process=G5-WLS,*')
perfOName = AdminControl.makeObjectName (perfName)
sigs = ['javax.management.ObjectName', 'java.lang.Boolean']
threadPoolName = AdminControl.completeObjectName ('name=WebContainer,type=ThreadPool,process=G5-WLS,*')
params = [AdminControl.makeObjectName (threadPoolName), java.lang.Boolean ('false')]
jvmStats=AdminControl.invoke_jmx (perfOName, 'getStatsObject', params, sigs)
ActiveCount=jvmStats.getStatistic( 'ActiveCount').getCurrent()
And the result :
wsadmin>print ActiveCount
1

Access to windows server share prompt for credentials on Windows 7

Since I have restarted one of my DC (I have previously check if it owned FSMO roles), windows 7 domain computers ask for credentials to access network shares.
Bellow the prompt Windows, there is an error message about wrong credentials.
I have check the credential store with no success.
No problem with Windows XP clients with same user account.
No error in event log (I have enable the account audit functionnality).
Reboot of file server and clients do nothing.
Thanks for your help.
In addition, we have lot of entries in the event log 4625:
Sujet :
ID de sécurité : NULL SID
Nom du compte : -
Domaine du compte : -
ID d’ouverture de session : 0x0
Type d’ouverture de session : 3
Compte pour lequel l’ouverture de session a échoué :
ID de sécurité : NULL SID
Nom du compte : username
Domaine du compte : domain.local
Informations sur l’échec :
Raison de l’échec : Une erreur s’est produite lors de l’ouverture de session.
État : 0xc000006d
Sous-état : 0x0
Informations sur le processus :
ID du processus de l’appelant : 0x0
Nom du processus de l’appelant : -
Informations sur le réseau :
Nom de la station de travail : computer
Adresse du réseau source : -
Port source : -
Informations détaillées sur l’authentification :
Processus d’ouverture de session : NtLmSsp
Package d’authentification : NTLM
Services en transit : -
Nom du package (NTLM uniquement) : -
Longueur de clé : 0
Cet événement est généré lorsqu’une demande d’ouverture de session échoue. Il est généré sur l’ordinateur sur lequel l’accès a été tenté.
Le champ Objet indique le compte sur le système local qui a demandé l’ouverture de session. Il s’agit le plus souvent d’un service, comme le service Serveur, ou un processus local tel que Winlogon.exe ou Services.exe.
Le champ Type d’ouverture de session indique le type d’ouverture de session qui a été demandé. Les types les plus courants sont 2 (interactif) et 3 (réseau).
Les champs relatifs aux informations sur le processus indiquent quel est le compte et le processus sur le système qui ont demandé l’ouverture de session.
Les champs relatifs aux informations sur le réseau indiquent la provenance de la demande d’ouverture de session distante. Le nom de la station de travail n’étant pas toujours disponible, peut rester vide dans certains cas.
Les champs relatifs aux informations d’authentification fournissent des détails sur cette demande d’ouverture de session spécifique.
- Les services en transit indiquent les services intermédiaires qui ont participé à cette demande d’ouverture de session.
- Le nom du package indique quel a été le sous-protocole qui a été utilisé parmi les protocoles NTLM.
- La longueur de la clé indique la longueur de la clé de session générée. Elle a la valeur 0 si aucune clé de session n’a été demandée.
I have found the solution.
This is the technet link that addresses this problem.
I have installed on my DC the KB3002657-v2 and things are back to normal.
Thx.

shoulda-matcher error validating length_of

I'm writing some specs for my User model but the tests are not passing. I'm fallowing this from the github page of the gem without success. This is my code:
validates :phone, numericality: { only_integer: true }, allow_blank: true, length: { is: 7 }
validates :mobile, numericality: { only_integer: true }, allow_blank: true, length: { is: 10 }
and my specs
it { should ensure_length_of(:phone).is_equal_to(7) }
it { should ensure_length_of(:mobile).is_equal_to(10) }
This validations should only run during the update process.
The errors:
Did not expect errors to include "longitud errónea (debe ser de 7 caracteres)" when telefono is set to "xxxxxxx", got error: longitud errónea (debe ser
de 7 caracteres)
Did not expect errors to include "longitud errónea (debe ser de 10 caracteres)" when celular is set to "xxxxxxxxxx", got error: longitud errónea (debe s
er de 10 caracteres)
FYI: I've set Spanish Locales; I think this is the cause
Hope someone could help me. Thanks is advance
I think you got the error because shoulda_matcher does not expect that length: { is: 7 } is used with numericality.
PS as for me - it is strange to use numeric for phone numbers, you can use string and use validates with format to be sure in validness data. For example email validation here

use symfony form validator for Bulk-Insert

i receive an CSV File from the User and I want to insert it into the Database. I want to use the Form Validation:
$pf = new ProductForm();
$old_memory_usage = 0;
while($data = $csvreader->read())
{
$mem = memory_get_usage() / 1024;
echo "Memory-Usage: " . $mem . " KB; Mem-Diff: " . $mem - $old_memory_usage . "\n";
$old_memory_usage = $mem;
$p = new Product();
$p->fromArray($data);
$pf->bind($p->toArray(), array());
if($pf->isValid())
{
$p->save();
}
else
{
//display error message to the user
}
}
This works fine when isValid() returns true. The Memory Difference is 0 KB. But if there is an Error in the "form" the memory-difference is 6-7 KB. So I get an allowed_memory error when the CSV-File is very huge.
I tryed to free the form like:
unset($pf)
$pf = null;
$pf = new ProductForm();
no success. It is just worse!
ans ideas?
thx!
You can disable doctrine profiler in your databse yml:
dev:
doctrine:
class: sfDoctrineDatabase
param:
profiler: false

Resources