Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Dynamic html values

I have a dropdown in my Form:

class MyForm extends Phalcon\Forms\Form
{
    public function initialize($entity=null,$options=null){

    $mydrop = new Select ('mydrop', MyModel::find('some arguments'),array('using'=>array('id','name')));
    $this->add($mydrop);
}

Then in the index.volt:

    {{ form.render('mydrop'); }}
    <div class="prefill_1"></div>
    <div class="prefill_2"></div>

Controller:

class MyController extends Phalcon\Mvc\Controller
{
    public function indexAction(){
        $form = new MyForm();
        $this->view->form = $form;

        $mymodelslist = MyModel::find();
        $this->view->model_list = $mymodellist;
    }
}

MyModel has the following fields: id, name, adress1, address2. What I want to do is when the user selects a value from mydrop the volt references model_list to fill the two divs with address1 and address2 for the corresponding id selected in the dropdown.

I am sure this will require some ajax/jquery stuff but I am a serious n00b with that, so first off is this possible and if so how to do it? Thanks in advance!



17.9k

That looks like it describes sort of what I am trying to do but is there somewhere the complete source because just the snippets is sort of confusing... I have never done anything with ajax before so the full code would be very helpful



19.6k

You need an AJAX function that is called when you select a value (this is Jquery mode):

function myAJAX()
{
    $.ajax(
    {
        url:            '/url/to/your/action',
        dataType: 'JSON', // Or whatever you want.
        async:       false,    // This will ensure that the page will wait to AJAX to get completed.
        data:
        {
            // If you wanna send POST, do it here with 'var1AssociativeName: var1AssociativeValue', and so on.
        }
    })done(function (data)
    {
        // Fill DIV1 with the values of 'address1', appending in the desired way.
        // IDEM for DIV2 and 'address2'.
    });
}


17.9k

I have never written a line of ajax in my life. This should be interesting :(



19.6k
Accepted
answer

Download Jquery (is a JS file) and copy my function in a script tag below the downloaded file. In your action, create a new Phalcon\Http\Response() and do:

$response->setJsonContent(array(
    'address1' => $address1,
    'address2' => $address2
));

return $response;

Later, in the done(function (data)) of your AJAX:

done(function (data)
{
    // For each address1...
    DIV1.append('<p>' + address1 + '</p>').
    // IDEM for address2.
    // Also, doing a console.log(data['addressX']), you will see what vars are in.
});