how to get the text of a field in WPFormLite - php

I have a form in my website (Wordpress) with several fields. I need to get the data from each field to process it in the logic of my program.
I have tried to use this code and other similar ones that they provide in their documentation but after 8 hours of work I have not succeeded.
Any ideas?
add_action("wpforms_process_complete", 'function_save_custom_form_data');
function function_save_custom_form_data($params) {
foreach($params as $idx=>$item) {
$field_name = $item['name'];
$fiel_value = $item['value'];
// Do whatever you need
echo $field_name;
}
return true;
}

Related

Laravel Nova Actions Multiple messages

I could find a proper solution in the forum for my problem.
In my Laravel nova I have some Course Categories and if the user wants to delete some of them I
create an action to delete the data but before that I
check if these course categories have some courses in it.
This works everything fine. I'll go trough a foreach loop for every checked
Categorie but if some are deletable and some not the foreach breaks out and stops.
I think its because the return statements. But how can i get this return
`Action::message('Deleted!');`
OR
Action::danger('The Course Category "'.$model->name.'" could not be deleted, it may contains some Courses!');
done without breaking out of the loop and continue ?
Set a variable before the loop - let's call it "alldeleted".
$alldeleted = true;
And also set a blank array for categories that cannot be deleted :
$undeletedcategories = array();
If, during the loop, one of the categories cannot be deleted, note that by setting alldeleted to be false, adding the category name to the array, and using continue to go to the next element in the loop :
$alldeleted = false;
$undeletedcategories[] = $model->name;
continue;
Then, at the end of the process, look at whether $alldeleted is true or not and compose your response accordingly :
if($alldeleted) {
// return your "all deleted alright" status message here.
} else {
// Return the "these categories weren't deleted" status message here.
}
Thanks for the fast help Giles, I was able to solve my issue. I added another foreach to fill all the Category names in the Message.
$alldeleted = true;
$undeletedcategories = [];
$categorie = [];
foreach ($models AS $model)
{
$course = Course::where('category_id', $model->id)->count();
if($course === 0)
{
$model->delete();
}
else {
$alldeleted = false;
$undeletedcategories[] = $model->name;
}
}
if($alldeleted === true) {
return Action::message('Deleted all selected Courses successfully!');
} else {
foreach($undeletedcategories AS $cat)
{
$categorie[] = $cat;
}
return Action::danger('The following Course Category "'.implode(", ",$categorie).' " could not be deleted, it may contains some Courses!');
}

value stored as array in the database getting deleted while adding new values into the same array while updating

Here my problem is when i go for updating the values already stored in the database is getting deleted and only the newly added values are getting
here is my code
<script>
$(document).ready(function() {
if(destId=='bar3' || sourceId=='bar3') {
var itemvalue2 =Array();
$('ul#bar3 li').each(function() {
itemvalue2.push($(this).attr("value"));
});
document.getElementById("bar3-output").value=itemvalue2;
}
});
</script>
here is my view
<ul id="bar3" class="block__list block__list_tags">
<input type="hidden" id="bar3-output" name="all_active_menu3" class="form-control"
value="<?php if(!empty($team_info->members)) {
$tagsArray = explode(',', $team_info->members);
$tagsLinksArray = array();
foreach($tagsArray as $tag) {
$tagName = trim($tag);
$tagsLinksArray[]=$tagName;
}
$tagsLinks = implode(',', $tagsLinksArray);
echo $tagsLinks;}?>
">
</ul>
Here is my control
public function save_team($team_id = NULL)
{
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
$this->Teams_model->_table_name = 'tbl_teams'; // table name
$this->Teams_model->_primary_key = 'team_id'; // $id
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
if (!empty($team_id)) {
$message = ('Team Info Updated');
} else {
$message = ('Team Info Saved');
}
$type = 'success';
set_message($type, $message);
redirect('admin/team/team_list'); //redirect page
}
the value in the database is not becoming stable i had used many ideas but didn't reached destination.hope your help please help me
I'm not certain how your code works but here is what my guess is and what is going wrong: You're just replacing the old value in both cases.
This seems to be the relevant code fragment.
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
//...
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
The first assignment of $profile_data reads the current team data from the existing team. Your naming is a bit confusing as you're not actually reading any POST data it seems. The assignment within the if block that would fulfill the condition !empty($team_id) should update the team members and the false block should create a new team. Did you verify that $team_id gets set successfully?
I'm not certain about the structure of the team information but rather than a straight assignment using = in the true block you should be using += or manually combine the new and old data and do the assignment afterwards.
Using something like array_merge or a loop to create an intermittent object to hold the combined data should work here.

cakephp can't update table with set

I have a problem with updating database table in cakephp...
So I have a profile page where the logged in user can see and update his personal information. Here is my solution for it (yes I know it's not the best...)
if($this->request->is('post')) {
$data = $this->request->data['user-profile'];
// $uid = $this->Session->read("WebUser.id");
$uid = 1;
$user_data = $this->WebUser->find('first', array('conditions'=>array('id'=>$uid)));
$updated_fields = '';
foreach($data as $key => $value) {
if($key != 'state'){
if(empty($value)) {
$this->Session->setFlash("Please fill in all the required fields");
return;
}
}
if($user_data['WebUser'][$key] != $value) {
if($key == 'email') {
$mail_check = $this->WebUser->find('first', array('conditions'=>array('email'=>$value, 'id !='=>$uid)));
if($mail_check) {
$this->Session->setFlash("This e-mail is already registered");
return;
}
}
$updated_fields .= "'".$key."'=>'".$value."',";
}
}
if($updated_fields != '') {
$updated_fields .= "'modified'=>'".date("Y-m-d H:i:s")."'";
$this->WebUser->read(null, $uid);
$this->WebUser->set(array('first_name'=>'John','modified'=>'2014-12-30 10:53:00'));
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
$this->Session->setFlash("Error : Data modifying isn't complete. Please try again!");
}
}
return;
}
So this code fetches the user info from the database and looks for those fields which are edited on profile page. Problem is when I want to save the data it give me back false and didn't save it... Does someone have a solution for this?
Try putting
$this->WebUser->validationErrors;
in else part and check whether there are any validation errors or not.
Like this:
if($this->WebUser->save()) {
$this->printr($this->data);
$this->WebUser->save();
$this->Session->setFlash("Success : Profile data is now modified", array("class"=>"success_msg"));
} else {
echo "<pre>";print_r($this->WebUser->validationErrors);die();
$this->Session->setFlash("Error : Data modifying isn't complete. Please try agin!");
}
Did you tried to set id directly?
$this->WebUser->id = $uid;
Also, CakePHP is automatically update modified field in your table after any transactions. So you don't have to set it directly (but you can if you want any other date value).
About validation. I recommend you to read about Data Validation in CakePHP, because that validation is not good, it's can be handled by models.
Also. You can get any validation errors from models using Model::$validationErrors.
debug($this->Recipe->validationErrors);
The problem with this code was that didn't wanted to save the posted data ( debug($this->WebUser->save) has give me back false). At the end I didn't found the solution why this code not worked but the conclusion is that you never need to use more users table than one. So now I have a Users and Groups tables, and different type of users are connected to their groups(Admin, User, ...).

Form validation for multiple text input Codeigniter

Array values in form are always a problem for form validation in CI. Now I've to input multiple values and those array values are to be stored in DB. Now the user can keep some fields blanks by mistake as shown below in the links:
Input values.
Values in the array on submission.
I used this tutorial to add input boxes on + button click. On submission the blank values will be truncated and then not null array values will added to database. I tried this using a sample program in native PHP but could not implement it in CI.
I used the following code in native PHP to insert values in DB truncating null values:
<?php
include 'sql_connect.php';
$str = array();
for($i=0;$i<count($_POST["txtSiteName"]);$i++)
{
$str[] = $_POST["txtSiteName"][$i];
}
$str = array_filter($str, function($item) {if(!is_null($item)) return $item;});
foreach($str as $loop_str)
{
$arr_str[] = $loop_str;
}
for($k = 0; $k<count($arr_str);$k++)
{
mysql_query("INSERT INTO sitename (name) VALUES ('".$arr_str[$k]."')") or die(mysql_error());
}
print_r($arr_str);
?>
How can I achieve this in CI ?
I tried to use callback function but the array value is not being passed to the callback function.
EDIT:
The below code shows my callback function :
On entering 3 urls it is called 3 times. Is that normal ?
Also my array_walk's callback function is not working. Calling a callback function inside another callback function is not possible ?
public function null_check()
{
$urls = $this->input->post('link_name');
array_walk($urls, 'prepurl');
var_dump($urls);
}
prepurl function:
public function prepurl($item, $key)
{
$item = "http://".$item;
}
Your question is not clear to me but since you mentioned to validate multiple text boxes. So if your text boxes are something like this
<input type="text" name="txtSiteName[]" />
<input type="text" name="txtSiteName[]" />
then simply you can use
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean');
to validate all the text boxes against null or empty.
Update (TO pass an argument in to the callback)
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check[' . $this->input->post('txtSiteName') . ']');
function sitename_check($str, $sitenames) {
// $sitenames will be your textboxe's array
}
The first argument is used by CodeIgniter by default so second argument is your parameter. Also take a look at insert_batch() to insert multiple records.
Also you can do this like
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check');
function sitename_check() {
$sitenames = $this->input->post('txtSiteName');
}
Update: (For array_walk)
array_walk($urls, array($this, 'prepurl'));
Here is a simple process of doing it
Set message like this
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean|callback_check_array');
Here is callback
function check_array()
{
$txtSiteName = $this->input->post('txtSiteName');
$error = 0;
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$error = $error + 1;
}
}
if($error == 0){
return TRUE;
}else{
$this->form_validation->set_message('check_array', 'All fields are empty. Please provide at leaset 1');
return FALSE;
}
}
When validation is successfull run this code or modify according to your requirements
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$txtSiteName = $this->input->post('txtSiteName');
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$data['name'] = $value;
$this->mymodel->insert($data);
}
}
}
Model Method
function insert($data)
{
$this-db->insert('table_name',$data);
}

cakephp getting value of textfield in model

Hi I have dynamically added input fields on my add view. When I submit my form I want all them input fields to be concatenated into one string and stored in a single database field.
Im trying to achieve this using the beforeSave method of cakephp but I can't seem to find out how to get the values of a text field within the Model.
function beforeSave($options)
{
$result = '';
$bool = true;
$counter = 0;
while($bool == true)
{
$result = $result + ',' + $this->data['Variable']['selectOptions' + counter];
}
return true;
}
Anyone any ideas on how to achieve this?
Thanks in advance.
In my opinion (from MVC point of view) it would be better to concatenate the fields in controller and then unset unnecessary fields before saving the model...
after get the post values in model you can merge the array values into a single variable like this..
<?php
$var = array('test1','test2','test3','test4','test5','test6');
$new_values = implode(',',$var);
echo $new_values;
?>
You can retrieve these values after saving to database.
this might not be the perfect answer but might give you some head start in that direction
function beforeSave($options = array()) {
pr($this->data); // <= show data you intend to save
exit;
}
use foreach to loop the data array ($this->data) and perform concatenation on the values and assign the concatenated string to the feild name
function beforeSave($options = array()) {
foreach ($this->data['Variable'] as $key=>$value)
{
$feildflag = strstr($key, 'selectOptions');
if($feildflag){
$concatenatedstring .= $value;
}
}
$this->data['Variable']['your_feild_name'] = $concatenatedstring ;
}
Your dynamic form field should looks like in a foreach loop:
<?php echo $this->Form->input('Model.field][', array());
In your model:
function beforeSave($options)
{
if(!empty($this->data))
{
$this->data['Model']['common_field'] = implode(",", $this->data['Model'['field'];
unset($this->data['Model']['field']);
}
}

Categories