i make a controller in zf2 for save data in mongodb but it not save any record in event table,how i save data?here is my code:
public function createAction()
{
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
//echo $calendar_id;
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$calendar_id);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
//$form = new CalendarForm();
//$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I set code and save data using mongoodm,here is my code:
public function createAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($calendar_id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$post['calendar_id']);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
$form = new EventForm();
$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
Related
How to implement logout action in Zend Framework 2?
I am building my first ever zend application for matrimony site.
When I click on logout link user is logged out but his session is not expired,like when I click on the menu of edit profile or search profile the user session is still active.So how will I be able to implement that.
LoginController
public function indexAction()
{
$id=$this->params()->fromQuery('id');
if($id!="")
{
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$sql = "UPDATE projects SET confirmation='Y' where memcode = '$id'";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
}
$form = new LoginForm();
$viewModel = new ViewModel(array('form' =>$form));
return $viewModel;
}
public function getAuthService()
{
if (! $this->authservice) {
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'projects','email','password', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$this->authservice = $authService;
}
return $this->authservice;
}
public function processAction()
{
$this->getAuthService()->getAdapter()->setIdentity($this->request->getPost('email'))->setCredential($this->request->getPost('password'));
$result = $this->getAuthService()->authenticate();
if ($result->isValid()) {
$this->getAuthService()->getStorage()->write($this->request->getPost('email'));
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'confirm'
));
}
else {
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index1'
));
}
}
public function confirmAction()
{
$user_email = $this->getAuthService()->getStorage()->read();
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$sql = "SELECT name,memcode,gender,castenobar FROM projects where email = '$user_email'";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$user = $result->current();
$user_session = new Container('user');
$user_name = $this->getAuthService()->getStorage()->read();
$user_session->username= $user['name'];
$user_session->usermemcode= $user['memcode'];
$user_session->usergender= $user['gender'];
$user_session->usercastenobar= $user['castenobar'];
$username = $user_session->username;
$usergender = $user_session->usergender;
$usercastenobar = $user_session->usercastenobar;
if($usercastenobar=='Y'){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[]=$res;
}
return new ViewModel(array(
'selectData' => $selectData,
'user_name' => $username
));
}
else
{
$sql="select * from projects where gender !='".$usergender."' and castenobar='N'";
//echo $sql;
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[]=$res;
}
return new ViewModel(array(
'selectData' => $selectData,
'user_name' => $username
));
}
}
public function logoutAction()
{
//$this->getAuthService()->clearIdentity();
$storage = new \Zend\Authentication\Storage\Session();
$storage->clear();
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}
Your "logoutAction()" should look like this:
public function logoutAction()
{
$name = 'Zend_Auth' ;
$container = new Container($name);
$container->getManager()->getStorage()->clear($name);
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}
If you don't define name of session's container, use the default name 'Zend_Auth' in $name, otherwise in $name you must use your own name for the session container.
Your "$this->redirect()..." doesn't logout user and it doesn't clear the 'Zend_Auth' container. It only redirects to another site. The user is still logged in / active. To be sure that the user is logged in or logged out you can use:
$auth = new AuthenticationService();
if ($auth->hasIdentity()) {
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}
i make a setting action in which i used doctrine query for getting single result but it returns null while data exist in database,how i get single result?here is my code:
public function settingsAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'create'
));
}
//echo $id;
//$calendar = $id;//$this->getCalendarTable()->getCalendar($id);
$calendar = $documentManager->getRepository('Calendar\Document\Calendar')->find($id);
$form = new CalendarForm();
$form->bind($calendar);
$form->get('submit')->setAttribute('value', 'Save');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
//$this->getCalendarTable()->saveCalendar($form->getData());
return $this->redirect()->toRoute('calendar', array('action' => 'show', 'id' => $id));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
You don't need to create a query to fetch by id as the DocumentRepository already provides this via it's find($id) method.
Just use the document manager to fetch the repository
$document = $documentManager->getRepository('FooDocument')->find($id);
You can also use the convenience method find($documentName, $id) directly on the document manager.
$document = $documentManager->find('FooDocument', $id);
While trying to insert a collection of entities which have a file field, i couldn't figure out if there's is a better way to create the UploadedFile Object being cast by the Document::document annotation. Here's my code, any help on improving it is very appreciated :)
public function createAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
$entity = new Paper();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity->setAuthor($user);
$em->persist($entity);
// chotest foreach in the universe
if (isset($_FILES) && array_key_exists('arkad1a_cfpbundle_paper', $_FILES)) {
foreach ($_FILES['arkad1a_cfpbundle_paper']['name']['documents'] as $k => $v) {
$document = new UploadedFile(
$_FILES['arkad1a_cfpbundle_paper']['tmp_name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['type']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['size']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['error']['documents'][$k]['document'],
false
);
$Document = new \Arkad1a\CFPBundle\Entity\Document();
$Document->setAuthor($user)
->setDocument($document)
->setPaper($entity)
->upload();
$em->persist($Document);
}
}
$em->flush();
return $this->redirect($this->generateUrl('paper_show', array('id' => $entity->getId())));
} else {
die('invalid');
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
I am new in zf2. I make a create action and want to get last inserted id but calender_id always equal to zero. How can I get the last insert id in create action ?
Here is my code:
public function createAction()
{
if ($this->zfcUserAuthentication()->hasIdentity())
{
$form = new CalendarForm();
$form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$calendar = new Calendar();
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$calendar->exchangeArray($form->getData());
$this->getCalendarTable()->saveCalendar($calendar);
if($request->isXmlHttpRequest()) {
//$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//$calender = new \Calendar\Model\Calendar($dm);
$response = new Response();
$calender_id = $calendar->calendar_id;
$userid =$calendar->user_id;
$title=$calendar->title;
$description=$calendar->description;
$output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
//$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect()->toRoute('calendar');
}
}
return array('form' => $form);
}
else
{
$this->redirect()->toRoute('zfcuser/login');
}
}
how i get last inserted id?
If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. You can also use this method in your saveCalendar method.
Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);