Doctrine 2 update of more than one column? - doctrine-orm

How can I combine these two updates on the same tuple into one operation?
$q = $this->em->createQuery('update \Entity\UserEn u set u.last = :last where u.name = :name');
$q->setParameters( array(
'last' => new \DateTime($newLast),
'name' => $theUser,
));
$q->getResult();
$q = $this->em->createQuery('update \Entity\UserEn u set u.contribution = :contribution where u.name = :name');
$q->setParameters( array(
'contribution' => $this->rContributionUser($theUser),
'name' => $theUser,
));
$q->getResult();
I think one update is cheaper than 2 updates.

Use a comma to separate the two assignments:
$q = $this->em->createQuery('update \Entity\UserEn u set u.last = :last, u.contribution = :contribution where u.name = :name');
$q->setParameters( array(
'last' => new \DateTime($newLast),
'contribution' => $this->rContributionUser($theUser),
'name' => $theUser,
));
$q->getResult();

Related

Drupal 8 how to alter paragraph form?

In drupal 8, I'm using paragraph in node. It's working fine but I got stuck to alter paragraph form. I want to hide one field on base of other field value.
Please help if somebody worked it on before
I found below code helpful and fixed my problem. I hope it will be useful for others also.
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
// $entity_form['#bundle'] paragraph machine name
if($entity_form['#entity_type'] == 'paragraph' && $entity_form['#bundle'] == 'location'){
$parents = $entity_form['#parents'];
$identifier = $parents[0].'['.implode('][', array_slice($parents, 1)).']';
$entity_form['field_dropoff_time']['#states'] = array(
'visible' => array(
'select[name="'. $identifier .'[field_camp_location_type]"]' => ['value' => 1]
),
);
$entity_form['field_pickup_time']['#states'] = array(
'visible' => array(
'select[name="'. $identifier .'[field_camp_location_type]"]' => ['value' => 1]
),
);
}
}

Self Join Query Doctrine 2 Zendframework 2

I am using Doctrine 2 ORM, Zendframework 2
Entity attribute in Role Entity look like this
/**
*
* #ORM\Column(type="string")
*/
protected $name;
/**
*
* #ORM\OneToMany(targetEntity="\Application\Entity\Role", mappedBy="parent")
*/
protected $children;
/**
*
* #ORM\ManyToOne(targetEntity="\Application\Entity\Role", inversedBy="children")
*
*/
protected $parent;
Mysql Table look like this.
Result I am looking for is an array.
One thing is critical, Any entry in array before apprearing in value must be added as key,
So order is very important.
i.e [site-manager] => guest can't come as first entry(0 index) if [guest] => will not exist before it becaause guest(value) does not exist in array as key
so [guest] => will come first even if it is entered as second record in table
Array(
[guest] =>
[site-manager] => guest
[company-manager] => site-manager
[member] => guest
[staff] => member
[internalstaff] => member
[sales] => staff
[manager] => sales,internalstaff
[admin] => manager
)
I am running this code in my controller which is returning empty array
$qb = $objectManager->createQueryBuilder();
$qb->select('r, p')
->from('\Application\Entity\Role', 'r')
->innerJoin('r.parent','p', 'with','p.id = r.id')
//->where('b.id = ?1')
->orderBy('r.id', 'ASC');
$data = $qb->getQuery()->getArrayResult();
Any help will be appreciated
One solution could be
$qb = $objectManager->createQueryBuilder();
$qb->select('r.name', 'c.name as children')
->from('\Application\Entity\Role', 'r')
->join('r.parent','c');
$data = $qb->getQuery()->getArrayResult();
$refine = array();
foreach ($data as $v)
{
if(is_array($v))
{
if(array_key_exists($v["children"], $refine)){
$refine[$v["name"]][] = $v["children"];
} else {
$refine[$v["children"]] = array();
$refine[$v["name"]][] = $v["children"];
}
}
}
print_r($refine);
Will return following
Array
(
[guest] => Array
(
)
[site-manager] => Array
(
[0] => guest
)
[company-manager] => Array
(
[0] => site-manager
)
[member] => Array
(
[0] => guest
)
[staff] => Array
(
[0] => member
)
[internalStaff] => Array
(
[0] => member
)
[sales] => Array
(
[0] => staff
)
[manager] => Array
(
[0] => internalStaff
[1] => sales
)
[admin] => Array
(
[0] => manager
)
)
You can use implode function if you wish to flatten inner array

ZF2 - set selected value on Select Element

I've a problem with dropdown list with Zend Framework 2 & Doctrine.
I would put the "selected" attribute on my dropdown list but all options pass to selected
My code :
Controller :
public function editAction()
{
// get error message during addAction
$this->layout()->setVariable("messageError", $this->flashMessenger()->getErrorMessages());
$auth = $this->getAuthService();
if ($auth->hasIdentity()){
$builder = new AnnotationBuilder();
// Get id of StaticContent
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
$this->flashMessenger()->addErrorMessage("Aucun plan choisi !");
return $this->redirect()->toRoute('admin/plans');
}
$plan = $this->getEntityManager()->getRepository("Admin\Entity\Plan")->find((int)$id);
$form = $builder->createForm($plan);
// Find options for Localite list (<select>)
$localites = $this->getEntityManager()->getRepository("Admin\Entity\Localite")->getArrayOfAll();
$form->get('localiteid')->setValueOptions($localites);
$form->get('localiteid')->setValue("{$plan->getLocaliteid()->getId()}");
// Find options for TypePlan list (<select>)
$typesPlan = $this->getEntityManager()->getRepository("Admin\Entity\TypePlan")->getArrayOfAll();
$form->get('typeid')->setValueOptions($typesPlan);
$form->get('typeid')->setValue("{$plan->getTypeid()->getId()}");
// Options for Statut list (<select>)
$form->get('statut')->setValueOptions(array('projet'=>'Projet', 'valide'=>'Validé'));
$form->get('statut')->setValue($plan->getStatut());
$form->setBindOnValidate(false);
$form->bind($plan);
$form->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Modifier',
'id' => 'submitbutton',
'class' => "btn btn-primary"
),
));
$request = $this->getRequest();
if ($request->isPost()) {
[...]
}
}
With
$localites = $this->getEntityManager()->getRepository("Admin\Entity\Localite")->getArrayOfAll();
$form->get('localiteid')->setValueOptions($localites);
i populate my dropdown correctly, normally with
$form->get('localiteid')->setValue("{$plan->getLocaliteid()->getId()}");
just set "selected" on option defined by :
$plan->getLocaliteid()->getId()
So why all options are selected in my dropdown ?!
Information : It's the same for typeId but no Statut
It's probably not working because of the curly braces. According to the PHP documentation
Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.
This is also unnecessary when using setValue. ZF2 will convert it to a string when formatting it in the view.
When you create the arrays to pass to setValueOptions() you should make it an associative array of arrays with the following values:
$form->get('select')->setValueOptions(array(
'field' => array(
'value' => 'value_of_the_option',
'label' => 'what is displayed',
'selected' => true,
),
));
Which ever of the fields has the selected option set to true will be the default selection in the form element.
Personally i don't know if getArrayOfAll() such function exists, i assume that you are correctly passing array to FORM,
I think you should be doing something like this to set value.
$form->get('localiteid')->setValue($plan->getLocaliteid()->getId());
But Since you are populating DROP down i guess this approach will not work best with Drop Down. You need to do something like this
$form->get('localiteid')->setAttributes(array('value'=>$plan->getLocaliteid()->getId(),'selected'=>true));
I've found a bug ?!
$plan = $this->getEntityManager()->getRepository("Admin\Entity\Plan")->find((int)$id);
$idLocalite = 18;//(int)$plan->getLocaliteid()->getId();
$idTypePlan = 2;//(int)$plan->getTypeid()->getId();
When i'm using $plan->getLocaliteid()->getId(); or $plan->getTypeid()->getId() to pass parameter into Repository method getArrayOfAll($idLocalite)
LocaliteRepository.php :
class LocaliteRepository extends EntityRepository {
public function getArrayOfAll($currentLocaliteId) {
$result = $this->_em->createQuery("SELECT l.nom, l.localiteid FROM Admin\Entity\Localite l ORDER BY l.nom")->getArrayResult();
$localite = array();
foreach($result as $loc) {
if ($currentLocaliteId == $loc['localiteid']) {
$localite[$loc['localiteid']] = array(
'value' => $loc['localiteid'],
'label' => $loc['nom'],
'selected' => true,
);
} else {
$localite[$loc['localiteid']] = array(
'value' => $loc['localiteid'],
'label' => $loc['nom'],
'selected' => false
);
//$localite[$loc['localiteid']] = $loc['nom'];
}
}
return $localite;
}
}
So, if i'm using $idLocalite = 18 instead of $idLocalite = (int)$plan->getLocaliteid()->getId() only wanted option are selected. Why ?!

Add Netsuite Sales order items

I am getting this type of error:
=> i am getting error in the integration of the netsuite.
In sales order add the items in the netsuite so there are some error is define in above section my code is below please see the code add how to solve this problem.
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERRORi am gatting this type of error please help me
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERROR
my code is
include('NetSuiteService.php');
$service = new NetSuiteService();
if($order_items->netsuitid > 0){
$internal_Id = $order_items->netsuitid;
$emailCustomer = $order_items->user_email;
}
else{
$customer_Info = $order->get_customer_info($order->user_id);
$customer_information = array();
foreach($customer_Info as $customer_key => $customer_value){
if($customer_value->meta_key == 'first_name'){
$customer_information['first_name'] = $customer_value->meta_value;
}
if($customer_value->meta_key == 'last_name'){
$customer_information['last_name'] = $customer_value->meta_value;
}
}
$customer_information['email'] = $customer_Info->user_email;
//Add customer into net suit integration
$service = new NetSuiteService();
$customer = new Customer();
$customer->lastName = $customer_information['last_name'];
$customer->firstName = $customer_information['first_name'];
$customer->companyName = 'Company Name';
$customer->phone = '2222222222';
$customer->email = $customer_information['email'];
$emailCustomer = $customer_information['email'];
$request = new AddRequest();
$request->record = $customer;
$addResponse = $service->add($request);
if (!$addResponse->writeResponse->status->isSuccess) {
echo "You are already Registered with Netsuit.";
}
else {
$internal_Id = $addResponse->writeResponse->baseRef->internalId;
$order->insert_Customer($internal_Id,$order->user_id);
}
//End customer into net suit integration
}
//Add Product Information
/*$items = array();
foreach ( $order_items as $item_id => $item ) {
$itemRef = new nsRecordRef(array('internalId'=>$internal_Id));
$qty = $item['qty'];
if($item['type'] == 'line_item'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
if($item['type'] == 'fee'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
$SalesOrderItem->setFields($salesOrderItemFieldArray);
$items[] = $SalesOrderItem;
}
$salesOrderItemList = new nsComplexObject("SalesOrderItemList");
$salesOrderItemList->setFields(array(
"item" => $items
));
$salesOrderFields = array(
"orderStatus" => $order->status,
"entity" => '',
"getAuth" => true,
"shippingCost" => $order->order_shipping,
"shipMethod" => $order->payment_method,
"toBeEmailed" => true,
"email" => $emailCustomer,
"itemList" => $salesOrderItemList
);*/
$so = new SalesOrder();
//created Date
//$so->createdDate = $order->order_date;
//entity
$so->entity = new RecordRef();
$so->entity->internalId = $internal_Id;
$so->entity->name = $order->order_custom_fields['_billing_company'][0];
//Transaction Id
//$so->tranId = $order->order_custom_fields['Transaction ID'][0];
//Transaction Paid Date
//$so->tranDate = $order->order_custom_fields['_paid_date'][0];
//Source
$so->source = 'littlecrate';
//Created From
$so->createdFrom = 'littlecrate.com';
//Currency Name
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->currency = $order->order_custom_fields['_order_currency'];
$so->currencyName = $geoplugin->countryName;
$so->currency = $order->order_custom_fields['_order_currency'][0];
//Discount
$so->discountRate = $order->order_custom_fields['_order_discount'][0];
//Tax
$so->taxRate = $order->order_custom_fields['_order_tax'][0];
//email
$so->email = $order->billing_email;
//Status
//$so->orderStatus = $order->status;
//Billing Address
$so->billAddressList = array(
'billFirstname' => $order->order_custom_fields['_billing_first_name'][0],
'lastname' => $order->order_custom_fields['_billing_last_name'][0],
'billAddressee' => $order->order_custom_fields['_billing_address_1'][0],
'billAddr1' => $order->order_custom_fields['_billing_address_2'][0],
'billCountry' => $order->order_custom_fields['_billing_country'][0],
'billState' => $order->order_custom_fields['_billing_state'][0],
'billZip' => $order->order_custom_fields['_billing_postcode'][0],
'billPhone' => $order->order_custom_fields['_billing_phone'][0],
'billEmail' => $order->order_custom_fields['_billing_email'][0]);
//Shipping Address
$so->shipAddressList = array(
'shipFirstname' => $order->order_custom_fields['_shipping_first_name'][0],
'shipLastname' => $order->order_custom_fields['_shipping_last_name'][0],
'shipAddressee' => $order->order_custom_fields['_shipping_address_1'][0],
'shipAddr1' => $order->order_custom_fields['_shipping_address_2'][0],
'shipCity' => $order->order_custom_fields['_shipping_city'][0],
'shipState' => $order->order_custom_fields['_shipping_state'][0],
'shipZip' => $order->order_custom_fields['_shipping_postcode'][0],
'shiplPhone' => $order->order_custom_fields['_billing_phone'][0],
'shipEmail' => $order->order_custom_fields['_billing_email'][0]);
//Ship Date
//$so->shipDate = $order->order_custom_fields['Transaction ID'][0];
//Shipping Method
$so->shipMethod = $order->shipping_method;
//Shipping Charges
$so->shippingCost = $order->order_shipping;
//Shipping Tax Rate
$so->shippingTax1Rate = $order->order_shipping_tax;
//Payment Method
$so->paymentMethod = $order->payment_method;
//Sub Total
//$so->subTotal = $order->order_total;
//Discount Total(Cart Total)
//$so->discountTotal = $order->cart_discount;
//Tax Total
//$so->taxTotal = $order->order_tax;
//Total
//$so->total = $order->order_total;
//Product Listing
$arrItemsList = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
if($valueProduct['type'] == 'line_item'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
if($valueProduct['type'] == 'fee'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
$i++;
}
//print_r($arrItemsList);
$so->itemList->item = $arrItemsList;
/*$so->itemList = new SalesOrderItemList();
$soi = new SalesOrderItem();
$soi->item = new RecordRef();
$soi->item->internalId = 15;
$soi->quantity = 3;
$soi->price = new RecordRef();
$soi->price->internalId = $id;
$soi->amount = 55.3;
$so->itemList->item = array($soi);*/
$request = new AddRequest();
$request->record = $so;
//print_r($request);
$addResponse = $service->add($request);
print_r($addResponse);
exit;
if (!$addResponse->writeResponse->status->isSuccess) {
echo "ADD ERROR";
} else {
echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
}
+
I Complited Using The Help Of Saqib,
http://stackoverflow.com/users/810555/saqib
He is The Great Developer And Regarding Netsuite Information Please Contact To Saqib Thanks Man U Just Do It.
<?php
$order_date = date('Y-m-d H:i:s');
// create array of fields
$itemArr = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
//if you not have internal id of item in netsuuite then please add the item in the netsuite and try.
$netsuiteItemId = 'Your Item Internal id Which is in the Netsuite Item';
$itemArr[$i]['item']['internalId'] = $netsuiteItemId;
$itemArr[$i]['quantity'] = $valueProduct['qty'];
$i++;
}
if (!define('LF', "\n")) {
define('LF', "\n");
}
/* for use in formatting custom addresses since NetSuite converts to <br> */
//Billing Address Information
/* this example has the customer address info in a db record, just pulled into $row */
$billAddress = stripslashes($order->order_custom_fields['_billing_first_name'][0]) . ' ' . $order->order_custom_fields['_billing_last_name'][0] . LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_1'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_2'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_country'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_state'][0]) . ' - ' . $order->order_custom_fields['_billing_postcode'][0] . ', ' . LF;
$billAddress .= $order->order_custom_fields['_billing_phone'][0] . ', ' . $order->order_custom_fields['_billing_email'][0];
//Shipping Address Information
$shipAddress = stripslashes($order->order_custom_fields['_shipping_first_name'][0]) . ' ' . $order->order_custom_fields['_shipping_last_name'][0] . LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_1'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_2'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_city'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_state'][0]) . ', ' . $order->order_custom_fields['_shipping_postcode'][0] . ', ' . LF;
$shipAddress .= $order->order_custom_fields['_billing_phone'][0] .', '. $order->order_custom_fields['_billing_email'][0];
$purchaseOrderFields = array (
'entity' => array ('internalId' => $internal_Id, 'type' => 'customer'),
'shippingCost' => $order->order_shipping,
'shipMethod' => $order->payment_method,
'toBeEmailed' => true,
//'tranId' => $order->order_custom_fields['Transaction ID'][0],
//'tranDate' => date('Y-m-d H:i:s'),
'source' => 'littlecrate',
'createdFrom' => 'littlecrate.com',
'discountRate' => $order->order_custom_fields['_order_discount'][0],
'taxRate' => $order->order_custom_fields['_order_tax'][0],
'email' => $order->billing_email,
//'shipDate' => date('Y-m-d H:i:s'),
'shipMethod' => $order->shipping_method,
'shippingCost' => $order->order_shipping,
'shippingTax1Rate' => $order->order_shipping_tax,
'paymentMethod' => $order->payment_method,
//'taxTotal' => $order->order_tax,
//'total' => $order->order_total,
'billAddress' => $billAddress,
'shipAddress' => $shipAddress,
'itemList' => array (
'item' => $itemArr
)
);
$salesOrder = new nsComplexObject('SalesOrder');
$salesOrder ->setFields($purchaseOrderFields);
$addResponse = $myNSclient->add($salesOrder );
if (!$addResponse->isSuccess) {
echo "Order Information is Not Inserted Into The Netsuite. Please Contact to Administration.";
exit;
}
?>
You item List object doesn't seem in correct format. Your code should look like this
$itemArr = array();
foreach($order_items_product as $keyProduct =>$valueProduct){
$item = new SalesOrderItem();
$item->item = $valueProduct['product_id'];
$item->quantity = $valueProduct['qty'];
$itemArr[] = $item;
}
$itemList = new SalesOrderItemList();
$itemList->item = $itemArr;
$so->itemList->item = $itemList;

I'm getting 'The request must contain the parameter Signature' although I'm actually supplying it

I'm trying the AWS Product Advertisement API in PhP.
Here is the PhP code that I've copied from net.
function callSOAPFunction($function, $array){
$timeStamp = gmdate("Y-m-d\TH:i:s\Z");
//service is always the same, $function is operation
$string = 'AWSECommerceService'.$function.$timeStamp;
$signature = base64_encode(hash_hmac("sha256", $string, 'MySecretKey', True));
$params = array('Service' => 'AWSECommerceService',
'AssociateTag' => 'Wassup?',
**'Signature' => $signature,**
'AWSAccessKeyId' => 'MyKey'
'Request' => array($array),
'Timestamp' => $timeStamp
);
$client = new
SoapClient("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
array('exceptions' => 0));
return $client->__soapCall($function, array($params));
}
$array = array('Operation' => 'ItemSearchRequest',
'ItemPage' => 3,
'SearchIndex' => 'DVD',
'ResponseGroup' => 'Large',
'Keywords' => 'Karate');
$result = callSOAPFunction("ItemSearch", $array);
Although I'm including the signature parameter, I'm still getting the error.