undefined variable company
undefined variable i m getting error
public function addPolicyAction()
{
if ($this->sessionContainer->empId == "")
{
return $this->redirect()->toRoute('admin_user_login');
}
$ouCode = $this->sessionContainer->ouCode;
$langCode = $this->sessionContainer->langCode;
$empId = $this->sessionContainer->empId;
$arrLabel = array('company_policy','pdid','pdname','file_name','active');
$commonTransalationLabel = $this->commonTranslation->getCommonTransactionInformation($arrLabel, $langCode);
$companyPolicyForm = new CompanyPolicyForm($commonTransalationLabel);
if ($this->getRequest()->isPost()) {
// $data = $this->params()->fromPost();
$request = $this->getRequest();
$data = array_merge_recursive(
$request->getPost()->toArray(), $request->getFiles()->toArray()
);
$data['ouCode'] = $ouCode;
$data['langCode'] = $langCode;
$companyPolicyForm->setData($data);
$chkValidate = $this->hrCompanypolicy->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode
]);
if ($companyPolicyForm->isValid()) {
$data = $companyPolicyForm->getData();
if(isset($_POST['Submit'])){
$name = $_FILES['fileName']['name'];
$target_dir = 'public/media/policy_photos/';
$target_file = $target_dir . basename($_FILES["fileName"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$extensions_arr = array("jpg","jpeg","png","gif");
if( in_array($imageFileType,$extensions_arr) ){
move_uploaded_file($_FILES['fileName']['tmp_name'],$target_dir.$name);
}
}
$company = $this->companyPolicyManager->add($data,$ouCode, $langCode,$empId);
$cpData = $this->companyPolicyManager->getcpDataBycpId($data,$ouCode,$langCode);
$companyPolicyForm->buildCompanyPolicyData($cpData);
$this->flashMessenger()->addMessage($commonTransalationLabel['success_message']);
}
}
return new ViewModel([
'form' => $company,
'companypolicydata' => $cpData,
'label' => $commonTransalationLabel,
'form' => $companyPolicyForm,
'flashMessages' => $this->flashMessenger()->getMessages()
]);
}
i want to remove undefined variable in zendframework 3
i m using zendframework 3 and getting undefined variable in zendframework 3 what is the issue in the code ?
How to defined a variable in zendframework 3 i want to solve the issue
Problem is that you're using the $company variable in your return new ViewModel statement, but you only create the variable when the entire form is valid.
Instead of what you're doing, make sure that you provide a Form instance (whichever you need, e.g. CompanyForm) to your controller via the Factory. Then have your function along the lines like below (I've removed some error checking):
public function editAction()
{
$id = $this->params()->fromRoute('id', null);
/** #var Company $entity */
$entity = $this->getObjectManager()->getRepository(Company::class)->find($id);
/** #var CompanyForm $form */
$form = $this->getForm();
$form->bind($entity);
/** #var Request $request */
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
/** #var Company $entity */
$entity = $form->getObject();
$this->getObjectManager()->persist($entity);
try {
$this->getObjectManager()->flush();
} catch (Exception $e) {
throw new Exception('Could not save. Error was thrown, details: ', $e->getMessage());
}
return $this->redirectToRoute('companies/view', ['id' => $entity->getId()]);
}
}
return [
'form' => $form,
];
}
Related
I've a variable name $email but I don't know how to send it to dashController.php:
$action = $this->client->auth($username, $password);
if (isset($action->success) && $action->success){
$email = $action->data->email;
$response = new RedirectResponse('/dash');
$cookie = new Cookie('JWT', $action->data->jwt->token, new \DateTime($action->data->jwt->expires_at));
$response->headers->setCookie($cookie);
return $response;
}
in dashController.php
class dashController extends authContainer {
#[Route("/dash", "dashboard")]
public function indexAction(): Response
{
return $this->render('dash.twig', [
'email' => ...
]);
}}
If your class inherit from Symfony AbstractController class, you can use the
redirectToRoute method helper. Your code will be like :
if (isset($action->success) && $action->success){
$email = $action->data->email;
$response = $this->redirectToRoute('dashboard');
$cookie = new Cookie('JWT', $action->data->jwt->token, new \DateTime($action->data->jwt->expires_at));
$response->headers->setCookie($cookie);
return $response;
}
I'm trying to deserialize to an object with property which might take an array of objects as value or be null.
I have no problem deserializing arrays but I need to deserialize null to an empty array or to null itself.
For example { "items": null }
class A {
/**
* #var null|Item[]
*/
private $items = [];
/**
* #return Item[]|null
*/
public function getItems(): ?array
{
return $this->items ?? [];
}
/**
* #param Item $param
* #return A
*/
public function addItem(Item $param)
{
if (!is_array($this->items)) $this->items = [];
if (!in_array($param, $this->items))
$this->items[] = $param;
return $this;
}
// /** tried with this as well
// * #param array|null $param
// * #return A
// */
// public function setItems(?array $param)
// {
// $this->items = $param ?? [];
// return $this;
// }
/**
* #param Item $item
* #return A
*/
public function removeItem(Item $item): A
{
if (!is_array($this->items)) $this->items = [];
if (in_array($item, $this->items))
unset($this->items[array_search($item, $this->items)]);
return $this;
}
/**
* #param Item $item
* #return bool
*/
public function hasItem(Item $item): bool
{
return in_array($item, $this->items);
}
}
Serializer looks like this
$defaultContext = [
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>
function ($articles, $format, $context) {
return $articles->getId();
},
AbstractObjectNormalizer::SKIP_NULL_VALUES => false
];
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$encoders = [new JsonEncoder()];
$serializer = new Serializer([
new ArrayDenormalizer(),
new DateTimeNormalizer(),
new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter, null,
new ReflectionExtractor(), null, null, $defaultContext
),
], $encoders);
$a = $serializer->deserialize('{ "items": null }', A::class, 'json');
The error I get when items is null
[Symfony\Component\Serializer\Exception\InvalidArgumentException]
Data expected to be an array, null given.
Is it possible to have nullable property?
Traced down to the Serializer source code and found three possible options to have a nullable array.
Option 1
Remove addItem, hasItem, removeItem methods and it allows to set null, array, whatever. This is less preffed solution in my case.
Option 2
Adding a constructor helps as well. https://github.com/symfony/serializer/blob/5.3/Normalizer/AbstractNormalizer.php#L381
/**
* A constructor.
* #param array|null $items
*/
public function __construct($items)
{
$this->items = $items ?? [];
}
Option 3
Extended ArrayDenormalizer and overrided denormalize method to handle nulls
public function denormalize($data, string $type, string $format = null, array $context = []): array
{
if (null === $this->denormalizer) {
throw new BadMethodCallException('Please set a denormalizer before calling denormalize()!');
}
if (!\is_array($data) && !is_null($data)) {
throw new InvalidArgumentException('Data expected to be an array or null, ' . get_debug_type($data) . ' given.');
}
if (!str_ends_with($type, '[]')) {
throw new InvalidArgumentException('Unsupported class: ' . $type);
}
if(is_null($data))
return [];
$type = substr($type, 0, -2);
$builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
foreach ($data as $key => $value) {
if (null !== $builtinType && !('is_' . $builtinType)($key)) {
throw new NotNormalizableValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, get_debug_type($key)));
}
$data[$key] = $this->denormalizer->denormalize($value, $type, $format, $context);
}
return $data;
}
I want to retrieve a quantity for each item that I store in session and store it in database.
How do I retrieve the quantity in session and passed to my quantity attribute of my article entity during database persistence?
For example for this article:
(id 4, quantity 2).
I would store 2 in the quantity attribute of my article entity.
I tried :
$article->setQuantity($session->get('panier'));
I have this error:
An exception occurred while executing 'INSERT INTO article ....... {"4": "2"}
Notice: Array to string conversion
/**
* #Route("/payment", name="payment")
*/
public function paymentAction(Request $request)
{
$session = $request->getSession();
$produits = $this->getDoctrine()->getManager()->getRepository('AppBundle:Stock')->findArray(array_keys($session->get('panier')));
$commande = $session->get('commande');
var_dump($session->get('panier'));
if ($request->isMethod('POST')) {
$token = $request->get('stripeToken');
\Stripe\Stripe::setApiKey($this->getParameter("private_key"));
\Stripe\Charge::create(array(
"amount" => $commande->getTotal() * 100,
"currency" => "EUR",
"source" => $token,
"description" => ""
));
foreach ($produits as $produit) {
$article = new Article();
$article->setTitle($produit->getStock()->getTitle());
$article->setContent($produit->getStock()->getContent());
//problem here
$article->setQuantity($session->get('panier'));
//
$article->setPrice($produit->getPrice());
$commande->addArticle($article);
$em = $this->getDoctrine()->getManager();
$em->persist($commande);
$em->flush();
}
return $this->redirectToRoute('confirmation');
}
return $this->render(':default:payment.html.twig', array(
'commande' => $commande,
'panier' => $session->get('panier'),
'produits' => $produits,
'public_key' => $this->getParameter("public_key"),
));
}
Add article in session :
/**
* #Route("/shop/add/{id}", name="add_article")
*
*/
public function addArticlelAction(Request $request, $id)
{
$session = $request->getSession();
if (!$session->has('panier'))
$session->set('panier', array());
$panier = $session->get('panier');
if (array_key_exists($id, $panier)) {
if ($request->query->get('qte') != null)
$panier[$id] = $request->query->get('qte');
} else {
if ($request->query->get('qte') != null)
$panier[$id] = $request->query->get('qte');
else
$panier[$id] = 1;
}
$session->set('panier', $panier);
return $this->redirectToRoute('panier');
}
UPDATE:
If $id in addArticlelAction is the product id then:
foreach ($produits as $produit) {
$article = new Article();
$article->setTitle($produit->getStock()->getTitle());
$article->setContent($produit->getStock()->getContent());
//problem here
$article->setQuantity($session->get('panier')[$produit->getId()]);
//
$article->setPrice($produit->getPrice());
$commande->addArticle($article);
$em = $this->getDoctrine()->getManager();
$em->persist($commande);
$em->flush();
}
should work, because for the moment you have two products (product1 who has id 1 and product 4 who has id 4). When you call /shop/add/{id}, you are adding to $session->get('panier')[1] and $session->get('panier')[4] the quantities. So, when you're in foreach (to store in DB), you need to access index 1 and index 4 ($produit->getId())
I just start to study zend framwork2 , and read the document about how to use fieldset http://zf2.readthedocs.org/en/latest/modules/zend.form.collections.html
I can use tablegateway insert product data into database.but don't know how to insert data to brand table and I don't know how to link product and brand . thank you very much!!!!!
Many people has the same problem and rlandas wrote and uploaded a working code to github
i post the code of the controller in case the url changes. but take a look at the complete module in github
<?php
namespace Product\Controller;
use Product\Table\ProductTable;
use Product\Entity\Product as ProductEntity;
use Product\Form\CreateProduct;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Http\PhpEnvironment\Response;
use Zend\View\Model\ViewModel;
class ManageController extends AbstractActionController
{
public function indexAction ()
{
$product = $this->getProductTable();
$products = $product->getAllOrderByName();
$view = new ViewModel();
$view->setVariable('products', $products);
return $view;
}
public function viewAction ()
{
if ($id = $this->params('id')) {
$product = $this->getProductTable()
->getByProductId($id);
}
$view = new ViewModel();
$view->setVariable('product', $product);
return $view;
}
public function addAction ()
{
$form = new CreateProduct();
$product = $this->getServiceLocator()->get('Product\Entity\Product');
$form->bind($product);
$data = array(
'product' => array(
'name' => 'product name ' . mt_rand(1, 1000),
'price' => mt_rand(100.000, 5000.999) / 100,
'brand' => array(
'name' => 'My brand ' . mt_rand(1, 200),
'url' => 'http://www.mybrand.com'
),
'categories' => array(
array('name' => 'Sony'),
array('name' => 'Panasonic'),
array('name' => 'Phillips')
)
)
);
$form->populateValues($data);
// action viewscript
$view = new ViewModel(array(
'form' => $form
));
// do Post/Redirect/Get (PRG) strategy to stop user refresh/back button
$prg = $this->prg($this->getRequest()->getRequestUri(), true);
if ($prg instanceof Response) {
return $prg;
}
// this is when the user first arrives to this url, display the form
else if ($prg === false) {
return $view;
}
// lets retrieve the post data stored in the PRG session
$post = $prg;
// validate the form
$form->setData($post);
if(!$form->isValid())
return $view;
// if data are valid, then save
// save the brand
$brand = $product->getBrand();
$brandTable = $this->getBrandTable();
$brand = $brandTable->save($brand);
$brandId = $brandTable->getLastInsertValue();
$product->setBrandId($brandId);
// save the categories
$categoryTable = $this->getCategoryTable();
$categoryTable->persist($product->getCategories())->flush();
$categoryIds = implode(",", $categoryTable->getEntityIds());
$product->setCategoryIds($categoryIds);
// save the product
$productTable = $this->getProductTable();
$product = $productTable->save($product);
$this->redirect()->toRoute('product');
return $view;
}
public function editAction ()
{
$form = new CreateProduct();
$product = $this->getServiceLocator()->get('Product\Entity\Product');
$form->bind($product);
// action viewscript
$view = new ViewModel(array(
'form' => $form
));
$productTable = $this->getProductTable();
if ($id = $this->params('id')) {
$product = $this->getProductTable()->getByProductId($id);
// get the brands
$brand = $this->getBrandTable()->getByBrandId($product->getBrandId());
$product->setBrand($brand);
// get the categories
$categoryIds = explode(",", $product->getCategoryIds());
$categories = $this->getCategoryTable()->getAllByCategoryId($categoryIds);
$product->setCategories($categories);
$form->bind($product);
}
// do Post/Redirect/Get (PRG) strategy to stop user refresh/back button
$prg = $this->prg($this->getRequest()->getRequestUri(), true);
if ($prg instanceof Response) {
return $prg;
}
// this is when the user first arrives to this url, display the form
else if ($prg === false) {
return $view;
}
// lets retrieve the post data stored in the PRG session
$post = $prg;
// validate the form
$form->setData($post);
if(!$form->isValid())
return $view;
\Zend\Debug\Debug::dump(__METHOD__.' '.__LINE__);
\Zend\Debug\Debug::dump($post);
\Zend\Debug\Debug::dump($product);
return $view;
}
/**
*
* #return \Product\Table\ProductTable
*/
public function getProductTable ()
{
$sm = $this->getServiceLocator();
$table = $sm->get('Product\Table\ProductTable');
return $table;
}
/**
*
* #return \Product\Table\BrandTable
*/
public function getBrandTable ()
{
return $this->getServiceLocator()
->get('Product\Table\BrandTable');
}
/**
*
* #return \Product\Table\CategoryTable
*/
public function getCategoryTable ()
{
return $this->getServiceLocator()
->get('Product\Table\CategoryTable');
}
}
I'm using symfony2 and createForm to get the http post data. After witch I do:
$Data = (array) $form->getData();
And I get:
array (size=1)
'�Far\MT\AccountBundle\Entity\Movement�toAccount' => int 3
I don't think this is the normal behavior for these cases, any sugestions?
the toAccount should be the complete index name.
Wasn't able to reproduce the conditions in a test case for the cli:
<?php
namespace A;
class MyClass
{
public $id;
public $name;
public $age;
}
$object = new MyClass();
$object->name = "Andre";
$object->id = 1;
$object->age = 30;
var_dump($object);
$Ar = (array) $object;
var_dump($Ar)
This above worked ok.
I used this solution:
//comment
$Data = $form->getData();
$obj = new \ReflectionObject($Data);
$props = $obj->getProperties();
$propname = array();
foreach ($props as $prop) {
$tmp = "get".ucfirst($prop->name);
if (($res = $Data->$tmp() )!== null) {
$propname[$prop->name] = $res;
}
}
$tmpSearch = $propname;
I'll clean it up after.
You can use the Symfony normalizer class, as your propose will fail when you have fields in your form name with underscore like 'facility_id' but your setter is called facilityId
<?php
$data = $form->getData();
$normalizers = new \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer();
$norm = $normalizers->normalize($data);
print_r($norm);
you'll get output like
Array ( [fullname] => fullnameVal [email] => emaile#lkjl.com [phoneNumber] => 5554444 [facilityId] => 123132 )