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,
];
}
When attempting to perform a doctrine query and serialze it to json (not using JSM, using the symfony serializer) I get the following in the json:
""due":{"timezone":{"name":"Europe/Berlin","transitions":[{"ts":-2147483648,"time":"1901-12-13T20:45:52+0000","offset":3208,"isdst":false,"abbr":"LMT"},{"ts":-2147483648,"time":"1901-12-13T20:45:52+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-1693706400,"time":"1916-04-30T22:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-1680483600,"time":"1916-09-30T23:00:00+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-1663455600,"time":"1917-04-16T01:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-1650150000,"time":"1917-09-17T01:00:00+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-1632006000,"time":"1918-04-15T01:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-1618700400,"time":"1918-09-16T01:00:00+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-938905200,"time":"1940-04-01T01:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-857257200,"time":"1942-11-02T01:00:00+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-844556400,"time":"1943-03-29T01:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-828226800,"time":"1943-10-04T01:00:00+0000","offset":3600,"isdst":false,"abbr":"CET"},{"ts":-812502000,"time":"1944-04-03T01:00:00+0000","offset":7200,"isdst":true,"abbr":"CEST"},{"ts":-796777200,"time":"1944-10-02T01:00:00+0000","offset":3600,"
When storing the due date, the timezone is saved and there is an additional timezone field stored. Is there a way to pull the date in a specific format or specify the timezone to use when retrieving?
public function blahAction(Request $request)
{
$currentUser = $this->getUser();
$em = $this->getDoctrine()->getManager();
$blahs = $em->getRepository('AppBundle:blah')->findAllByStatus($currentUser,'TODO');
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizer = array(new ObjectNormalizer());
$serializer = new Serializer($normalizer, $encoders);
$response = new Response($serializer->serialize($blahs, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
You have 2 ways to get RFC3339 Datetime format ...
Option 1:
Add DateTimeNormalizer as normalizer. An example is https://symfony.com/doc/current/components/serializer.html#recursive-denormalization-and-type-safety.
Change
$normalizer = array(new ObjectNormalizer());
by
$normalizer = array(new DateTimeNormalizer(), new ObjectNormalizer());
Option 2
More simple is using "serializer" container service ... your code will look like ...
public function blahAction(Request $request)
{
$currentUser = $this->getUser();
$em = $this->getDoctrine()->getManager();
$blahs = $em->getRepository('AppBundle:blah')->findAllByStatus($currentUser,'TODO');
$response = new Response($this->get('serializer')->serialize($blahs, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
.. or, if your prefer autowiring way (this code is unchecked)
public function blahAction(Request $request, \Symfony\Component\Serializer\SerializerInterface $serializer)
{
$currentUser = $this->getUser();
$em = $this->getDoctrine()->getManager();
$blahs = $em->getRepository('AppBundle:blah')->findAllByStatus($currentUser,'TODO');
$response = new Response($serializer->serialize($blahs, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
In Symfony 5.1 it's recomended to add a callback function to specify datetime field format.For example:
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
$dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
};
$defaultContext = [
AbstractNormalizer::CALLBACKS => [
'created_at' => $dateCallback,
'updated_at' => $dateCallback
],
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>
function ($articles, $format, $context) {
return $articles->getId();
}
];
$encoders = [new JsonEncoder()];
$normalizers = [
new ObjectNormalizer(null, null, null,
null, null, null,
$defaultContext)
];
$serializer = new Serializer(
$normalizers, $encoders
);
$articles = $serializer->serialize($articles, 'json');
Where $articles = array of App\Entity\Article objects
You can specify datetime format you need in your callback function.
Another option is to pass arguments to the default DateTimeNormalizer in services.yaml:
Symfony\Component\Serializer\Normalizer\DateTimeNormalizer:
arguments:
$defaultContext:
datetime_format: 'Y-m-d\TH:i:s.v\Z'
I'm trying to test a form but i got unreachable field exception.
My controller's code :
class StudentController extends Controller
{
/**
* #Route("/student/new",name="create_new_student")
*/
public function newAction(Request $request){
$student = new Student();
$form = $this->createFormBuilder($student)->add('name',TextType::class)
->add('save',SubmitType::class,['label' => 'Create student'])->getForm();
$form->handleRequest($request);
if($form->isSubmitted()){
$student = $form->getData();
$name = $student->getName();
echo "Your name is ".$name;
die();
}
return $this->render(':Student:new.html.twig',['form' => $form->createView()]);
}
}
My StudentControllerTest :
class StudentControllerTest extends WebTestCase
{
public function testNew(){
$client = static::createClient();
$crawler = $client->request('POST','/student/new');
$form = $crawler->selectButton('Create student')->form();
$form['name'] = 'Student1';
$crawler = $client->submit($form);
$this->assertGreaterThan(0,$crawler->filter('html:contains("Your name is Student1")')->count());
}
}
When i run the test using phpunit i got :
InvalidArgumentException: Unreachable field "name"
I'm following the tutorial from https://symfony.com/doc/current/testing.html
You should use the $form['form_name[subject]'] syntax
public function testNew(){
$client = static::createClient();
//you should request it with GET method, it's more close to the reality
$crawler = $client->request('GET','/student/new');
$form = $crawler->selectButton('Create student')->form();
$form['form_name[name]'] = 'Student1';
// [...]
}
Try this way. Edit Test
$form = $crawler->selectButton('Create student')->form(['name' => 'Student1']);
Edit Controller:
...
$name = $student->getName();
return new Response("Your name is ". $name);
Do not kill what Symfony request.
I'm trying to insert a data passed in the form (e-mail) in the response that I create in the listener to ensure that the response is a json object.
I can not take the form data from 'event in any way ..
There is a solution to what I want?
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::PROFILE_EDIT_SUCCESS => 'onProfileEditSuccess',
);
}
public function onProfileEditSuccess(FormEvent $event)
{
$response = new Response();
$output = array('success' => true, 'new_mail' => $event); //event return empty object
$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
$event->setResponse($response);
}
I tried to listen to the event COMPLETED, but does not make me change response!
You can grab form from $event object with $event->getForm() in PROFILE_EDIT_SUCCESS event.
in FOS\UserBundle\Controller\ProfileController:
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
To access email
$form = $event->getForm();
$email = $form['email']->getData();
I would authenticate a user in a very direct way (FOSUserBundle, Symfony2.2). I'am trying with a trivial example, but it doesn't work:
...
use FOS\UserBundle\Controller\RegistrationController as RegController;
...
class DefaultController extends Controller{
...
public function indexAction(){
$route = 'first_set_profile';
$url = $this->container->get('router')->generate($route);
$response = new RedirectResponse($url);
$userManager = $this->get('fos_user.user_manager');
$userToLogIn = $userManager->findUserByEmail('aa#bb.com');
new RegController(authenticateUser($userToLogIn, $response));
...
}
This script is running, but it is not authenticate the user with email aa#bb.com...
Thanks
This is how you can authenticate a demo user for example programmatic:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
public function demologinAction(Request $request)
{
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserByEmail('demo#example.com');
if (!$user) {
throw $this->createNotFoundException('No demouser found!');
}
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
$context = $this->get('security.context');
$context->setToken($token);
$router = $this->get('router');
$url = $router->generate('dashboard_show');
return $this->redirect($url);
}
The third parameter in the UsernamePasswordToken must be the firewall name.