lundi 28 décembre 2015

Get selected value from a dropdown L-5.1 using JavaScript

I'm trying to get the selected value using Javascript and sending the value to the server side so as to process it using Laravel - PHP. This is ocde I've written so far, but I'm not getting it at the server side, is there anything I need to do more?

This is the blade file:

{!! Form::open(array('url' => 'created-products', 'method' => 'post'), array('id'=>'createproduct')) !!}
{!! Form::token() !!}

    @if(!Auth::check())
        <p><h3>Please login to create product</h3></p>
        @else
            <p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies, null, array('id'=>'companynameId')) !!} </p>
            <p>{!! Form::text('productname', Input::old('productname')) !!}</p>
            <p>{!! Form::hidden('hiddenCompanyName', '', array('id'=>'selectedCompanyHidden')) !!}</p>
            <p>{!! Form::submit('CREATE PRODUCT') !!}</p>

    @endif

    <script>
        var returnedCompany = document.getElementById("companynameId");
        var storedCompany = returnedCompany.options[returnedCompany.selectedIndex].value;

        var hiddenCompanyId = document.getElementsByName('hiddenCompanyName');
        document.createproduct.hiddenCompanyId.value = storedCompany;
        document.forms["createproduct"].submit();
    </script>
{!! Form::close() !!}

This is the function to get the value from the blade file:

private static function compareCompany(ProductRequest $productRequest){
        $companyPicked = $productRequest->hiddenCompanyName;
        $listedCompanies = Company::where('user_id', '=', Auth::user()->id);
        $companies = new Company;
        if($companies->user_id === Auth::user()->id)
        {   
            foreach($listedCompanies as $company) {
                if($company->companyname === $companyPicked)
                {
                    return $company->id;
                } 
            }
        }
    }

This is the function to save it into the DB.

public function store(ProductRequest $productRequest)
{
   $product = new Product;
    $company = new Company;
   if($productRequest->isMethod('post')){

   $product->user_id     = Auth::user()->id;
   $product->company_id  = $this->compareCompany($productRequest);
   $product->companyname = $productRequest->companyname;
   $product->productname = $productRequest->productname;

   $product->save();
   return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
   }else{
        return redirect('company-create')->withErrors($productRequest)->withInput();
    }
}

Please help out. I've been on this for days. Appreciate.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire