jquery ui autocomplete not populating from remote datasource - jquery-ui

My first stackoverflow post! So I cannot figure out why this is not working. It was working in the past but it does not now, don't know what changed. The JSON is returning correctly it's just not populating the drop down.
Here is the html:
$(document).ready(function(){
$('#search').autocomplete({
source: 'search.php',
minLength: 2
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="search">Search</label>
<input type="text" id="search" />
</div>
</body>
Here is the PHP:
mysql_select_db('symfony',$con);
$autocomplete_value = mysql_real_escape_string($_GET["term"]);
$sql = "SELECT name FROM Artist WHERE name LIKE '%$autocomplete_value%' UNION
SELECT name FROM Event WHERE name LIKE '%$autocomplete_value%'";
$query = mysql_query($sql);
echo $sql;
$results = array();
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
array_push($results, array( 'name' => $row['name']) );
}
json_encode($results);
?>
EDIT**
My coworker helped me figure it out. I need to change
array_push($results, array( 'name' => $row['name']) );
to
array_push($results, array( 'value' => $row['name']) );
Now it works!

Related

Unable to access mutator functions in Wizard form page while using react-final-form

I am trying to create a Wizard form using react-final-form by referring to this code https://codesandbox.io/s/km2n35kq3v. For my use case I need some mutator functions to be used inside my form fields. This example illustrates how to do that - https://codesandbox.io/s/kx8qv67nk5?from-embed.
I am not sure how to access mutator functions in my form steps when I am using a wizard form instead of a single page form.
I tried to combine both the examples by modifying the <Form> component rendered by Wizard.js to pass in the mutators. However I cannot access these mutators in the Wizard form pages.
In Wizard.js
return (
<Form
mutators={{
// potentially other mutators could be merged here
...arrayMutators,
}}
render={({
handleSubmit,
submitting,
values,
pristine,
invalid,
form: {
mutators: {push, pop, remove},
},
}) => {
return (
<form onSubmit={handleSubmit}>
Another file index.js
<Wizard
initialValues={{ employed: true, stooge: "larry" }}
onSubmit={onSubmit}
>
<Wizard.Page>
<FieldArray name="customers">
{({ fields }) =>
fields.map((name, index) => (
<div key={name}>
<label>Cust. #{index + 1}</label>
<Field
name={`${name}.firstName`}
component="input"
placeholder="First Name"
/>
<span
onClick={() => fields.remove(index)}
style={{ cursor: "pointer" }}
>
❌
</span>
</div>
))
}
</FieldArray>
</Wizard.Page>
</Wizard>
It errors out - remove is undefined in index.js
Look at this working example: https://codesandbox.io/s/znzlqvzvnx
changes I have made:
Wizard.js
static Page = ({ children, mutators }) => {
if(typeof children === 'function'){
return children(mutators);
}
return children;
};
...
<form onSubmit={handleSubmit}>
{
// activePage
<activePage.type {...activePage.props} mutators={mutators} />
}
...
index.js (only first <Wizard.page>)
<Wizard.Page>
{
({ upper }) => (
<React.Fragment>
<div>
<label>First Name</label>
<Field
name="firstName"
component="input"
...
</div>
</React.Fragment>
)
}
</Wizard.Page>

Laravel 5.5 autocomplete method returns a 500 error in one place not another

I have a simple form to get an autocomplete of an author's name from a table of several thousand.
In my simple form I have:
<form>
<div class="ui-widget">
<label for="authors">authors: </label>
<input id="authors" value="">
</div>
</form>
The javascript is:
<script>
$(function()
{
$( "#authors" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
I have a route pointing to a controller:
Route::get('autocompleteAuthors','AutoCompleteController#authors')->name('autocompleteAuthors');
and a function in the controller:
public function authors()
{
$term = Input::get('term');
$results = array();
$queries = DB::table('author')
->where('name', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->name];
}
return Response::json($results);
}
This works fine.
In a form to edit a quote (part of the edit could be the author) I have the following:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
</div>
and the javascript is:
<script>
$(function()
{
$( "#author" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
So they are both sending "term" to the same route yet in the second case I get a 500 error.
Can't see any reason for this!
I managed to sort it out. If you set the value in
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
everything fails.
The answer is very simple: set it after the ui is called.
So my form includes:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" style="width:50%">
</div>
and I invoke the ui with
$(function() {
$( "#author" ).autocomplete({
source: "{{ route('autocompleteAuthors') }}",
minLength: 3,
select: function(event, ui) {
$('#q').val('ui.item.value');
}
});
});
and then I add the initial value:
$( "#author" ).val("{{ $author[0]['name'] }}");

A public action method 'ABC' was not found on controller xyz

Background:
I'm doing some changes in already implemented project, Which uses MVC, Kendo Grid.And there is onePost action method called EmployeeSearchByName which takes one string parameter 'Name'.Kendo Grid's pages size is 10 records per page, when I search someones name control properly goes to that action and it fetches the employee according name and shows it in kendo grid but when I click on next page in kendo then I get the error 'A public action method 'EmployeeSearchByName ' was not found on controller xyz'.
Code Of View:
#model Silicus.Finder.Web.ViewModel.EmployeesViewModel
#using Kendo.Mvc.UI;
#using Silicus.Finder.Models.DataObjects;
<link href="~/Content/css/FinderStyle.css" rel="stylesheet" />
#{
ViewBag.Title = "Employees List";
var message = TempData["AlertMessage"] ?? string.Empty;
var importMessage = Session["ImportEmployee"] ?? string.Empty;
Session["ImportEmployee"] = string.Empty;
}
<link href="~/Content/MyKendoStyle.css" rel="stylesheet" />
<link href="~/Content/css/FinderStyle.css" rel="stylesheet" />
<div class="container-fluid" style="padding-right: 0px;padding-left: 0px;">
<div id="modal-container" class="k-popup" tabindex="-1" role="dialog" style="border-style: hidden;margin-top:-100px">
<div class="modal-content" style=" position:fixed !important;z-index:auto;width:97%;">
</div>
</div>
</div>
<div id="adv" class="container-fluid" style="margin-left: 3%;">
<div class="ContainerPanel">
<div>
<span style="color:black; font-weight: bold;">Advanced Search</span>
<div class="header1 pull-right">
<img src="~/Images/Project/down-arrow.png" style="height:20px; margin-top: -3px;" />
</div>
<div class="content">
<br />
#using (Html.BeginForm("GetEmployeesByCriteria", "Employee", FormMethod.Post))
{
var model = Model.SearchCriteria;
var i = 0;
if (i == 0)
{
#Html.EditorFor(modelItem => model, new { htmlAttributes = new { #class = "form-control" } });
++i;
}
}
</div>
</div>
</div>
</div>
<div id="Grid" class="container-fluid" style="margin: 0.5% 3% 0.5% 3%;">
#(Html.Kendo().Grid((IEnumerable<Silicus.Finder.Web.ViewModel.EmployeesListViewModel>)Model.Employees)
.Name("employeeListGrid")
.Columns(columns =>
{
columns.Bound(employee => employee.FullName).Template(#<label>
#Html.ActionLink(item.FullName, "Details", "Employee", new { id = item.EmployeeCode }, new { #class = "modal-link" })
</label>
);
columns.Bound(employee => employee.EmployeeCode).Title("Employee Code");
columns.Bound(employee => employee.Title);
columns.Bound(employee => employee.HighestQualification).Sortable(false);
columns.Bound(employee => employee.EmployeeType).Sortable(false);
columns.Bound(employee => employee.TotalExperienceInMonths);
columns.Bound(employee => employee.SilicusExperienceInMonths).Sortable(false);
})
.Scrollable(scr => scr.Height(300))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Sortable(sortable => sortable.AllowUnsort(false))
)
</div>
#Scripts.Render("~/bundles/jquery")
<script>
//Details Modal Popup
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
$('#Grid').toggle();
$('#adv').toggle();
});
$('body').on('click', '.modal-close-btn', function () {
$('#modal-container').modal('hide');
});
$('#modal-container').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
$('#CancelModal').on('click', function () {
return false;
});
});
$(document).ready(function () {
$("#modal-container").hide();
$("#dialog-import-employee").hide();
});
$(window).load(function () {
$('#moduleHeaderTitleOnDashBoardImage').text("Employees");
$('#modal-container').hide();
});
$(".header1").click(function () {
$(".ContainerPanel").toggleClass("advance-width");
$header = $(this);
$content = $header.next();
$content.slideToggle(1, function () {
});
});
</script>
Question:How to resolve this ?
Kendo grid sends additional parameters which are used for its sorting & filtering.
Try to rewrite your action method like this:
public JsonResult GetIndexContent([DataSourceRequest]DataSourceRequest request, SearchCriteriaViewModel searchCriteria)
{
// your logic ... + return json
}
What we did additionally was telling the GridBuilder which Read method it should use. You even have the possibility to add searchCriteria as parameters;
.DataSource(datasource => datasource
.Ajax()
.Model(model => model.Id("Id"))
.Read(read => read.Action("GetIndexContent", "YourControllerName").Data(fetchSearchCriteriaMethodName))
.PageSize(10)
);
The JavaScript function 'fetchSearchCriteriaMethodName' should just return your search criteria as a JSON object.

POST working wierdly in yii2

Below given is the code for my view
<div class="col-md-6">
<?php
if($fanclub_count<2)
{?>
<?php $form = ActiveForm::begin();?>
<?= $form->field($model_fanclub, 'crew_member_id')->dropDownList(ArrayHelper::map(MovieCrewMembers::find()->all(),
'id', 'name'),['prompt'=>'Select Crew','style'=>'width:50%']) ?>
<?= Html::submitButton(Yii::t('app', 'Join'),
['class' =>'btn btn-success']) ?>
<?php ActiveForm::end();
}?>
</div>
<div class="col-md-6">
<?php
if($user_clubs!=null)
{
foreach($user_clubs as $active_clubs )
{
$image= '/movie_crew_members/' . $active_clubs[0]."_".$active_clubs[2];
$path = \Yii::$app->thumbler->resize($image,55,55,Thumbler::METHOD_NOT_BOXED,true);
?>
<div class="col-md-6">
<img src="cache/<?php echo $path?>"></br>
<a href="<?php echo \Yii::$app->getUrlManager()->createUrl( [ '/users/change_fanclub',
'id'=>$active_clubs[0],'userid'=>$user_id] ); ?>">
<i class="fa fa-times-circle-o fa-2x"></i></a>
</div>
<?php
}
}
else
{
echo "No Active Clubs";
}
?>
</div>
there are basically two things a dropdown box and a image with a icon which redirect to a action. Sometimes it works perfect sometimes not. ie,when i click the drop down it gets redirected to users/change_fanclub. how is it possible? dropdown is independent of action users/change_fanclub. then how come it get redirected there?
I solved the problem by using this
<?php
$form = ActiveForm::begin( [
'method' => 'post',
'action' => [ "users/profile","user_id"=>$user_id ],
] );
?>
i don't know why i got redirected to users/change_fanclub when i click on the submit button of model_fanclub instead of going to users/profile. But i removed the error by specifying the action in ActiveForm.

Symfony merge two forms that have a field with the same name

Hi I have two forms, a Specification form and a Source form.
I'm merging the two forms into one so that users can submit a specification and the source of the specification at the same time.
The problem is that the specification table has a field called name and the source table has a field called name. So, when creating the forms and merging, I have two name fields that should refer to two different things, the specification name and the source name. Any way to get around this without restructuring the model/database?
class NewsLinkForm extends BaseNewsLinkForm
{
public function configure()
{
unset($this['id']);
$link = new SourceForm();
$this->mergeForm($link);
$this->useFields(array('name', 'source_url'));
$this->setValidators(array(
'source_url' => new sfValidatorUrl(),
));
$this->validatorSchema->setOption('allow_extra_fields', true);
}
}
class SourceForm extends BaseLimelightForm
{
public function configure()
{
$this->useFields(array('name'));
$this->setWidgets(array(
'name' => new sfWidgetFormInputText(array(),
array(
'class' => 'source_name rnd_3',
'maxlength' => 50,
'data-searchahead' => url_for('populate_sources_ac'),
'data-searchloaded' => '0'
)),
));
$this->setValidators(array(
'name' => new sfValidatorString(array('trim' => true, 'required' => true, 'min_length' => 3, 'max_length' => 50)),
));
$this->widgetSchema->setNameFormat('source[%s]');
}
}
<h5>add specification</h5>
<div class="item">
<?php echo $specificationForm['name']->renderLabel() ?>
<?php echo $specificationForm['name']->render(array('data-searchahead' => url_for('populate_lime_specifications_ac'), 'data-searchloaded' => '0')) ?>
</div>
<div class="item">
<?php echo $specificationForm['content']->renderLabel() ?>
<?php echo $specificationForm['content']->render(array('data-searchahead' => url_for('populate_specifications_ac'), 'data-searchloaded' => '0')) ?>
</div>
<div class="clear"></div>
<div class="item">
<?php echo $specificationForm['name']->renderLabel() ?>
<?php echo $specificationForm['name']->render() ?>
</div>
<div class="item">
<?php echo $specificationForm['source_url']->renderLabel() ?>
<?php echo $specificationForm['source_url']->render() ?>
</div>
You could try this piece of code:
// rename the name field of the first form
$sourceForm->setWidget('source_name', $sourceForm->getWidget('name'));
unset($this['name']);
// merge
$newsLinkForm->mergeForm($sourceForm);

Resources