I have an autocomplete field in my form that lets me select a contact name and associate it with a listing.
On the edit page however, it will display the contact ID and not his firstname and lastname.
How can I do that?
This is getEdit() method in ListingsController.php
public function getEdit($id)
{
// get the nerd
$listings = Listing::find($id);
$listings->images = Image::where('listing_id', $id)->get();
$ImagesFileName = "";
$listings->imagesFiles = "";
if ($listings->images) {
foreach ($listings->images as $CurImage) {
$ImagesFileName[] = $CurImage['image_name'];
}
$listings->imagesFiles = implode(",", $ImagesFileName) ;
}
$query = DB::table('contacts')->get();
foreach ($query as $firstname)
{
$name[] = $firstname->firstname." ".$firstname->lastname;
}
$fullname = json_encode($name);
// show the edit form and pass the nerd
$this->layout->content = View::make('listings/edit')
->with('listings', $listings)
->with('getClientsByLetters', $fullname);
}
This is action_getClientsByLetters() in ListingsController.php
public function action_getClientsByLetters() {
$term = Input::get('query');
$data = array();
$query = DB::query("
SELECT * FROM contacts
WHERE MATCH (contact)
AGAINST('+".$term."*' IN BOOLEAN MODE)
");
foreach ($query as $results => $contact) {
$data[] = array(
'id' => $contact->id,
'value' => $contact->firstname
);
}
return json_encode($data);
}
This is the field in views/listings/edit.blade.php
<p>{{ Form::text('contact_id', null, array('class'=>'form-control', 'placeholder'=>'Contact Name', 'id'=>'contact', 'onblur'=>'test()')) }}</p>
And this is the javascript code on the same view
$(function() {
var availableTags = <?php echo $getClientsByLetters; ?>;
$( "#contact" ).autocomplete({
source: availableTags,
minLength: 2,
});
});
I think this is just a problem of approach. Normally I would just set up this kind of field as a SELECT control, using the ID as the key field and the name as the displayed option values. In all modern browsers you get progressive autocomplete on SELECT controls by default. One important question, however, is whether you are intending users to be able to add arbitrary new names to this field, or if it is intended to only allow existing names with assigned IDs to be entered. In the latter case then yes, we probably need to figure out how to get your autocomplete text field to work instead.
Your action_getClientsByLetters looks close, but I don't think it's ever being run.
Autocomplete is accepting an array of strings or an array of objects where each object has both a label and a value, which I think is what you should be aiming for.
With that in mind, I'd add a function whose sole responsibility is to fetch the contacts and put them in the required form that autocomplete is expecting, which you would probably be using the array of objects because it looks like your going to need the ID later.
function getContacts()
{
$contacts = Contact::all();
$autoComplete = array();
foreach($contacts as $contact) {
$autoComplete[]['label'] = $contact->first_name . ' ' . $contact->last_name;
$autoComplete[]['value'] = $contact->id;
}
return json_encode($autoComplete);
}
Then you'd call the view with...
$this->layout->content = View::make('listings/edit')
->with('listings', $listings)
->with('getClientsByLetters', $this->getContacts());
Related
I am using JQuery Datatables to display all the users of my forum in a page from a table called 'users'. I am using Code Igniter for server-side processing. I looked up the Datatables documentation on how to render data and I got it going. However, I have some PHP variables and functions that I want to echo into a JavaScript variable so I can use them within the render function for the target column. However, I am wondering how to echo a model function from a different table with a parameter into the JavaScript variable, or whether that is even a good approach. Below is my set-up. I have only posted the lines that are relevant to this question (unless I am doing it all wrong).
Model (Dashboard_model)
public function my_followee($followee) {
$username = $this->session->username;
return $this->db->get_where('followers', array('user' => $followee, 'follower' => $username))->row_array();
}
JS:
{
"targets": [-1],
"data": null,
"orderable": false,
"render": function ( data, type, full ) {
var myself = "<?php echo $this->session->username; ?>";
var is_following = "<?php echo $this->dashboard_model->my_followee('+full[1]+');" //full[1] is username column
if(is_following == false && myself !== full[1]) {
return Follow ';
} else if(is_following == true && myself !== full[1]) {
return Unfollow ';
} else if(myself == full[1]) {
return 'This is you';
}
}
}
Basically, I want to check if the loggedin user is already following the currently selected user. If no, show follow button, otherwise, show unfollow button.
When I check the page, all the buttons have follow (except the currently logged in user), whereas some should return true and show unfollow. I suspect I'm violating syntax rules in this line:
var is_following = "<?php echo $this->dashboard_model->my_followee('+full[1]+');"
I am new to JQuery and Datatables and can't seem to figure out the right way to do this. Please can someone point me to the right direction, or suggest better ways of achieving my aim? I would really appreciate the help.
EDIT
I tried this in my controller that handles the ajax call request
public function users_ajax_list()
{
$this->load->model('user/users_model', 'users');
$this->load->model('dashboard_model');
$list = $this->users->get_users();
$data = array();
foreach ($list as $user) {
if ($this->dashboard_model->my_followee($user->username) == true) {
$is_following = true;
} else {
$is_following = false;
}
$row = array();
$row[] = $user->profile_image;
$row[] = $user->username;
$row[] = ucfirst($user->surname);
$row[] = ucfirst($user->first_name);
$row[] = ucfirst($user->state);
$row[] = ucfirst($user->lga);
$row[] = $user->followers;
$row[] = $user->following;
$row[] = $user->total_posts;
$row[] = $user->gender;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->users->count_all_users(),
"recordsFiltered" => $this->users->count_filtered_users(),
"data" => $data,
);
//output to json format
echo json_encode($output);
echo json_encode($is_following);
}
It produced errors: wrong JSON response. What am I doing wrong? And how is the best way to do it? And how can I access the JSON variable within the render function for the targeted column.
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.
I have a simple dropdown field with 2 values and a dependent dropdown field:
public function areaForm() {
$datasource = function($val) {
if ($val =='yes') {
$areas = DataObject::get('Area', 'ParentID = 0');
return $areas->map('ID', 'Name');
}
if ($val == 'no') {
return false;
}
};
$fields = new FieldList(
TextField::create('Name', 'Area Name:'),
$dropField = DropdownField::create('isChild', 'Is this a sub Area?', array('yes' => 'Yes', 'no'=>'No' ))
->setEmptyString('Select one'),
DependentDropdownField::create('ParentSelect', 'Select Parent Area:', $datasource)
->setDepends($dropField)
->setEmptyString('Select one')
);
return new Form($this, __FUNCTION__, $fields, FieldList::create(new FormAction('doSaveArea', 'Save area')));
}
public function doSaveArea($data, $form) {
var_dump($data);
exit;
$name = $data['Name'];
$isChild = $data['isChild'];
if ($isChild === 'no') {
$area = new Area();
$area->Name = $name;
$area->ParentID = 0;
$area->write();
}
elseif ($isChild === 'yes') {
$area = new Area();
$area->Name = $name;
$area->ParentID = $data['ParentSelect'];
$area->write();
}
$this->redirectBack();
}
When ever I try to save my object by submitting the form, it gives me the same message:
Please select a value within the list provided. x is not a valid option
The values are being populated correctly. I can see them in the browser by inspecting the element. Yet if I select ID 1 for example it says "1 is not a valid option" etc for each Area object. It gets stuck at validation, doesn't even go to the action. I've done similar things in other parts of the site/other sites and they work fine.
Why is this validation incorrectly blocking the form submission and how do we fix this?
Seems like you just need to create an Array of your Map object.
if ($val =='yes') {
$areas = Area::get()->filter('ParentID', '0');
return $areas->map('ID', 'Name')->toArray();
}
Normally you could just use the Map object as the source for a DropdownField. But I think the DependentDropdownField has a little trouble with the Map object.
I have problems with a submit form (or with the routing design) that deletes N table based on id.
I've a made a simple routing function that use the index php file:
function relativeRouter ($controller,$action,$query_data=""){
$param = is_array($query_data) ? http_build_query($query_data) : "$query_data";
$url = "index.php?controller=$controller&action=$action&$param";
return $url;
The index create instances of controllers using controller=?&action=?.
It also bind the POST/GET params to the methods arguments (in an array, $params). (im already aware to not use directly calls to superglobals)
$params=array();
if(isset($_GET['controller'])&&isset($_GET['action'])){
$c = $_GET['controller'];
$a = $_GET['action'];
// add all query string additional params to method signature i.e. &id=x&category=y
$queryParams = array_keys($_GET);
$queryValues = array_values($_GET);
for ($i=2;$i<count($queryParams);$i++) {
$params[$queryParams[$i]] = $queryValues[$i];
}
if ($_POST) {
print_r($_POST); // THIS CONTAINS ONLY 1 PASSED ID.
// add all query string additional params to method signature i.e. &id=x&category=y
$queryParams = array_keys($_POST);
$queryValues = array_values($_POST);
for ($i=0;$i<count($_POST);$i++) {
$params[$queryParams[$i]] = $queryValues[$i];
}
}
include_once APP_ROOT."/controller/$c.php";
$controller = new $c();//CombustibiliController
$controller->$a($params);//inserimento
} else {
//attiva controller predefinito
$controller = new Admin();
$controller->index();
}
The routing works well in a form with different HTML form item names. (name='') but i'm expriencing problems by passing an array of id that are used for a multi-checkbox delete.
The $_POST is arriving with an array with only one items instead of many :
Array ( [ids] => 110 )
While works with no hassle with the insert form:
Array ( [title] => 435 [desc] => 5534 )
Here the table view:
<?php
if (isset($products)) {
$action = relativeRouter("ProductsController", "deleteProducts");
$html="<form id='multiselect' action='$action' method='POST'>\n";
foreach ($products as $product) {
$html.= "<tr>\n"
."<td><input type='checkbox' name='ids' value='".$product->id."'></td>\n"
."<td>".$product->id."</td>\n"
."<td>".$product->title."</td>\n"
."<td>".$product->description."</td>\n"
."<td>".$product->image."</td>\n"
."</tr>\n";
}
$html.="</form>\n";
echo $html;
}
?>
And here the jQuery that runs the form from a button:
<script>
function send() {
$('#multiselect').submit();
$('.play-confirm-modal').modal('hide');
}
$('.play-crud-delete').on('click',function(){
var checked = $( "input:checkbox:checked" ).length;
if(checked>0) {
$('.play-confirm-modal').modal('show');
console.log(checked);
} else {
alert("No selected checkboxes");
}
});
</script>
Hope someone can help. Firefox networks show module params but the POST only contains one of them, always the last.
<input type='checkbox' name='ids[]' value='".$product->id."'>
replace this and check. name should contain array operator for multivalue
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']);
}
}