concatenate fields with zend_form - zend-framework

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

Related

Update controller method not rendering json data in Laravel

I have a simple form with some text inputs and uploading photos with that form. Store method working very well but I'm doing something wrong in update method.
This is my store method which works fine:
public function store(Request $request)
{
dd($request);
$post = new Post;
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = "asdasd";
$post->ip = request()->ip();
if($request->hasfile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
$post->slug = $post->id."-".$this->make_slug($request->title);
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('archive');
}
And this is my update method which saves everything but photos:
public function update(Request $request, $id)
{
if(Auth::user()->role == 3 || Auth::user()->id == Post::find($id)->user_id){
$post = Post::find($id);
$post->title = $request->title;
$post->user_id = $request->user()->id;
$post->who = $request->who;
$post->when = $request->when;
$post->where = $request->where;
$post->body_text = $request->body;
$post->embed = $request->embed;
$post->status = "4";
$post->tags = $request->tags;
$post->slug = $id."-".$this->make_slug($request->title);
$post->ip = request()->ip();
if($request->hasFile('photo'))
{
foreach($request->file('photo') as $image)
{
$name= time()."-edit-".$this->photo_san($image->getClientOriginalName());
$image->move(public_path().'/uploads/', $name);
$data[] = $name;
}
$post->photo = json_encode($data);
}
$post->save();
Session::flash('success', 'Well done.');
return redirect()->route('new');
}
else
Session::flash('error', 'Shame on you :( ');
return redirect()->route('new');
}
When I'm updating any post, everything updating but photos and I don't have any idea what's wrong.
I don't know if it differs but I'm using Laravel 5,8

Set 'enctype' form attribute in moodle form?

I am creating a form in moodle. I require multipart/form-data in enctype attributes to work with files. But I don't know where the attribute should be set. And how to set it.
Have a look at the Files API with the Forms API for uploading files.
http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms
UPDATE: Haven't tested this but its a cut down version of some existing code I have
In your edit.php file have something like this:
require_once(dirname(__FILE__) . '/edit_form.php');
$id = optional_param('id', null, PARAM_INT);
if ($id) {
// Existing record
$record = $DB->get_record('mytablename');
} else {
// New record
$record = new stdClass();
$record->id = null;
$record->myfield = '';
...
}
// Prepare the files.
$fileoptions = array(
'maxbytes' => get_max_upload_file_size(),
'maxfiles' => '1', // Change this to how many files can be uploaded.
'subdirs' => 0, // No sub directories.
'context' => $context
);
$record = file_prepare_standard_filemanager($record, 'myfiles',
$fileoptions, $context, 'mypluginname', 'myfiles', $record->id);
$mform = new edit_form(null, array('fileoptions' => $fileoptions));
if ($formdata = $mform->get_data()) {
// Form has been submitted.
if (empty($formdata->id)) {
// New record so create it.
$recordid = $DB->insert_record('mytablename', $formdata);
$record = $DB->get_record('mytablename', array('id' => $recordid));
} else {
// Update it.
$DB->update_record('mytablename', $formdata);
$record = $DB->get_record('mytablename', array('id' => $id));
}
// Save the files.
$formdata = file_postupdate_standard_filemanager($formdata, 'myfiles',
$fileoptions, $context, 'mypluginname', 'myfiles', $record->id);
} else {
// Display the form.
$mform->set_data($record);
$mform->display();
}
And in your edit_form.php have something like this
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/formslib.php');
class edit_form extends moodleform {
public function definition() {
$fileoptions = $this->_customdata['fileoptions'];
$mform =& $this->_form;
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
...
$mform->addElement('filemanager', 'myfiles_filemanager',
get_string('myfiles', 'mypluginname'), null, $fileoptions);
$this->add_action_buttons(false, get_string('submit'));
}
}
I know this question is old but did not see anything in the Moodle documentation. This works as of Moodle 3.11.
class my_form extends moodleform {
...
$mform = $this->_form;
...
$attr = $mform->getAttributes();
$attr['enctype'] = "multipart/form-data";
$mform->setAttributes($attr);
}

Zend2 TableGateway: how to retrieve a set of data

I have a ContactsTable.php module and an function like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row record");
}
return $row;
}
which is ok, but it only returns one row.
The problem is in my database I have multiple records with the same Last Name, so my question is:
How can I return a set of data?
I tried this:
$where = new Where();
$where->like('last_name', $last_name);
$resultSet = $this->tableGateway->select($where);
return $resultSet;
but it doesn't work.
Your first function should work as you expect, just remove line
$row = $rowset->current();
So, complete function should look like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
foreach ($rowset as $row) {
echo $row['id'] . PHP_EOL;
}
}
More info you can find in documentation http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html
You can use the resultset to get array of rows:
public function getContactsByLastName($last_name) {
$select = new Select();
$select->from(array('u' => 'tbl_users'))
->where(array('u.last_name' => $last_name));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
return $rows;
}
Its working for me.

symfony 1.4 resett values from fields after fail

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);
}

Database expression not used in query

Can anyone tell me why my expression is not used in the query below?
SELECT accountreset.* FROM accountreset WHERE (reset_id = '34') LIMIT 1
public function findByResetId($resetId, $model = null) {
$result = null;
if (isset($resetId)) {
$select = $this->getDao()->select(
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);
$select->where('reset_id = ?', $resetId);
$row = $this->getDao()->fetchRow($select);
if (null != $row) {
if (!($model instanceof Stage5_Model_PasswordResetter)) {
$model = new Stage5_Model_PasswordResetter();
}
// vul het model object
$model->setResetId($row->reset_id);
$model->setUserId($row->user_id);
$model->setExpiration($row->expiration);
$result = $model;
}
}
return $result;
}
Your Zend_Db_Expr should go into from() method instead of select()
$select = $this->getDao()
->select()
->from(
$this->getDao()->info('name'),
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);