Symfony : Form : get Key Children - symfony

How can I get children → elements key?
(see screenshot, I want to access and modify 0, 3, 2)
I need this for add error on collection form.
Thank you!
[EDIT]
foreach ($form->getData()->getCategs() as $d) {
if ($d->getNbHeures() > 8){
$form->get('categs')->get($nb)->get('nbHeures')->addError(new FormError('Vous ne pouvez pas saisir plus de 8h.'));
$nbErreur++;
}
}
I need to get $nb.
[EDIT]
I founded this, but I don't know if it's the best solution:
foreach ($form->get('categs') as $k => $d) {
if ($d->getData()->getNbHeures() > 8) {
$form->get('categs')->get($k)->get('nbHeures')->addError(new FormError('Vous ne pouvez pas saisir plus de 8h.'));
$nbErreur++;
}
}

Related

Xquery variable not set

In my Xquery 3.1 module I have imported my " global variables" through a module import, one of which ($globalvar:MSGS) contains an XML document that I generally have no problems accessing through reference to the variable. For example this
$globalvar:MSGS//vocab[#xml:id="warning"]
will return
<vocab xml:id="warning">
<span lang="en">Warning! Your changes (OBJECTID) could not be saved!</span>
<span lang="fr">Attention, vos modifications (OBJECTID) n’ont pas pu être sauvegardées !</span>
</vocab>
But the following is returning an error err:XPDY0002 variable '$msg' is not set pointing to line 7-8:
1. let $collid := $mydoc//collection-id/text()
2. let $errtitle :=
3. <msg-error-title>
4. {
5. let $msg := $globalvar:MSGS/id("warning")/span
6. return
7. <en>{replace($msg[#lang="en"]/text(),"OBJECTID",$collid)}</en>,
8. <fr>{replace($msg[#lang="fr"]/text(),"OBJECTID",$collid)}</fr>
9. }
10. </msg-error-title>
11. return $errtitle
But if I remove the inner let ... return and make direct reference to $globalvar:MSGS like below, there are no errors:
let $collid := $mydoc//collection-id/text()
let $errtitle :=
<msg-error-title>
{
<en>{replace($globalvar:MSGS/id("warning")/span[#lang="en"]/text(),"OBJECTID",$collid)}</en>,
<fr>{replace($globalvar:MSGS/id("warning")/span[#lang="fr"]/text(),"OBJECTID",$collid)}</fr>
}
</msg-error-title>
return $errtitle
I don't understand why $msg isn't set in the first example? Is there an alternative?
added test
let $collid := "FOOID"
let $xml :=
<vocab xml:id="warning">
<span lang="en">Warning! Your changes (OBJECTID) could not be saved!</span>
<span lang="fr">Attention, vos modifications (OBJECTID) n’ont pas pu être sauvegardées !</span>
</vocab>
let $errtitle :=
<msg-error-title>
{let $msg := $xml/id("warning")/span
return
<en>{replace($msg[#lang="en"]/text(),"OBJECTID",$collid)}</en>,
<fr>{replace($msg[#lang="fr"]/text(),"OBJECTID",$collid)}</fr>
}
</msg-error-title>
return $errtitle
Your test case fails in Saxon with
Static error
XPST0008 Unresolved reference to variable $msg
The problem is that "," doesn't bind as closely as you think, so you need extra parens around the return expression:
return (
<en>{replace($msg[#lang="en"]/text(),"OBJECTID",$collid)}</en>,
<fr>{replace($msg[#lang="fr"]/text(),"OBJECTID",$collid)}</fr>
)

Drupal commerce save personnal field

I'm new to Drupal Commerce ...
I added two fields in the order table :
field_date_de_livraison (text) and field_info_comp_cmde (long text).
In a personalized pane , I try to save the entered values ​​with this code :
function pane_date_livraison_checkout_form_submit($form, &$form_state, $checkout_pane, $order) {
if (!empty($form_state['values'][$checkout_pane['pane_id']])) {
$Date_saisie = $form_state['values'][$checkout_pane['pane_id']];
if (!empty($Date_saisie['date_livraison'])) {
$Date_sauvegarde = new DateTime($Date_saisie['date_livraison']);
$Date_sauvegarde = $Date_sauvegarde->format('d/m/Y');
$order->field_date_de_livraison = $Date_sauvegarde;
}
if (!empty($Date_saisie['info_comp'])) {
$order->field_info_comp_cmde = $Date_saisie['info_comp'];
}
}
dpm($order, "RETURN_SUBMIT", $type = 'status');
}
With dpm , I see the values ​​assigned to variables , but then they are not saved to the table?
Thank's for your answers !

Get content of an ArrayCollection

I would like to upgrade my symfony 2 project from 2.3 to 2.7 LTS version. I have a problem in a repository to get result of a query. In 2.3, this query give me something :
public function findProtectedPublications( $steps, $start, $end)
{
$query= $this->getEntityManager()
->createQueryBuilder()
->select('d.pubRefs')
->from('ImpressionDemandBundle:Event', 'h')
->innerJoin('h.demand','d')
->where('d.protectedPublications = :pub')
->setParameter('pub', 1 )
->andWhere('h.date >= :start')
->setParameter('start', $start )
->andWhere('h.date <= :end')
->setParameter('end', $end )
->andWhere('h.stepId in (:steps)')
->setParameter('steps', $steps )
->orderBy('d.id','ASC')
->getQuery();
$results = $query->getResult();
$publications = array();
if ($results && ! empty ($results)){
foreach($results as $result){
$pubs = $result['pubRefs'];
if ($pubs && ! empty($pubs)){
foreach($pubs as $pub){
$publications[] = $pub;
}
}
}
}
return $publications;
}
But this code doesn't work in earlier version because $pubs variable in an ArrayCollection. So I changed the end of my code with this :
$results = $query->getResult();
$publications = array();
if ($results && ! empty ($results)){
foreach($results as $result){
$pubs = $result['pubRefs'];
var_dump($pubs);
if (! $pubs->isEmpty()){
$arrayPubs = $pubs->toArray();
foreach($arrayPubs as $pub){
$publications[] = $pub;
}
}
}
}
return $publications;
In this part, when I dump the $pubs variable, I have :
object(Doctrine\Common\Collections\ArrayCollection)#131 (2) {
["elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
NULL
["_elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
array(1) {
[0]=>
object(Impression\DemandBundle\Entity\Publication)#125 (5) {
["editor":"Impression\DemandBundle\Entity\Publication":private]=>
string(24) "Journal Le Monde 4-10-13"
["coauthors":"Impression\DemandBundle\Entity\Publication":private]=>
string(12) "Machin Machin"
["title":"Impression\DemandBundle\Entity\Publication":private]=>
string(57) "La tragédie de Lampedusa: s"émouvoir, comprendre, agir."
["nbPages":"Impression\DemandBundle\Entity\Publication":private]=>
float(1)
["nbCopies":"Impression\DemandBundle\Entity\Publication":private]=>
float(40)
}
}
}
So it seems that there are elements in this ArrayCollection, but the test $pubs->isEmpty() gives a true result, so I have nothing in $publications array.
Edit: In fact, the problem seems to be due to my data in the database : for an object previous from my upgrade, I have something like this in the database :
O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:54:"Doctrine\Common\Collections\ArrayCollection_elements";a:1:{i:0;O:42:"Impression\DemandBundle\Entity\Publication":5:{s:50:"Impression\DemandBundle\Entity\Publicationeditor";s:5:"BREAL";s:53:"Impression\DemandBundle\Entity\Publicationcoauthors";s:5:"MONOT";s:49:"Impression\DemandBundle\Entity\Publicationtitle";s:18:"USA Canada mexique";s:51:"Impression\DemandBundle\Entity\PublicationnbPages";d:150;s:52:"Impression\DemandBundle\Entity\PublicationnbCopies";d:150;}}}
and this gives the error.
For a object add after my upgrade, I have something like this in the database :
O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:53:"Doctrine\Common\Collections\ArrayCollectionelements";a:1:{i:0;O:42:"Impression\DemandBundle\Entity\Publication":5:{s:50:"Impression\DemandBundle\Entity\Publicationeditor";s:8:"dfg dfgd";s:53:"Impression\DemandBundle\Entity\Publicationcoauthors";s:7:"dfg dfg";s:49:"Impression\DemandBundle\Entity\Publicationtitle";s:5:"fdg d";s:51:"Impression\DemandBundle\Entity\PublicationnbPages";d:5;s:52:"Impression\DemandBundle\Entity\PublicationnbCopies";d:3;}}}
and the function findProtectedPublications() works without errors.
The difference between the two versions is ArrayCollection_elements for the first and ArrayCollectionelements for the second.
To correct this data, I tried with
UPDATE demand SET pub_refs = REPLACE (pub_refs, "ArrayCollection_elements', 'ArrayCollectionelements')
but this doesn't work because of special chars. Trying with
UPDATE demand SET pub_refs = REPLACE (pub_refs, "ArrayCollection�_elements', 'ArrayCollection�elements')
doesn't work better. How can I correct this data ?
Doctrine can populate results as an Array instead of an ArrayCollection, simply change the getResult() call to:
$results = $query->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
This would be the most efficient way to complete your task however you could also use ArrayCollection's built-in toArray() method to convert its own data to array format:
$publications = $results->toArray();
As the problem seems to be due to a change in the storage of ArrayCollection in database between 2.3 and 2.7 version of symfony, I created an line command to update these in database.

sqlite3_step() does not return SQLITE_OK

I have a data base, this is in my proyect how a file localDB.db I want update some information of a table in this since my aplication`s code the method I use is the follow:
-(void)establecePerfil:(int)idPerfil{
while ([Utilidades consultaCargandoDatosDB]) {
[NSThread sleepForTimeInterval:1.0];
}
[Utilidades cargandoDatos:YES];
//perfil = [Perfil getInstance];
[self cargarBaseDeDatos];
NSLog(#"entre en establecer perfik");
sqlite3 *dataBase;
sqlite3_stmt *sentencia;
if(sqlite3_open([self.dataBasePath UTF8String], &dataBase)==SQLITE_OK){
NSLog(#"entre en establecer perfik 2");
NSString *sql = [NSString stringWithFormat:#"UPDATE perfiles SET \"seleccionado\"= 1, \"completado\"=0 WHERE \"id\"= %d", idPerfil];
if(sqlite3_prepare_v2(dataBase, [sql UTF8String], -1, &sentencia, NULL)==SQLITE_OK){
sqlite3_reset(sentencia);
if(sqlite3_step(sentencia)==SQLITE_OK){
NSLog(#"set profile OK");
}
else{
// NSAssert1(0, #"Error while selecting. '%s'", sqlite3_errmsg(dataBase));
NSLog( #"Save Error: %s", sqlite3_errmsg(dataBase) );
NSLog(#"%i", sqlite3_extended_errcode(dataBase));
NSLog(#"%i",sqlite3_errcode(dataBase));
}
}
sqlite3_finalize(sentencia);
}else{
NSLog(#"No se ha abierto la base de datos");
}
sqlite3_close(dataBase);
[Utilidades cargandoDatos:NO];
}
I think, I have the problem in sqlite3_step(sentencia) because code error that appear after of else condition is 101 referencing to SQLITE_DONE so I don`t know that means this.
The documentation says that SQLITE_DONE is correct (and SQLITE_OK would not be).

Programmatically add an invoice to Dynamics AX 2009

I'm am pretty new to Dynamics AX 2009 and since I haven't really found the way to solve what I'm doing I decided to ask here.
I have a requirement to post(?) an invoice through X++.
I already found this HOWTO: Facturación selectiva de líneas en Dynamics AX and even though it's in Spanish I think you will get the idea.
Here is the code I modified from the link:
static void JAEE_PurchFormLetter(Args _args)
{
Num _invoiceNum; // Núm. factura
TransDate _invoiceDate; // Fecha factura
MyPurchFormLetter purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
PurchParmUpdate purchParmUpdate;
PurchParmTable purchParmTable;
PurchParmLine purchParmLine;
TradeLineRefId tableRefId;
PurchTable purchTable;
PurchLine purchLine;
;
ttsbegin;
_invoiceNum = 'Facbyjob';
_invoiceDate = str2date('14-01-2013', 123);
purchTable = PurchTable::find('00000019_062'); // Primer pedido
// Inizializar purchFormLetter con el primer pedido
purchFormLetter.parmCallerTable(purchTable);
purchFormLetter.callInitParmPurchTable(purchTable);
purchFormLetter.proforma(false); // Proforma: NO (Registrar: SI)
purchFormLetter.enableUpdateNowField(true); // Actualizar ahora: SI
purchFormLetter.printFormLetter(false); // Imprimir: NO
purchFormLetter.transDate(_invoiceDate); // Fecha de factura
// Inizializar purchParmUpdate con el primer pedido
purchParmUpdate.clear();
purchParmUpdate.initValue();
purchParmUpdate.ParmId = purchFormLetter.parmId();
purchParmUpdate.SumBy = AccountOrder::Account; // Agrupar por cliente
purchParmUpdate.SumNum = _invoiceNum; // Núm. Factura
purchParmUpdate.SpecQty = PurchUpdate::All; // Actualizar: Todo
purchParmUpdate.DocumentStatus = DocumentStatus::Invoice; // Tipo documento: Factura
purchParmUpdate.Proforma = NoYes::No; // Proforma: NO
purchParmUpdate.SumIncludePending = NoYes::No; // Incluir pendiente: NO
if (purchParmUpdate.validateWrite())
purchParmUpdate.insert();
else
throw Exception::Error;
purchFormLetter.purchParmUpdate(purchParmUpdate);
purchFormLetter.parmParmTableNum(purchParmUpdate.SumNum);
// Tabla temporal, se crea un registro de cabecera del primer pedido (sólo uno)
purchParmTable.clear();
purchParmTable.TableRefId = FormLetter::getTableRef();
purchFormLetter.createParmTable(purchParmTable, purchTable);
if (purchParmTable.validateWrite())
purchParmTable.insert();
else
throw Exception::Error;
tableRefId = purchParmTable.TableRefId;
// BEGIN - LINEAS
// - Repetir para cada línea que se quiera facturar y para cada una y
// - asignar las variabies purchTable y purchLine según proceda
purchParmLine.clear();
purchParmLine.initValue();
// Ajustar cantidades según necesidades
// Catnidades de compra
[purchParmLine.ReceiveNow,
purchParmLine.RemainBefore,
purchParmLine.RemainAfter] = purchFormLetter.qtyPurch(purchLine, naReal());
// Cantidades de inventario
[purchParmLine.InventNow,
purchParmLine.RemainBeforeInvent,
purchParmLine.RemainAfterInvent] = purchFormLetter.qtyInvent(purchLine, naReal());
if (purchParmLine.ReceiveNow)
{
purchParmLine.ParmId = purchParmUpdate.ParmId;
purchParmLine.initFromPurchLine(purchLine);
purchParmLine.setLineAmount();
purchParmLine.TableRefId = tableRefId;
if (purchParmLine.validateWrite())
purchParmLine.insert();
else
throw Exception::Error;
}
// END - LINEAS
// Registrar!
purchFormLetter.reArrangeNow(false); // No organizar
purchFormLetter.run();
ttscommit;
}
My question is in this line: purchFormLetter.callInitParmPurchTable(purchTable);.
Why should initParmPurchTable() be called from within a derived class of PurchFormLetter?
And also, how to accomplish this? I tried declaring my own class MyPurchFormLetter which extends PurchFormLetter, adding the callInitParmPurchTable() method but compiler tells me that the object does not have the method when I try to run the code.
It reads:
Error al ejecutar código: Object objeto no tiene el método 'callInitParmPurchTable'.
EDIT:
What I have done is add the method into the class, in such a way that callInitParmPurchTable() is part of the object. But I am leaving the question open since I don't think this is the right approach.
Have you modified PurchFormLetter::construct(DocumentStatus::Invoice); to return a MyPurchFormLetter?
Also look into the "compile forward" feature
I have found out the following:
It is correct to make a class that inherits from PurchFormLetter and implement there the method callInitParmPurchTable() which obviously is the one that executes initParmPurchTable().
Most likely the one part that I had been missing was to compile MyPurchFormLetter so that the compiler could tell the method existed.

Resources