2012-09-02 5 views
4

Прежде всего, им совершенно новый для PHP и кодирования, но здесь идет.получить значение из раскрывающегося списка. (немного сложно)

У меня есть веб-форма, которая должна получить информацию из файла txt (находится в папке на сервере) У меня есть способ заставить его получить информацию из файла и как создать раскрывающийся список, показать все файлы в папке. Как бы то ни было, что я не могу понять, как заставить их работать вместе, поэтому имя файла, из которого он читается, берется из выбранного значения раскрывающегося списка.

код для списка:

<? 
$currentdir = 'files'; //change to your directory 
$dir = opendir($currentdir); 

echo 'Files are as follows:<br>'; 
echo '<select name="select">'; 
while($file = readdir($dir)) 
{ 
    echo '<option value="'.$file.'">'.$file.'</option>'; 
} 
echo '</select>'; 
closedir($dir); ?> 

и код для чтения из файла:

<input type="text" value="<?php $myFile = ""; $lines = file($myFile); echo $lines[2]; ?>" name="refnr" id="refnr" class="input" /> 

позволяет сказать, что падение вниз показывает 2 файла, test.txt и test2.txt , если я выберу test2.txt из раскрывающегося списка, мне захотелось поставить «test2.txt» между «» на <?php $myFile = ""; , но независимо от того, как я пытаюсь поставить код туда, чтобы получить выбранное значение, он просто не может ...

Полный код моей формы, как это прямо сейчас:

<?php 
if (!empty($_POST)) { 

    // Used for later to determine result 
    $success = $error = false; 

    // Object syntax looks better and is easier to use than arrays to me 
    $post = new stdClass; 

    // Usually there would be much more validation and filtering, but this 
    // will work for now. 
    foreach ($_POST as $key => $val) 
     $post->$key = trim(strip_tags($_POST[$key])); 

    // Check for blank fields 
    if (empty($post->refnr)) 
     $error = true; 

    else { 

     // Get this directory, to include other files from 
     $dir = dirname(__FILE__); 

     // Get the contents of the pdf into a variable for later 
     ob_start(); 
     require_once($dir.'/pdf.php'); 
     $pdf_html = ob_get_contents(); 
     ob_end_clean(); 

     // Load the dompdf files 
     require_once($dir.'/dompdf/dompdf_config.inc.php'); 

     $dompdf = new DOMPDF(); // Create new instance of dompdf 
     $dompdf->load_html($pdf_html); // Load the html 
     $dompdf->render(); // Parse the html, convert to PDF 
     $pdf_content = $dompdf->output(); // Put contents of pdf into variable for later 

     // Get the contents of the HTML email into a variable for later 
     ob_start(); 
     require_once($dir.'/html.php'); 
     $html_message = ob_get_contents(); 
     ob_end_clean(); 

     // Load the SwiftMailer files 
     require_once($dir.'/swift/swift_required.php'); 

     $mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer 

     $message = Swift_Message::newInstance() 
         ->setSubject('Felanmalan') // Message subject 
         ->setTo(array('[email protected]' => 'Fel')) // Array of people to send to 
         ->setFrom(array('[email protected]' => 'Fel')) // From: 
         ->setBody($html_message, 'text/html') // Attach that HTML message from earlier 
         ->attach(Swift_Attachment::newInstance($pdf_content, 'Felanmalan.pdf', 'application/pdf')); // Attach the generated PDF from earlier 

     // Send the email, and show user message 
     if ($mailer->send($message)) 
      $success = true; 
     else 
      $error = true; 

    } 

} 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
    <title>Felanm&auml;lan fr&aring;n IKEA</title> 
    <style type="text/css"> 
     html, body, h1, h2, h3, h4, h5, h6, p, span, ul, li, div, form, input, select, textarea, button {margin:0; padding:0;} 
     ul {list-style:none;} 
     a, a:hover {text-decoration:none; outline:0;} 
     a img {border:0;} 

     body {font:12px/16px Verdana, Arial, sans-serif; background:#ffffff;} 
     #container {width:450px; margin:10px auto; padding:10px; overflow:hidden; border:1px solid #000; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px; background:#F9F9F9;} 
     #container h1 {margin-bottom:20px; font-size:40px; line-height:40px; font-family:'HelveticaNeue-Light', 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight:normal;} 
     .message {margin-bottom:10px; padding:5px;} 
     .success {color:#4F8A10; border:1px solid #4F8A10; background:#DFF2BF;} 
     .error {color:#D8000C; border:1px solid #D8000C; background:#FFBABA;} 
     label {display:block; margin-bottom:3px; cursor:pointer;} 
     .input, textarea, select, button {display:block; width:440px; margin-bottom:10px; padding:3px; font:22px/22px 'HelveticaNeue-Light', 'Helvetica Neue', Helvetica, Arial, sans-serif; border:1px solid #CCC; border-top-width:2px;} 
     textarea {font-size:13px; line-height:16px;} 
     select {width:396px;} 
     button {float:right; width:auto; margin-bottom:0; padding:3px 30px; cursor:pointer; font-size:16px; border:1px solid #999; border-bottom-width:2px; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; background:#EEE;} 
     button:active {border-bottom-width:1px; padding:4px 30px 3px; background:#E9E9E9;} 
    </style> 
</head> 
<body> 
<? 
$currentdir = 'files'; //change to your directory 
$dir = opendir($currentdir); 

echo 'Files are as follows:<br>'; 
echo '<select name="select">'; 
while($file = readdir($dir)) 
{ 
    echo '<option value="'.$file.'">'.$file.'</option>'; 
} 
echo '</select>'; 
closedir($dir); ?> 

    <div id="container"> 

     <h1><img src="felimg.png" /> Felanm&auml;lan</h1> 

     <?php if ($success) { ?> 
      <div class="message success"> 
       <h4>Congratulations! It worked! Now check your email.</h4> 
      </div> 
     <?php } elseif ($error) { ?> 
      <div class="message error"> 
       <h4>Sorry, an error occurred. Try again!</h4> 
      </div> 
     <?php } ?> 

     <form method="post" action=""> 
      <label for="date"><b>Date:</b></label> 
      <input type="text" readonly name="date" id="date" class="input" value="<? print(Date("Y-m-d")); ?>"/> 

      <label for="refnr"><b>Referensnummer:</b></label> 
      <input type="text" value="<?php $myFile = ""; $lines = file($myFile); echo $lines[2]; ?>" name="refnr" id="refnr" class="input" /> 

      <label for="bestav"><b>Best&auml;lld av:</b></label> 
      <input type="text" name="bestav" id="bestav" class="input" />   

      <label for="tel"><b>Tel:</b></label> 
      <input type="text" name="tel" id="tel" class="input" /> 

      <label for="email"><b>Email:</b></label> 
      <input type="text" name="email" id="email" class="input" />   

      <label for="kund"><b>Kund:</b></label> 
      <textarea name="kund" id="kund" rows="4" cols="40"></textarea> 

      <label for="ktel"><b>Tel:</b></label> 
      <input type="text" name="ktel" id="ktel" class="input" /> 

      <label for="art"><b>Ber&ouml;rd Artikel:</b></label> 
      <textarea name="art" id="art" rows="3" cols="40"></textarea> 

      <label for="fel"><b>Fel p&aring; varan: </b></label> 
      <textarea name="fel" id="fel" rows="2" cols="40"></textarea> 

      <label for="q1"><b>Installation gjord av fackman:</b></label> 
      <select name="q1" id="q1"> 
       <option value="Ja">Ja</option> 
       <option value="Nej">Nej</option> 
      </select> 

      <label for="q2"><b>Serviceverkstad:</b></label> 
      <input type="text" name="q2" id="q2" class="input" /> 

      <label for="q3"><b>Servicenr:</b></label> 
      <input type="text" name="q3" id="q3" class="input" /> 

      <label for="q4"><b>Serienr:</b></label> 
      <input type="text" name="q4" id="q4" class="input" /> 

      <label for="q5"><b>Inom garanti eller reklamation:</b></label> 
      <select name="q5" id="q5"> 
       <option value="Garanti">Garanti</option> 
       <option value="Reklamation">Reklamation</option> 
      </select> 

      <label for="q6"><b>Informerat om punkt 8:</b></label> 
      <select name="q6" id="q6"> 
       <option value="Ja">Ja</option> 
       <option value="Nej">Nej</option> 
      </select>   

      <label for="q7"><b>Har kund sj&auml;lv g&aring;tt igenom manual f&ouml;r fels&ouml;kning:</b></label> 
      <select name="q7" id="q7"> 
       <option value="Ja">Ja</option> 
       <option value="Nej">Nej</option> 
      </select>    

      <label for="q8"><b>Ordernr:</b></label> 
      <input type="text" name="q8" id="q8" class="input" /> 

      <label for="q9"><b>Ink&ouml;psdatum:</b></label> 
      <input type="date" name="q9" id="q9" class="input" /><br> 


      <p><button type="submit">Submit!</button></p> 
     </form> 

    </div> 

</body> 
</html> 

надеюсь, что это имеет смысл и снова, извините, если окажется, что это вопрос noob :) Я использовал 2 дня поиска в Google и тестировании, и я просто подошел к точке, где мне нужно немного нажать в правильном направлении.

Заранее спасибо.

ps, ​​чтобы объяснить короткие мои цели, тогда у меня есть 1 веб-форма, которая генерирует txt-файл и сохраняет его на сервере, а затем другую форму, где «администратор» может выбрать файл из раскрывающегося списка, получить информация о том, что клиент заполнен в версии txt, а затем заполнить то, что ему нужно заполнить, а затем сохранить и отправить в PDF-файл техническому специалисту.

+0

Хотя не обязательно, с использованием базы данных может быть проще, вместо того, чтобы иметь дело с текстовыми файлами. – Jocelyn

+0

заменить '

ответ

1

Вы можете использовать

echo '<select id="select" name="select">'; 
while($file = readdir($dir)) 
{ 
    echo '<option value="'.$file.'">'.$file.'</option>'; 
} 
echo '</select>'; 

И после того, как он был загружен в DOM, используйте

document.getElementById('select').onchange=changeSelect; 
function changeSelect(){ 
    document.getElementById('refnr').value=document.getElementById('select').value; 
} 
changeSelect(); 

Посмотри здесь: http://jsfiddle.net/7nzBS/

+0

Спасибо, что работал так, как мне было нужно. – denully

+0

@denully Добро пожаловать :). Если мой ответ решит вашу проблему, не забудьте отметить его как принятый ответ. – Oriol

0
I wanted it to put "test2.txt" in between the "" at `<?php $myFile = ""` 

Вы не можете сделать такие вещь, потому что "text2.txt" находится на стороне клиента и $myfile, php переменная, находится на стороне сервера. Если вы хотите получить доступ к данным клиентской стороны со стороны сервера, вам необходимо отправить данные через HTTP. Таким образом, у вас есть два варианта:

  1. Послать выбранное значение с помощью HTTP после или получить.
  2. Отослать выбранное значение через AJAX.
+0

Прошу прощения, я, возможно, объяснил это немного неясно. Файл test2.txt также находится на сервере, все файлы есть. Когда клиент заполняет дату, в веб-форме он генерирует .txt-файл с информацией. Этот файл помещается в папку на сервере. Затем администратор (сторонник) может видеть файлы .txt из выпадающего меню, из своей веб-формы и оттуда, заполнить оставшуюся информацию, а затем сгенерировать из нее документ PDF, который будет отправлен на техник. – denully

0

Спасибо Ориоль, что работал :)

код теперь выглядит, как это и работает так, как мне нужно это. Также спасибо за все другие предложения, прекрасное с быстрыми и полезными ответами :)

  <label for="refnr"><b>Referensnummer:</b></label> 
     <input type="text" value="<?php $selectedfile = @$_POST['file2']; $myFile = "files/$selectedfile"; $lines = file($myFile); echo $lines[0]; ?>" name="refnr" id="refnr" class="input" /> 
Смежные вопросы