How can i reset my formfield values ?
action:
$this->form = new $class();
$this->form->bind($request->getParameter('signin'));
if ($this->form->isValid())
{
$values = $this->form->getValues();
$this->redirect('#example');
}
else
{
if ($this->form->hasGlobalErrors())
$this->errorclass = 'error';
}
$this->form->resetFormFields();
return $this->renderPartial('ajax/example);
I have 2 fields email and pw: want to resett them after error that they empty
This dont work :(
$this->form->resetFormFields();
Any solutions?
Thx in regards
If your form has only 2 fields (email and pw), you can simply reinit form.
else
{
if ($this->form->hasGlobalErrors())
$this->errorclass = 'error';
$this->form = new $class();
}
If your form has more fields (no only email and pw) and you want to preserve other field values, you can remove email and pw values and bind new form.
$values = $request->getParameter('signin');
$this->form->bind($values);
if ($this->form->isValid())
{
$this->redirect('#example');
}
else
{
if ($this->form->hasGlobalErrors())
$this->errorclass = 'error';
$values['pw'] = '';
$values['email'] = '';
$this->form = new $class();
$this->form->bind($values);
}
Related
I have checked email unique in codeigniter. In else past I diplayed error. But the system error is not convenient. how to customise error...
i have tried giveng javascript alert instead of that error message... but after that alert the data are storing in database.. Actually the data should not store in database if the email is not unique..
public function add_applicants() {
// $field_name=$this->input->post('photo');
$data = $this->input->post();
$mobile = $this->db->get_where('applicants',array('mobile_number'=>$this->input->post('mobile_number')));
if($mobile->num_rows()>0)
{
throw new Exception("Mobile Number Already Registered");
}
$email = $this->db->get_where('applicants',array('email_id'=>$this->input->post('email_id')));
if($email->num_rows()>0)
{
throw new Exception("Email_id Already Registered");
}
$school_id= $this->input->post('school_code');
$name_of_exam= $this->input->post('name_of_exam');
$name= $this->input->post('name_candiadte');
switch($name_of_exam){
case '1':
$exam='NMMS';
break;
case '2':
$exam='NTS';
break;
}
$school_code = $this->Welcome_Model->getschoolData($school_id);
if (isset($_FILES['photo']) == 1) {
$config['upload_path'] = FCPATH . 'uploads/'. $school_code->name_of_the_school.'/'. $exam ;
$this->upload_path = $config['upload_path'];
if ($this->validate_upload_path() == TRUE) {
$config['upload_path'] = $this->upload_path;
// print_r($this->upload_path) ;
// die();
}
$config['allowed_types'] = 'jpg';
$config['max_size'] = 2000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = true;
$config['file_name'] = $name.'-'.date('Ymdhis') . '.jpg';
$file_name = $config['file_name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$this->upload->display_errors();
}
}
$data['photo'] = $file_name;
$insetapplicants = $this->Welcome_Model->insertApplicants($data);
if ($insetapplicants == 'Success') {
echo "<script>
alert('New Applicants Added Successfully');
// window.location.href='dashboard';
</script>";
}
}
Problem: even if my form fields meet the rules the codeigniter form validation still returns false (error).
example:
public function edit(){
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'title', 'required|xss_clean|trim|is_unique[news.Title]');
$this->form_validation->set_rules('description', 'description', 'required|xss_clean|trim');
$this->form_validation->set_rules('notes', 'notes', 'required|xss_clean|trim');
if ($this->form_validation->run() == FALSE)
{
$data['error'] = '';
$data['page_title']="Edit News";
echo "error";
}
else {
..........
if i leave the fields empty it will tell me to enter something because they cant be left empty. if i type something then it returns error once i submit the form.
you have to use the callback validation function
you have to pass id also
$this->form_validation->set_rules('title', 'Title', 'required|xss_clean|trim|callback_check_title');
function check_title($title) {
if($this->input->post('id'))
$id = $this->input->post('id');
else
$id = '';
$result = $this->news_model->check_unique_title($id, $title);
if($result == 0)
$response = true;
else {
$this->form_validation->set_message('check_title', 'Title must be unique');
$response = false;
}
return $response;
}
in model
function check_unique_title($id, $title) {
$this->db->where('title', $title);
if($id) {
$this->db->where_not_in('id', $id);
}
return $this->db->get('news')->num_rows();
}
it will work for both insert and update
no need for callback function
The problem is : codeigniter database class is not loaded;
You should load database : $this->load->database(); before running
if ($this->form_validation->run() == FALSE)
{
$data['error'] = '';
$data['page_title']="Edit News";
echo "error";
}
I'm using the zend framework with centurion and I'm having a problem with my form. I have fields num_ordre and code, both of which are primary keys and I have columns in my table named conca, it's the concatenation of two fields, num_ordre and code.
My question is, in my method post, I want to test if the concatanation of num_ordre and code already exists in my database; but the problem is how to take a value of to fields before posting it.
This is my code
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$row=$user->createRow();
$row->code=$this->_getParam('code');
$row->Num_ordre=$this->_getParam('Num_ordre');
$row->Libelle_champ=$this->_getParam('Libelle_champ');
$row->comparaison=$this->_getParam('comparaison');
$row->formule=$this->_getParam('formule');
$row->obligatoire=$this->_getParam('obligatoire');
$row->Req_traduction=$this->_getParam('Req_traduction');
$row->tolerance_erreur=$this->_getParam('tolerance_erreur');
$row->Mess_erreur=$this->_getParam('Mess_erreur');
$row->conca=$this->_getParam('Num_ordre').$this->_getParam('code');
$row->save();
if( isset ($posts['_addanother'])){
$_form = $this->_getForm();
$_form->removeElement('id');
$this->_helper->redirector('new','admin-verification');
}
else
$this->_helper->redirector(array('controller'=>'Admin-verification'));
}else{
parent::postAction();
}
}}
How about you just check it like this ?
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$mdl = new Model_Something(); //Call your model so you can test it
//Add a condition here
if ($form->isValid($formData) && $mdl->uniqueConcatenated($this->_getParam('num_ordre'), $this->_getParam('code')) {
$row=$user->createRow();
/**truncated, keep your existing code here**/
}
}
}
Then in your model Model_Something
public function uniqueConcatenated($numOrder, $code) {
$concatenated = $numOrder.$code;
//Check for the existence of a row with the concatenated field values
$select = $this->select();
$select->where('concatenatedField = '.$concatenated);
$row = $this->fetchRow($select);
return $row;
}
Hope this helps
You could manually call isValid on the validator:
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$formValues = $form->getValues();
$uniqueValidator = new Zend_Validate_Db_NoRecordExists('verifications','conca');
if ($uniqueValidator->isValid($formValues['Num_ordre'] . $formValues['Num_ordre'])) {
// valid
} else {
// not unique
}
}
untested code
I'm creating a CakePHP application that can have multiple users editing the same information at the same time. To prevent users from overwriting over each other's changes, I want to make it where when a user saves their form, it only saves the one or two fields that the user has changed.
I can't just compare the fields to the database values because those database values may actually be newer ones from other users.
Does CakePHP offer any way to only send the updated fields via POST?
I don't believe there is a built-in solution. I came up with some code that works, but you would definitely want to put it into its own function so that it can be used by multiple controller actions. Also, it's not perfect. For example, it would fail on a date field since CakePHP has date fields rendered as selects in forms.
This is for an edit action. Original code:
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
}
Modified code:
public function edit($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$originalData = unserialize(base64_decode($this->request->data['Extra']['original_data']));
$save = $this->request->data;
unset($save['Extra']);
foreach ($save as $model => $modelFields) {
if (!array_key_exists($model, $originalData)) {
continue;
}
foreach ($modelFields as $field => $value) {
if (!array_key_exists($field, $originalData[$model])) {
continue;
}
if ($save[$model][$field] === $originalData[$model][$field]) {
unset($save[$model][$field]);
}
}
}
$this->User->set($save);
if ($this->User->validates() && $this->User->save($save, false)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
$this->request->data['Extra']['original_data'] = base64_encode(serialize($this->request->data));
}
}
Also, add this somewhere in the form in edit.ctp:
echo $this->Form->hidden('Extra.original_data');
I have created a collection form in symfony 1.4 and Propel 1.5 and everything displays properly but I cannot get the form to save to the database.
The form is used to edit multiple users at once.
I found this question and I implemented the suggestion of extending my collectionForm class with sfFormPropel, but when I do that I run out of memory. I cannot find what is being pulled from the database that would fill up the processes memory.
In my new save function I am not even doing anything.
Any ideas?
class ContactCollectionForm extends sfFormPropel
{
public function getModelName()
{
return 'ContactCollectionForm';
}
public function retrieveSubObject($fieldname, $model)
{
switch($fieldname)
{
default:
break;
}
return array();
}
public function save($con = null)
{
}
public function configure()
{
$user = $this->getOption('user');
$embedded = $this->getOption('embedded');
$custom = $this->getOption('custom');
$contact_list = $this->getOption('contact_list');
$cf = $custom['form'];
if(!array_key_exists(0, $cf['fields']['field']))
$cf['fields']['field'] = array($cf['fields']['field']);
$use_fields = array();
for($i=0;$i<count($contact_list);$i++)
{
foreach($cf['fields']['field'] as $field)
{
if($field['type'] == 'object')
{
// embed object form (ala: PersonData, Coordinate etc...)
$model = $field['model'];
$model_form = $model.'Form';
$sub_object = $contact_list[$i];
$sub_form = new $model_form($sub_object, array('user' => $user, 'embedded' => true, 'custom' => $field['fields']));
$this->embedForm($field['name'], $sub_form);
array_push($use_fields, $field['name']);
} // end field type == object
else
{
// standard form field
$this->setWidget($field['name'], CustomWidgetExtender::createSfWidget($field, $user, $this));
$this->widgetSchema->setLabel($field['name'], $field['label']);
if(trim($field['default']) != '')
$this->setDefault($field['name'], $field['default']);
// add field name to use_fields array
array_push($use_fields, $field['name']);
} // end field type != object
}
}
}
}
I ended up doing a rough hack by processing each form manually rather than trying to shoehorn this type of form into the symfony 1.x form framework.