I am using zend form and form decorator to view form.
After submitting this form and there is any error(validation) my form gets blank.
How can I restore previous values in form. And form should get blank if it gets submitted successfully.
articleForm.php
<?php
class Application_Form_articleForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
//$id = $this->createElement('hidden','id');
$name = $this->createElement('text','name');
$name->setLabel('URL name:')
->setAttrib('size',250);
$title = $this->createElement('text','title');
$title->setLabel('Title:')
->setAttrib('size',250);
$group_id = $this->createElement('select','group_id');
$group_id->setLabel('Category:')
->addMultiOptions(array(
'US' => 'United States',
'UK' => 'United Kingdom'
));
$tags = $this->createElement('text','tags');
$tags->setLabel('Tags:')
->setAttrib('size',250);
$status = $this->createElement('text','status');
$status->setLabel('status:')
->setAttrib('size',250);
//$Publish = $this->createElement('submit','Publish');
$Publish = new Zend_Form_Element_Submit('Publish');
$Publish->setLabel("Publish")
->setIgnore(true);
$allowed_tags = array(
'a' => array('href', 'title'),
'strong',
'img' => array('src', 'alt'),
'ul',
'ol',
'li',
'em',
'u',
'strike');
$content = new Zend_Form_Element_Textarea('content');
$content->setLabel('content')
->setAttrib('rows', 12)
->setAttrib('cols', 40)
->setRequired(true)
->addFilter('StringTrim')
->addFilter('StripTags', $allowed_tags);
$this->addElements(array(
$name,
$title,
$group_id,
$tags,
$content,
$status,
$Publish
));
$this->setDecorators(array(array('viewScript', array('viewScript' => 'admin/articleFormDecorator.phtml'))));
}
}
adminController.php
indexsAction()
public function indexAction() {
$mysession = new Zend_Session_Namespace('Admin');
if (!isset($mysession->adminName)) {
$this->_redirect('/admin/login');
}
$form = new Application_Form_articleForm();
$this->view->form = $form;
$content = new Application_Model_Content();
if ($this->_request->getPost('Publish')) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) { //If form data is valid
$content->insert($formData);
}
}
}
I am getting following error too
Exception information:
Message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Publish' in 'field list'
Where Publish is submit button.
Please modify your action as
You need to add unset($formData['Publish']);
public function indexAction() {
$mysession = new Zend_Session_Namespace('Admin');
if (!isset($mysession->adminName)) {
$this->_redirect('/admin/login');
}
$form = new Application_Form_articleForm();
$this->view->form = $form;
$content = new Application_Model_Content();
//$data = $content->fetchAll($content->select());
if ($this->_request->getPost('Publish')) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) { //If form data is valid
unset($formData['Publish']);
$content->insert($formData);
}
}
}
Related
I have created a form for an entity Event with user's fields like "email" and "password" what I use to create a user manually in the controller.
I can create the event and the user without problems, but I need to send a confirmation mail to enable the user. I can do it from the normal registration form, but here I don't know how to do it.
Sorry if my english isn't very good. I'm learning it.
The controller:
class EventController extends Controller
{
public function ajaxAction(Request $request) {
if (! $request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get the province ID
$id = $request->query->get('category_id');
$result = array();
// Return a list of cities, based on the selected province
$repo = $this->getDoctrine()->getManager()->getRepository('CASEventBundle:Subcategory');
$subcategories = $repo->findByCategory($id, array('category' => 'asc'));
foreach ($subcategories as $subcategory) {
$result[$subcategory->getName()] = $subcategory->getId();
}
return new JsonResponse($result);
}
public function indexAction(Request $request) {
$lead = new Lead();
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
if(is_object($user)) {
$promotor = $em->getRepository('CASUsuariosBundle:Promotor')->find($user);
if (is_object($promotor)) {
$form = $this->createForm(new EventType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:event.html.twig";
$isPromotor = true;
}
} else {
$form = $this->createForm(new LeadType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:full_lead.html.twig";
$isPromotor = false;
}
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
if($isPromotor === true) {
$type = $promotor->getType();
$name = $user->getName();
$lastname = $user->getLastName();
$email = $user->getEmail();
$password = $user->getPassword();
$phone = $user->getPhone();
$company = $promotor->getCompany();
$lead->setEventType($type);
$lead->setPromotorName($name);
$lead->setPromotorLastName($lastname);
$lead->setPromotorEmail($email);
$lead->setPromotorPhone($phone);
$lead->setPromotorCompany($company);
}
$emailReg = $form->get('promotorEmail')->getData();
$passwordReg = $form->get('promotorPassword')->getData();
$nameReg = $form->get('promotorName')->getData();
$typeReg = $form->get('promotorType')->getData();
$lastnameReg = $form->get('promotorLastName')->getData();
$phoneReg = $form->get('promotorPhone')->getData();
$companyReg = $form->get('promotorCompany')->getData();
if(!empty($emailReg) && !empty($passwordReg)) {
$userManager = $this->get('fos_user.user_manager');
$newUser = $userManager->createUser();
$newPromotor = new Promotor();
$newUser->setUsername($emailReg);
$newUser->setEmail($emailReg);
$newUser->setName($nameReg);
$newUser->setLastname($lastnameReg);
$newUser->setPhone($phoneReg);
$newUser->setIsPromotor(true);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($newUser, strval($passwordReg));
$newUser->setPassword($encoded);
$userManager->updateUser($newUser);
$newPromotor->setType($typeReg);
$newPromotor->setCompany($companyReg);
$newPromotor->setIdPromotor($newUser);
$em->persist($newUser);
$em->persist($newPromotor);
$em->persist($lead);
$em->flush();
//return $response;
}
$em->persist($lead);
$em->flush();
return $this->redirect($this->generateUrl('CASEventBundle_create'));
}
}
return $this->render($template, array('form' => $form->createView()));
}
}
you could just create a confirmation token yourself and set it to the not yet active user, send him a mail using swift wich contains a link to confirm like :
$confiToken = "123";
$url="http://url.com/confirm/$confiToken";
$user->setConfirmationToken($confiToken);
$message = $mailer->createMessage()
->setSubject('Confirm registration')
->setFrom('from#mail.com')
->setTo($sendTo)
->setBody(
$this->renderView(
'Bundle:Email:confirm.html.twig',
array(
'headline' => "Confirm your registration",
"sendTo"=>$sendTo,
"name"=>false,
"date"=>$date,
"message"=>"here ist your confirmationlink ".$url." "
)
),
'text/html'
);
$mailer->send($message);
when the user clicks the link in the email you can manually generate the token and set the user active:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
...
$user=$em->getRepository("Bundle:User")->findOneByConfirmationToken($token);
if(!$user || $user->isEnabled()){
throw $this->createNotFoundException("link out of date");
}else {
$user->setEnabled(true);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
$em->flush();
return $this->redirect($this->generateUrl('core_customer_dashboard'));
}
I'm trying to use the CallAPI function to post a status remotely after I get the tokens, but it's not working for some reason.
Here is my code:
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->access_token)) {
$url = 'http://api.linkedin.com/v1/people/~/shares';
$method = 'POST';
$parameters = array('comment' => 'Some comment', 'content' => 'Some content', 'title' => 'Some title');
$options = array();
$success = $client->CallAPI($url, $method, $parameters, $options, $response);
}
}
$success = $client->Finalize($success);
}
I'm doing something wrong, but I can't find out what, because it doesn't give me any errors.
I got a form for the registration of a user and use it as an edit-user-form, too.
Now I want to make this form more vabiable. That means in my case: I want to have a specific button label for the different actions.
If the form is called via RegisterAction, the label should be "Register" and if it's called via EditAction, it shall be "Update user". I tried some things but now I ran out of ideas.
Here is my code:
CustomerController.php
...
public function registerAction(){
$form = new Application_Form_Register();
$request = $this->_request->getParams();
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$customerArr = $customerModel->setCustomer($request,true);
$this->redirect('/customer/detail/id/'.$customerArr);
}
else{
$this->view->form = $form;
$this->view->button = "Register"; //TEST
}
}
public function editAction(){
$request = $this->_request->getParams();
if(isset($request['id']) && !empty($request['id'])){
$form = new Application_Form_Register();
$form->addElement('hidden', 'id', array(
'required' => true,
'value' => $request['id'],
'validators' => array(
$digits = new Zend_Validate_Digits()
)
));
if(isset($request['registerbtn']) && ($form->isValid($request) )){
$customerModel = new Application_Model_Customer();
$id = $customerModel->setCustomer($request,false);
$this->redirect('/customer/detail/id/'.$id);
}else{
$modelResult = new Application_Model_Customer();
$customer = $modelResult->getCustomer($request['id']);
$cArr = $customer->toArray();
$form->populate($cArr);
$this->view->form = $form;
$this->view->button = "Update user"; //TEST
}
}else{
$this->redirect('/');
}
}
...
The views
// register.phtml - begin
<h2>Registration</h2>
<?php
$this->headTitle('Registration');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
echo $this->error;?>
// register.phtml - end
// edit.phtml - begin
<?php
echo $this->headline;
$this->headTitle('Update user');
$button = $this->button; //TEST
$this->form->button = $button; //TEST
echo $this->form;
?>
// edit.phtml - end
And the form
//
...
$this->addElement('submit', 'registerbtn', array(
'ignore' => true,
'label' => $button, //TEST
'decorators' => $this->buttonDecorators,
));
...
I fear that this is totally wrong but I don't know how to do it right.
Try something like
if ($cas1)
$form->getElement('submit')->setLabel('cas1');
else
$form->getElement('submit')->setLabel('cas2');
I want to upload zip file in symfony but failed to do so.
When i am uploading text ot pdf or excel file,image or single file then it is uploaded fine.
But when i tried to upload zip file it returns nothig and also there is no error log only blank page is appaear.
Im My form i have the following code.
class UploadSalaryForm extends BaseForm {
public function configure() {
// Note: Widget names were kept from old non-symfony version
$var = 'salary';
$this->setWidgets(array(
'EmpID' => new sfWidgetFormInputHidden(),
'seqNO' => new sfWidgetFormInputHidden(),
'MAX_FILE_SIZE' => new sfWidgetFormInputHidden(),
'ufile' => new sfWidgetFormInputFile(),
'txtAttDesc' => new sfWidgetFormInputText(),
'screen' => new sfWidgetFormInputHidden(),
'commentOnly' => new sfWidgetFormInputHidden(),
));
$this->setValidators(array(
'EmpID' => new sfValidatorNumber(array('required' => true, 'min'=> 0)),
'seqNO' => new sfValidatorNumber(array('required' => false, 'min'=> 0)),
'MAX_FILE_SIZE' => new sfValidatorNumber(array('required' => true)),
'ufile' => new sfValidatorFile(array('required' => false)),
//'ufile', new sfValidatorFileZip(array('required' => false)),
'txtAttDesc' => new sfValidatorString(array('required' => false)),
'screen' => new sfValidatorString(array('required' => true,'max_length' => 50)),
'commentOnly' => new sfValidatorString(array('required' => false)),
));
// set up your post validator method
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array(
'callback' => array($this, 'postValidate')
))
);
}
public function postValidate($validator, $values) {
// If seqNo given, ufile should not be given.
// If seqNo not given and commentsonly was clicked, ufile should be given
$attachId = $values['seqNO'];
$file = $values['ufile'];
$commentOnly = $this->getValue('commentOnly') == "1";
if (empty($attachId) && empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Upload file missing');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
} else if (!empty($attachId) && $commentOnly && !empty($file)) {
$message = sfContext::getInstance()->getI18N()->__('Invalid input');
$error = new sfValidatorError($validator, $message);
throw new sfValidatorErrorSchema($validator, array('' => $error));
}
return $values;
}
/**
* Save employee contract
*/
public function save() {
$empNumber = $this->getValue('EmpID');
$attachId = $this->getValue('seqNO');
$empAttachment = false;
if (empty($attachId)) {
$q = Doctrine_Query::create()
->select('MAX(a.attach_id)')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber);
$result = $q->execute(array(), Doctrine::HYDRATE_ARRAY);
if (count($result) != 1) {
throw new PIMServiceException('MAX(a.attach_id) failed.');
}
$attachId = is_null($result[0]['MAX']) ? 1 : $result[0]['MAX'] + 1;
} else {
$q = Doctrine_Query::create()
->select('a.emp_number, a.attach_id')
->from('EmployeeAttachment a')
->where('a.emp_number = ?', $empNumber)
->andWhere('a.attach_id = ?', $attachId);
$result = $q->execute();
if ($result->count() == 1) {
$empAttachment = $result[0];
} else {
throw new PIMServiceException('Invalid attachment');
}
}
//
// New file upload
//
$newFile = false;
if ($empAttachment === false) {
$empAttachment = new EmployeeAttachment();
$empAttachment->emp_number = $empNumber;
$empAttachment->attach_id = $attachId;
$newFile = true;
}
$commentOnly = $this->getValue('commentOnly');
if ($newFile || ($commentOnly == '0')) {
$file = $this->getValue('ufile');
echo "file==".$file;
$tempName = $file->getTempName();
$empAttachment->size = $file->getSize();
$empAttachment->filename = $file->getOriginalName();
$empAttachment->attachment = file_get_contents($tempName);;
$empAttachment->file_type = $file->getType();
$empAttachment->screen = $this->getValue('screen');
$empAttachment->attached_by = $this->getOption('loggedInUser');
$empAttachment->attached_by_name = $this->getOption('loggedInUserName');
// emp_id and name
}
$empAttachment->description = $this->getValue('txtAttDesc');
$empAttachment->save();
}
}
But this code is only worked for single file not for zip file.
I want to upload and extract zip file.
When i try to update the query in php- codeigniter I get this form_validation error. Here is my Controller
THIS gives me error and I am not able to update or add an entry into my database
<?php
class Person extends CI_Controller {
// num of records per page
private $limit = 15;
function Person() {
parent::__construct();
//$this->load->library('table','form_validation');
$this->load->library('table');
$this->load->library('form_validation');
$this->form_validation->set_rules();
$this->load->helper('url');
$this->load->model('personModel', '', TRUE);
}
function index($offset = 0) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
// load data
$persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
// have pagntn
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->personModel->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('No', 'Name', 'Gender', 'Education',
'Date of Birth (dd-mm- yyyy)', 'Interest', 'Actions');
$i = 0 + $offset;
foreach ($persons as $person) {
$this->table->add_row(++$i, $person->name, strtoupper($person->gender) ==
'M' ? 'Male' : 'Female', ($person->education),
date('d-m-Y', strtotime($person->dob)), ($person->interest),
anchor('person/view/' . $person->id, 'view', array('class' => 'view',
'onclick' => "return confirm('View Full Details?')")) . ' ' .
anchor('person/update/' . $person->id, 'update', array('class' => 'update')) . ' ' .
anchor('person/delete/' . $person->id, 'delete', array('class' =>
'delete', 'onclick' => "return confirm('Are you sure want to delete this person?')"))
);
}
$data['table'] = $this->table->generate();
$this->load->library('table');
$this->load->library('form_validation');
// load view
$this->load->view('personList', $data);
}
function add() {
// set validation propert/ies
$this->set_fields();
// set common properties
$data['title'] = 'Add new person';
$data['message'] = '';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function addPerson() {
// set common properties
$data['title'] = 'Add new person';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
$id = $this->personModel->save($person);
// set form input name="id"
$this->form_validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function view($id) {
// set common properties
$data['title'] = 'Person Details';
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// get person details
$data['person'] = $this->personModel->get_by_id($id)->row();
// load view
$this->load->view('personView', $data);
}
function update($id) {
// set validation properties
$this->set_fields();
// prefill form values
$person = $this->personModel->get_by_id($id)->row();
$this->form_validation->id = $id;
$this->form_validation->name = $person->name;
$_POST['gender'] = strtoupper($person->gender);
$this->form_validation->dob = date('d-m-Y', strtotime($person->dob));
// set common properties
$data['title'] = 'Update person';
$data['message'] = '';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function updatePerson() {
// set common properties
$data['title'] = 'Update person';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$id = $this->input->post('id');
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))),
'education'=>$this->input->post('education'),
'interest'=>$this->input->post('interest'));
$this->personModel->update($id, $person);
// set user message
$data['message'] = '<div class="success">update person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function delete($id) {
// delete person
$this->personModel->delete($id);
// redirect to person list page
redirect('person/index/', 'refresh');
}
// validation fields
function set_fields() {
$fields['id'] = 'id';
$fields['name'] = 'name';
$fields['gender'] = 'gender';
$fields['dob'] = 'dob';
$fields['education']='educaiton';
$fields['interest']='
$this->form_validation->set_fields('$fields');
//echo"hellofff";
//exit;
}
// validation rules
function set_rules() {
$rules['name'] = 'trim|required';
$rules['gender'] = 'trim|required';
$rules['dob'] = 'trim|required|callback_valid_date';
$rules['education']='trim|required';
$rules['interest']='trim|required';
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('required', '* required');
$this->form_validation->set_message('isset', '* required');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
}
function form_validation() {
$this->add();
}
// date_validation callback
function valid_date($str) {
if (!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str)) {
$this->form_validation->set_message('valid_date', 'date format is not
valid. dd-mm-yyyy');
return false;
} else {
return true;
}
}
}
?>
This is my model:
PersonMOdel: Database name is employeeregistration and tableused is tbl_person
<?php
class PersonModel extends CI_Model {
// table name
private $tbl_person= 'tbl_person';
function Person(){
parent::construct();
}
// get number of persons in database
function count_all(){
return $this->db->count_all($this->tbl_person);
}
// get persons with paging
function get_paged_list($limit = 15, $offset = 0){
$this->db->order_by('id','asc');
return $this->db->get($this->tbl_person, $limit, $offset);
}
// get person by id
function get_by_id($id){
$this->db->where('id', $id);
return $this->db->get($this->tbl_person);
}
// add new person
function save($person){
$this->db->insert($this->tbl_person, $person);
return $this->db->insert_id();
}
// update person by id
function update($id, $person){
$this->db->where('id', $id);
$this->db->update($this->tbl_person, $person);
}
// delete person by id
function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->tbl_person);
}
}
?>
This can be cossidered a CRUD application.